blob: 2f7acba595c22e3931cfb7d3922301d87cb7ae85 [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;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100198import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700199import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700201import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.SystemClock;
203import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.UserManager;
208import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700209import android.os.storage.IStorageManager;
210import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.provider.Settings;
212import android.service.voice.IVoiceInteractionSession;
213import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900214import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.telecom.TelecomManager;
216import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100217import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700219import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.EventLog;
221import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700222import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700224import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700249import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700250import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700251import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.LocalServices;
253import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700254import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800255import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700257import com.android.server.am.ActivityManagerService;
258import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
259import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
260import com.android.server.am.AppTimeTracker;
261import com.android.server.am.BaseErrorDialog;
262import com.android.server.am.EventLogTags;
263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900266import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700305 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700306 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800376 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
379 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
553 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Ricky Wai96f5c352019-04-10 18:40:17 +0100661 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private final class FontScaleSettingObserver extends ContentObserver {
664 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
665 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
666
667 public FontScaleSettingObserver() {
668 super(mH);
669 final ContentResolver resolver = mContext.getContentResolver();
670 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
671 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
672 UserHandle.USER_ALL);
673 }
674
675 @Override
676 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
677 if (mFontScaleUri.equals(uri)) {
678 updateFontScaleIfNeeded(userId);
679 } else if (mHideErrorDialogsUri.equals(uri)) {
680 synchronized (mGlobalLock) {
681 updateShouldShowDialogsLocked(getGlobalConfiguration());
682 }
683 }
684 }
685 }
686
Riddle Hsua0536432019-02-16 00:38:59 +0800687 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
688 @Target(ElementType.METHOD)
689 @Retention(RetentionPolicy.SOURCE)
690 @interface HotPath {
691 int NONE = 0;
692 int OOM_ADJUSTMENT = 1;
693 int LRU_UPDATE = 2;
694 int PROCESS_CHANGE = 3;
695 int caller() default NONE;
696 }
697
Charles Chen8d98dd22018-12-26 17:36:54 +0800698 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
699 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700700 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700701 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700702 mSystemThread = ActivityThread.currentActivityThread();
703 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700704 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800705 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700706 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700707 }
708
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700709 public void onSystemReady() {
710 synchronized (mGlobalLock) {
711 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
712 PackageManager.FEATURE_CANT_SAVE_STATE);
713 mAssistUtils = new AssistUtils(mContext);
714 mVrController.onSystemReady();
715 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700716 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700718 }
719
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700720 public void onInitPowerManagement() {
721 synchronized (mGlobalLock) {
722 mStackSupervisor.initPowerManagement();
723 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
724 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
725 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
726 mVoiceWakeLock.setReferenceCounted(false);
727 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700731 mFontScaleSettingObserver = new FontScaleSettingObserver();
732 }
733
Wale Ogunwale59507092018-10-29 09:00:30 -0700734 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean freeformWindowManagement =
736 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
737 || Settings.Global.getInt(
738 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
739
740 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
741 final boolean supportsPictureInPicture = supportsMultiWindow &&
742 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
743 final boolean supportsSplitScreenMultiWindow =
744 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
745 final boolean supportsMultiDisplay = mContext.getPackageManager()
746 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
748 final boolean forceResizable = Settings.Global.getInt(
749 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
750
751 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900752 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753
754 final Configuration configuration = new Configuration();
755 Settings.System.getConfiguration(resolver, configuration);
756 if (forceRtl) {
757 // This will take care of setting the correct layout direction flags
758 configuration.setLayoutDirection(configuration.locale);
759 }
760
761 synchronized (mGlobalLock) {
762 mForceResizableActivities = forceResizable;
763 final boolean multiWindowFormEnabled = freeformWindowManagement
764 || supportsSplitScreenMultiWindow
765 || supportsPictureInPicture
766 || supportsMultiDisplay;
767 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
768 mSupportsMultiWindow = true;
769 mSupportsFreeformWindowManagement = freeformWindowManagement;
770 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
771 mSupportsPictureInPicture = supportsPictureInPicture;
772 mSupportsMultiDisplay = supportsMultiDisplay;
773 } else {
774 mSupportsMultiWindow = false;
775 mSupportsFreeformWindowManagement = false;
776 mSupportsSplitScreenMultiWindow = false;
777 mSupportsPictureInPicture = false;
778 mSupportsMultiDisplay = false;
779 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700780 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700781 // This happens before any activities are started, so we can change global configuration
782 // in-place.
783 updateConfigurationLocked(configuration, null, true);
784 final Configuration globalConfig = getGlobalConfiguration();
785 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
786
787 // Load resources only after the current configuration has been set.
788 final Resources res = mContext.getResources();
789 mThumbnailWidth = res.getDimensionPixelSize(
790 com.android.internal.R.dimen.thumbnail_width);
791 mThumbnailHeight = res.getDimensionPixelSize(
792 com.android.internal.R.dimen.thumbnail_height);
793
794 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
795 mFullscreenThumbnailScale = (float) res
796 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
797 (float) globalConfig.screenWidthDp;
798 } else {
799 mFullscreenThumbnailScale = res.getFraction(
800 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
801 }
802 }
803 }
804
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800805 public WindowManagerGlobalLock getGlobalLock() {
806 return mGlobalLock;
807 }
808
Yunfan Chen585f2932019-01-29 16:04:45 +0900809 /** For test purpose only. */
810 @VisibleForTesting
811 public ActivityTaskManagerInternal getAtmInternal() {
812 return mInternal;
813 }
814
Riddle Hsud93a6c42018-11-29 21:50:06 +0800815 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
816 Looper looper) {
817 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700818 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700819 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700820 final File systemDir = SystemServiceManager.ensureSystemDir();
821 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
822 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824
825 mTempConfig.setToDefaults();
826 mTempConfig.setLocales(LocaleList.getDefault());
827 mConfigurationSeq = mTempConfig.seq = 1;
828 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800829 mRootActivityContainer = new RootActivityContainer(this);
830 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700831
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700834 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700836 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700837 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700838 mKeyguardController = mStackSupervisor.getKeyguardController();
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void onActivityManagerInternalAdded() {
842 synchronized (mGlobalLock) {
843 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
844 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
845 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700846 }
847
Yunfan Chen75157d72018-07-27 14:47:21 +0900848 int increaseConfigurationSeqLocked() {
849 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
850 return mConfigurationSeq;
851 }
852
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700853 protected ActivityStackSupervisor createStackSupervisor() {
854 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
855 supervisor.initialize();
856 return supervisor;
857 }
858
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 public void setWindowManager(WindowManagerService wm) {
860 synchronized (mGlobalLock) {
861 mWindowManager = wm;
862 mLockTaskController.setWindowManager(wm);
863 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800864 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700865 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700866 }
867
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700868 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
869 synchronized (mGlobalLock) {
870 mUsageStatsInternal = usageStatsManager;
871 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700872 }
873
Wale Ogunwalef6733932018-06-27 05:14:34 -0700874 UserManagerService getUserManager() {
875 if (mUserManager == null) {
876 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
877 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
878 }
879 return mUserManager;
880 }
881
882 AppOpsService getAppOpsService() {
883 if (mAppOpsService == null) {
884 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
885 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
886 }
887 return mAppOpsService;
888 }
889
890 boolean hasUserRestriction(String restriction, int userId) {
891 return getUserManager().hasUserRestriction(restriction, userId);
892 }
893
Michal Karpinski15486842019-04-25 17:33:42 +0100894 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
895 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
896 callingUid, callingPackage);
897 if (mode == AppOpsManager.MODE_DEFAULT) {
898 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
899 == PERMISSION_GRANTED;
900 }
901 return mode == AppOpsManager.MODE_ALLOWED;
902 }
903
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700904 @VisibleForTesting
905 protected void setRecentTasks(RecentTasks recentTasks) {
906 mRecentTasks = recentTasks;
907 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700908 }
909
910 RecentTasks getRecentTasks() {
911 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700912 }
913
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700914 ClientLifecycleManager getLifecycleManager() {
915 return mLifecycleManager;
916 }
917
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700918 ActivityStartController getActivityStartController() {
919 return mActivityStartController;
920 }
921
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700922 TaskChangeNotificationController getTaskChangeNotificationController() {
923 return mTaskChangeNotificationController;
924 }
925
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700926 LockTaskController getLockTaskController() {
927 return mLockTaskController;
928 }
929
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 /**
931 * Return the global configuration used by the process corresponding to the input pid. This is
932 * usually the global configuration with some overrides specific to that process.
933 */
934 Configuration getGlobalConfigurationForCallingPid() {
935 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800936 return getGlobalConfigurationForPid(pid);
937 }
938
939 /**
940 * Return the global configuration used by the process corresponding to the given pid.
941 */
942 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900943 if (pid == MY_PID || pid < 0) {
944 return getGlobalConfiguration();
945 }
946 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100947 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900948 return app != null ? app.getConfiguration() : getGlobalConfiguration();
949 }
950 }
951
952 /**
953 * Return the device configuration info used by the process corresponding to the input pid.
954 * The value is consistent with the global configuration for the process.
955 */
956 @Override
957 public ConfigurationInfo getDeviceConfigurationInfo() {
958 ConfigurationInfo config = new ConfigurationInfo();
959 synchronized (mGlobalLock) {
960 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
961 config.reqTouchScreen = globalConfig.touchscreen;
962 config.reqKeyboardType = globalConfig.keyboard;
963 config.reqNavigation = globalConfig.navigation;
964 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
965 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
966 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
967 }
968 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
969 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
970 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
971 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700972 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900973 }
974 return config;
975 }
976
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700977 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700978 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700979 }
980
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700981 public static final class Lifecycle extends SystemService {
982 private final ActivityTaskManagerService mService;
983
984 public Lifecycle(Context context) {
985 super(context);
986 mService = new ActivityTaskManagerService(context);
987 }
988
989 @Override
990 public void onStart() {
991 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700992 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 }
994
Garfield Tan891146c2018-10-09 12:14:00 -0700995 @Override
996 public void onUnlockUser(int userId) {
997 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800998 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700999 }
1000 }
1001
1002 @Override
1003 public void onCleanupUser(int userId) {
1004 synchronized (mService.getGlobalLock()) {
1005 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1006 }
1007 }
1008
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001009 public ActivityTaskManagerService getService() {
1010 return mService;
1011 }
1012 }
1013
1014 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 public final int startActivity(IApplicationThread caller, String callingPackage,
1016 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1017 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1018 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1019 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1020 UserHandle.getCallingUserId());
1021 }
1022
1023 @Override
1024 public final int startActivities(IApplicationThread caller, String callingPackage,
1025 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1026 int userId) {
1027 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001028 enforceNotIsolatedCaller(reason);
1029 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001031 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1032 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1033 reason, null /* originatingPendingIntent */,
1034 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 }
1036
1037 @Override
1038 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1039 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1040 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1041 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1042 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1043 true /*validateIncomingUser*/);
1044 }
1045
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001046 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1048 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1049 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001050 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001052 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001053 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1054
1055 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001056 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 .setCaller(caller)
1058 .setCallingPackage(callingPackage)
1059 .setResolvedType(resolvedType)
1060 .setResultTo(resultTo)
1061 .setResultWho(resultWho)
1062 .setRequestCode(requestCode)
1063 .setStartFlags(startFlags)
1064 .setProfilerInfo(profilerInfo)
1065 .setActivityOptions(bOptions)
1066 .setMayWait(userId)
1067 .execute();
1068
1069 }
1070
1071 @Override
1072 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1073 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001074 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1075 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 // Refuse possible leaked file descriptors
1077 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1078 throw new IllegalArgumentException("File descriptors passed in Intent");
1079 }
1080
1081 if (!(target instanceof PendingIntentRecord)) {
1082 throw new IllegalArgumentException("Bad PendingIntent object");
1083 }
1084
1085 PendingIntentRecord pir = (PendingIntentRecord)target;
1086
1087 synchronized (mGlobalLock) {
1088 // If this is coming from the currently resumed activity, it is
1089 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001090 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 if (stack.mResumedActivity != null &&
1092 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001094 }
1095 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001096 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 }
1099
1100 @Override
1101 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1102 Bundle bOptions) {
1103 // Refuse possible leaked file descriptors
1104 if (intent != null && intent.hasFileDescriptors()) {
1105 throw new IllegalArgumentException("File descriptors passed in Intent");
1106 }
1107 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1108
1109 synchronized (mGlobalLock) {
1110 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1111 if (r == null) {
1112 SafeActivityOptions.abort(options);
1113 return false;
1114 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001115 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 // The caller is not running... d'oh!
1117 SafeActivityOptions.abort(options);
1118 return false;
1119 }
1120 intent = new Intent(intent);
1121 // The caller is not allowed to change the data.
1122 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1123 // And we are resetting to find the next component...
1124 intent.setComponent(null);
1125
1126 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1127
1128 ActivityInfo aInfo = null;
1129 try {
1130 List<ResolveInfo> resolves =
1131 AppGlobals.getPackageManager().queryIntentActivities(
1132 intent, r.resolvedType,
1133 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1134 UserHandle.getCallingUserId()).getList();
1135
1136 // Look for the original activity in the list...
1137 final int N = resolves != null ? resolves.size() : 0;
1138 for (int i=0; i<N; i++) {
1139 ResolveInfo rInfo = resolves.get(i);
1140 if (rInfo.activityInfo.packageName.equals(r.packageName)
1141 && rInfo.activityInfo.name.equals(r.info.name)) {
1142 // We found the current one... the next matching is
1143 // after it.
1144 i++;
1145 if (i<N) {
1146 aInfo = resolves.get(i).activityInfo;
1147 }
1148 if (debug) {
1149 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1150 + "/" + r.info.name);
1151 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1152 ? "null" : aInfo.packageName + "/" + aInfo.name));
1153 }
1154 break;
1155 }
1156 }
1157 } catch (RemoteException e) {
1158 }
1159
1160 if (aInfo == null) {
1161 // Nobody who is next!
1162 SafeActivityOptions.abort(options);
1163 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1164 return false;
1165 }
1166
1167 intent.setComponent(new ComponentName(
1168 aInfo.applicationInfo.packageName, aInfo.name));
1169 intent.setFlags(intent.getFlags()&~(
1170 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1171 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1172 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1173 FLAG_ACTIVITY_NEW_TASK));
1174
1175 // Okay now we need to start the new activity, replacing the currently running activity.
1176 // This is a little tricky because we want to start the new one as if the current one is
1177 // finished, but not finish the current one first so that there is no flicker.
1178 // And thus...
1179 final boolean wasFinishing = r.finishing;
1180 r.finishing = true;
1181
1182 // Propagate reply information over to the new activity.
1183 final ActivityRecord resultTo = r.resultTo;
1184 final String resultWho = r.resultWho;
1185 final int requestCode = r.requestCode;
1186 r.resultTo = null;
1187 if (resultTo != null) {
1188 resultTo.removeResultsLocked(r, resultWho, requestCode);
1189 }
1190
1191 final long origId = Binder.clearCallingIdentity();
1192 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001195 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001196 .setResolvedType(r.resolvedType)
1197 .setActivityInfo(aInfo)
1198 .setResultTo(resultTo != null ? resultTo.appToken : null)
1199 .setResultWho(resultWho)
1200 .setRequestCode(requestCode)
1201 .setCallingPid(-1)
1202 .setCallingUid(r.launchedFromUid)
1203 .setCallingPackage(r.launchedFromPackage)
1204 .setRealCallingPid(-1)
1205 .setRealCallingUid(r.launchedFromUid)
1206 .setActivityOptions(options)
1207 .execute();
1208 Binder.restoreCallingIdentity(origId);
1209
1210 r.finishing = wasFinishing;
1211 if (res != ActivityManager.START_SUCCESS) {
1212 return false;
1213 }
1214 return true;
1215 }
1216 }
1217
1218 @Override
1219 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1220 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1221 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1222 final WaitResult res = new WaitResult();
1223 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001224 enforceNotIsolatedCaller("startActivityAndWait");
1225 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1226 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001228 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001229 .setCaller(caller)
1230 .setCallingPackage(callingPackage)
1231 .setResolvedType(resolvedType)
1232 .setResultTo(resultTo)
1233 .setResultWho(resultWho)
1234 .setRequestCode(requestCode)
1235 .setStartFlags(startFlags)
1236 .setActivityOptions(bOptions)
1237 .setMayWait(userId)
1238 .setProfilerInfo(profilerInfo)
1239 .setWaitResult(res)
1240 .execute();
1241 }
1242 return res;
1243 }
1244
1245 @Override
1246 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1247 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1248 int startFlags, Configuration config, Bundle bOptions, int userId) {
1249 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001250 enforceNotIsolatedCaller("startActivityWithConfig");
1251 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1252 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001253 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001254 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 .setCaller(caller)
1256 .setCallingPackage(callingPackage)
1257 .setResolvedType(resolvedType)
1258 .setResultTo(resultTo)
1259 .setResultWho(resultWho)
1260 .setRequestCode(requestCode)
1261 .setStartFlags(startFlags)
1262 .setGlobalConfiguration(config)
1263 .setActivityOptions(bOptions)
1264 .setMayWait(userId)
1265 .execute();
1266 }
1267 }
1268
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269
1270 @Override
1271 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1272 int callingUid = Binder.getCallingUid();
1273 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1274 throw new SecurityException("Only the system process can request a permission token, "
1275 + "received request from uid: " + callingUid);
1276 }
1277 IBinder permissionToken = new Binder();
1278 synchronized (mGlobalLock) {
1279 mStartActivitySources.put(permissionToken, delegatorToken);
1280 }
1281
1282 Message expireMsg = PooledLambda.obtainMessage(
1283 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1284 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1285
1286 Message forgetMsg = PooledLambda.obtainMessage(
1287 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1288 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1289
1290 return permissionToken;
1291 }
1292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 @Override
1294 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1295 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1297 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 // permission grants) as any app that may launch one of your own activities. So we only
1300 // allow this in two cases:
1301 // 1) The caller is an activity that is part of the core framework, and then only when it
1302 // is running as the system.
1303 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1304 // can only be requested by a system activity, which may then delegate this call to
1305 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 final ActivityRecord sourceRecord;
1307 final int targetUid;
1308 final String targetPackage;
1309 final boolean isResolver;
1310 synchronized (mGlobalLock) {
1311 if (resultTo == null) {
1312 throw new SecurityException("Must be called from an activity");
1313 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001314 final IBinder sourceToken;
1315 if (permissionToken != null) {
1316 // To even attempt to use a permissionToken, an app must also have this signature
1317 // permission.
1318 mAmInternal.enforceCallingPermission(
1319 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1320 "startActivityAsCaller");
1321 // If called with a permissionToken, we want the sourceRecord from the delegator
1322 // activity that requested this token.
1323 sourceToken = mStartActivitySources.remove(permissionToken);
1324 if (sourceToken == null) {
1325 // Invalid permissionToken, check if it recently expired.
1326 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1327 throw new SecurityException("Called with expired permission token: "
1328 + permissionToken);
1329 } else {
1330 throw new SecurityException("Called with invalid permission token: "
1331 + permissionToken);
1332 }
1333 }
1334 } else {
1335 // This method was called directly by the source.
1336 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338
Wale Ogunwaled32da472018-11-16 07:19:28 -08001339 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001340 if (sourceRecord == null) {
1341 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
1343 if (sourceRecord.app == null) {
1344 throw new SecurityException("Called without a process attached to activity");
1345 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001346
1347 // Whether called directly or from a delegate, the source activity must be from the
1348 // android package.
1349 if (!sourceRecord.info.packageName.equals("android")) {
1350 throw new SecurityException("Must be called from an activity that is "
1351 + "declared in the android package");
1352 }
1353
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001354 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001355 // This is still okay, as long as this activity is running under the
1356 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001357 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001359 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 + " must be system uid or original calling uid "
1361 + sourceRecord.launchedFromUid);
1362 }
1363 }
1364 if (ignoreTargetSecurity) {
1365 if (intent.getComponent() == null) {
1366 throw new SecurityException(
1367 "Component must be specified with ignoreTargetSecurity");
1368 }
1369 if (intent.getSelector() != null) {
1370 throw new SecurityException(
1371 "Selector not allowed with ignoreTargetSecurity");
1372 }
1373 }
1374 targetUid = sourceRecord.launchedFromUid;
1375 targetPackage = sourceRecord.launchedFromPackage;
1376 isResolver = sourceRecord.isResolverOrChildActivity();
1377 }
1378
1379 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001380 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 }
1382
1383 // TODO: Switch to user app stacks here.
1384 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001385 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 .setCallingUid(targetUid)
1387 .setCallingPackage(targetPackage)
1388 .setResolvedType(resolvedType)
1389 .setResultTo(resultTo)
1390 .setResultWho(resultWho)
1391 .setRequestCode(requestCode)
1392 .setStartFlags(startFlags)
1393 .setActivityOptions(bOptions)
1394 .setMayWait(userId)
1395 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1396 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001397 // The target may well be in the background, which would normally prevent it
1398 // from starting an activity. Here we definitely want the start to succeed.
1399 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .execute();
1401 } catch (SecurityException e) {
1402 // XXX need to figure out how to propagate to original app.
1403 // A SecurityException here is generally actually a fault of the original
1404 // calling activity (such as a fairly granting permissions), so propagate it
1405 // back to them.
1406 /*
1407 StringBuilder msg = new StringBuilder();
1408 msg.append("While launching");
1409 msg.append(intent.toString());
1410 msg.append(": ");
1411 msg.append(e.getMessage());
1412 */
1413 throw e;
1414 }
1415 }
1416
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001417 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1418 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1419 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1420 }
1421
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 @Override
1423 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1424 Intent intent, String resolvedType, IVoiceInteractionSession session,
1425 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1426 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001427 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 if (session == null || interactor == null) {
1429 throw new NullPointerException("null session or interactor");
1430 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001433 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 .setCallingUid(callingUid)
1435 .setCallingPackage(callingPackage)
1436 .setResolvedType(resolvedType)
1437 .setVoiceSession(session)
1438 .setVoiceInteractor(interactor)
1439 .setStartFlags(startFlags)
1440 .setProfilerInfo(profilerInfo)
1441 .setActivityOptions(bOptions)
1442 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001443 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 .execute();
1445 }
1446
1447 @Override
1448 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1449 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001450 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1451 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001453 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .setCallingUid(callingUid)
1455 .setCallingPackage(callingPackage)
1456 .setResolvedType(resolvedType)
1457 .setActivityOptions(bOptions)
1458 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001459 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 .execute();
1461 }
1462
Riddle Hsu609a8e22019-06-27 16:46:29 -06001463 /**
1464 * Start the recents activity to perform the recents animation.
1465 *
1466 * @param intent The intent to start the recents activity.
1467 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1468 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001470 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1471 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001474 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 final long origId = Binder.clearCallingIdentity();
1476 try {
1477 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001478 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1479 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001480 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481
1482 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001483 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001484 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001485 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001486 if (recentsAnimationRunner == null) {
1487 anim.preloadRecentsActivity();
1488 } else {
1489 anim.startRecentsActivity(recentsAnimationRunner);
1490 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 }
1492 } finally {
1493 Binder.restoreCallingIdentity(origId);
1494 }
1495 }
1496
1497 @Override
1498 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 "startActivityFromRecents()");
1501
1502 final int callingPid = Binder.getCallingPid();
1503 final int callingUid = Binder.getCallingUid();
1504 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1505 final long origId = Binder.clearCallingIdentity();
1506 try {
1507 synchronized (mGlobalLock) {
1508 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1509 safeOptions);
1510 }
1511 } finally {
1512 Binder.restoreCallingIdentity(origId);
1513 }
1514 }
1515
1516 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001517 * Public API to check if the client is allowed to start an activity on specified display.
1518 *
1519 * If the target display is private or virtual, some restrictions will apply.
1520 *
1521 * @param displayId Target display id.
1522 * @param intent Intent used to launch the activity.
1523 * @param resolvedType The MIME type of the intent.
1524 * @param userId The id of the user for whom the call is made.
1525 * @return {@code true} if a call to start an activity on the target display should succeed and
1526 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1527 */
1528 @Override
1529 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1530 String resolvedType, int userId) {
1531 final int callingUid = Binder.getCallingUid();
1532 final int callingPid = Binder.getCallingPid();
1533 final long origId = Binder.clearCallingIdentity();
1534
1535 try {
1536 // Collect information about the target of the Intent.
1537 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1538 0 /* startFlags */, null /* profilerInfo */, userId,
1539 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1540 UserHandle.USER_NULL));
1541 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1542
1543 synchronized (mGlobalLock) {
1544 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1545 aInfo);
1546 }
1547 } finally {
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550 }
1551
1552 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 * This is the internal entry point for handling Activity.finish().
1554 *
1555 * @param token The Binder token referencing the Activity we want to finish.
1556 * @param resultCode Result code, if any, from this Activity.
1557 * @param resultData Result data (Intent), if any, from this Activity.
1558 * @param finishTask Whether to finish the task associated with this Activity.
1559 *
1560 * @return Returns true if the activity successfully finished, or false if it is still running.
1561 */
1562 @Override
1563 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1564 int finishTask) {
1565 // Refuse possible leaked file descriptors
1566 if (resultData != null && resultData.hasFileDescriptors()) {
1567 throw new IllegalArgumentException("File descriptors passed in Intent");
1568 }
1569
1570 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001571 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 if (r == null) {
1573 return true;
1574 }
1575 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001576 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001577 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 if (rootR == null) {
1579 Slog.w(TAG, "Finishing task with all activities already finished");
1580 }
1581 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1582 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001583 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 return false;
1585 }
1586
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001587 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1588 // We should consolidate.
1589 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001591 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 if (next != null) {
1593 // ask watcher if this is allowed
1594 boolean resumeOK = true;
1595 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001596 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001598 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599 Watchdog.getInstance().setActivityController(null);
1600 }
1601
1602 if (!resumeOK) {
1603 Slog.i(TAG, "Not finishing activity because controller resumed");
1604 return false;
1605 }
1606 }
1607 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001608
1609 // note down that the process has finished an activity and is in background activity
1610 // starts grace period
1611 if (r.app != null) {
1612 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1613 }
1614
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 final long origId = Binder.clearCallingIdentity();
1616 try {
1617 boolean res;
1618 final boolean finishWithRootActivity =
1619 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1620 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1621 || (finishWithRootActivity && r == rootR)) {
1622 // If requested, remove the task that is associated to this activity only if it
1623 // was the root activity in the task. The result code and data is ignored
1624 // because we don't support returning them across task boundaries. Also, to
1625 // keep backwards compatibility we remove the task from recents when finishing
1626 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001627 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 finishWithRootActivity, "finish-activity");
1629 if (!res) {
1630 Slog.i(TAG, "Removing task failed to finish activity");
1631 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001632 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001633 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001635 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001636 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 if (!res) {
1638 Slog.i(TAG, "Failed to finish by app-request");
1639 }
1640 }
1641 return res;
1642 } finally {
1643 Binder.restoreCallingIdentity(origId);
1644 }
1645 }
1646 }
1647
1648 @Override
1649 public boolean finishActivityAffinity(IBinder token) {
1650 synchronized (mGlobalLock) {
1651 final long origId = Binder.clearCallingIdentity();
1652 try {
1653 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1654 if (r == null) {
1655 return false;
1656 }
1657
1658 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1659 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001660 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 return false;
1662 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001663 r.finishActivityAffinity();
1664 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 } finally {
1666 Binder.restoreCallingIdentity(origId);
1667 }
1668 }
1669 }
1670
1671 @Override
1672 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1673 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001674 try {
1675 WindowProcessController proc = null;
1676 synchronized (mGlobalLock) {
1677 ActivityStack stack = ActivityRecord.getStackLocked(token);
1678 if (stack == null) {
1679 return;
1680 }
1681 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1682 false /* fromTimeout */, false /* processPausingActivities */, config);
1683 if (r != null) {
1684 proc = r.app;
1685 }
1686 if (stopProfiling && proc != null) {
1687 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001688 }
1689 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001690 } finally {
1691 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 }
1694
1695 @Override
1696 public final void activityResumed(IBinder token) {
1697 final long origId = Binder.clearCallingIdentity();
1698 synchronized (mGlobalLock) {
1699 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001700 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 }
1702 Binder.restoreCallingIdentity(origId);
1703 }
1704
1705 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001706 public final void activityTopResumedStateLost() {
1707 final long origId = Binder.clearCallingIdentity();
1708 synchronized (mGlobalLock) {
1709 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 public final void activityPaused(IBinder token) {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 ActivityStack stack = ActivityRecord.getStackLocked(token);
1719 if (stack != null) {
1720 stack.activityPausedLocked(token, false);
1721 }
1722 }
1723 Binder.restoreCallingIdentity(origId);
1724 }
1725
1726 @Override
1727 public final void activityStopped(IBinder token, Bundle icicle,
1728 PersistableBundle persistentState, CharSequence description) {
1729 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1730
1731 // Refuse possible leaked file descriptors
1732 if (icicle != null && icicle.hasFileDescriptors()) {
1733 throw new IllegalArgumentException("File descriptors passed in Bundle");
1734 }
1735
1736 final long origId = Binder.clearCallingIdentity();
1737
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001738 String restartingName = null;
1739 int restartingUid = 0;
1740 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001741 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001742 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001744 if (r.attachedToProcess()
1745 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1746 // The activity was requested to restart from
1747 // {@link #restartActivityProcessIfVisible}.
1748 restartingName = r.app.mName;
1749 restartingUid = r.app.mUid;
1750 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751 r.activityStoppedLocked(icicle, persistentState, description);
1752 }
1753 }
1754
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001755 if (restartingName != null) {
1756 // In order to let the foreground activity can be restarted with its saved state from
1757 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1758 // until the activity reports stopped with the state. And the activity record will be
1759 // kept because the record state is restarting, then the activity will be restarted
1760 // immediately if it is still the top one.
1761 mStackSupervisor.removeRestartTimeouts(r);
1762 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1763 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001764 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001765
1766 Binder.restoreCallingIdentity(origId);
1767 }
1768
1769 @Override
1770 public final void activityDestroyed(IBinder token) {
1771 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1772 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001773 final long origId = Binder.clearCallingIdentity();
1774 try {
1775 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1776 if (activity != null) {
1777 activity.destroyed("activityDestroyed");
1778 }
1779 } finally {
1780 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 }
1782 }
1783 }
1784
1785 @Override
1786 public final void activityRelaunched(IBinder token) {
1787 final long origId = Binder.clearCallingIdentity();
1788 synchronized (mGlobalLock) {
1789 mStackSupervisor.activityRelaunchedLocked(token);
1790 }
1791 Binder.restoreCallingIdentity(origId);
1792 }
1793
1794 public final void activitySlept(IBinder token) {
1795 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1796
1797 final long origId = Binder.clearCallingIdentity();
1798
1799 synchronized (mGlobalLock) {
1800 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1801 if (r != null) {
1802 mStackSupervisor.activitySleptLocked(r);
1803 }
1804 }
1805
1806 Binder.restoreCallingIdentity(origId);
1807 }
1808
1809 @Override
1810 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1811 synchronized (mGlobalLock) {
1812 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1813 if (r == null) {
1814 return;
1815 }
1816 final long origId = Binder.clearCallingIdentity();
1817 try {
1818 r.setRequestedOrientation(requestedOrientation);
1819 } finally {
1820 Binder.restoreCallingIdentity(origId);
1821 }
1822 }
1823 }
1824
1825 @Override
1826 public int getRequestedOrientation(IBinder token) {
1827 synchronized (mGlobalLock) {
1828 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1829 if (r == null) {
1830 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1831 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001832 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 }
1834 }
1835
1836 @Override
1837 public void setImmersive(IBinder token, boolean immersive) {
1838 synchronized (mGlobalLock) {
1839 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1840 if (r == null) {
1841 throw new IllegalArgumentException();
1842 }
1843 r.immersive = immersive;
1844
1845 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001846 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001848 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
1850 }
1851 }
1852
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 void applyUpdateLockStateLocked(ActivityRecord r) {
1854 // Modifications to the UpdateLock state are done on our handler, outside
1855 // the activity manager's locks. The new state is determined based on the
1856 // state *now* of the relevant activity record. The object is passed to
1857 // the handler solely for logging detail, not to be consulted/modified.
1858 final boolean nextState = r != null && r.immersive;
1859 mH.post(() -> {
1860 if (mUpdateLock.isHeld() != nextState) {
1861 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1862 "Applying new update lock state '" + nextState + "' for " + r);
1863 if (nextState) {
1864 mUpdateLock.acquire();
1865 } else {
1866 mUpdateLock.release();
1867 }
1868 }
1869 });
1870 }
1871
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 @Override
1873 public boolean isImmersive(IBinder token) {
1874 synchronized (mGlobalLock) {
1875 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1876 if (r == null) {
1877 throw new IllegalArgumentException();
1878 }
1879 return r.immersive;
1880 }
1881 }
1882
1883 @Override
1884 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001887 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 return (r != null) ? r.immersive : false;
1889 }
1890 }
1891
1892 @Override
1893 public void overridePendingTransition(IBinder token, String packageName,
1894 int enterAnim, int exitAnim) {
1895 synchronized (mGlobalLock) {
1896 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1897 if (self == null) {
1898 return;
1899 }
1900
1901 final long origId = Binder.clearCallingIdentity();
1902
1903 if (self.isState(
1904 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001905 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001906 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908
1909 Binder.restoreCallingIdentity(origId);
1910 }
1911 }
1912
1913 @Override
1914 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001917 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 if (r == null) {
1919 return ActivityManager.COMPAT_MODE_UNKNOWN;
1920 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001921 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 }
1923 }
1924
1925 @Override
1926 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001927 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001929 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001931 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 if (r == null) {
1933 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1934 return;
1935 }
1936 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001937 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 }
1939 }
1940
1941 @Override
1942 public int getLaunchedFromUid(IBinder activityToken) {
1943 ActivityRecord srec;
1944 synchronized (mGlobalLock) {
1945 srec = ActivityRecord.forTokenLocked(activityToken);
1946 }
1947 if (srec == null) {
1948 return -1;
1949 }
1950 return srec.launchedFromUid;
1951 }
1952
1953 @Override
1954 public String getLaunchedFromPackage(IBinder activityToken) {
1955 ActivityRecord srec;
1956 synchronized (mGlobalLock) {
1957 srec = ActivityRecord.forTokenLocked(activityToken);
1958 }
1959 if (srec == null) {
1960 return null;
1961 }
1962 return srec.launchedFromPackage;
1963 }
1964
1965 @Override
1966 public boolean convertFromTranslucent(IBinder token) {
1967 final long origId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return false;
1973 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001974 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(origId);
1978 }
1979 }
1980
1981 @Override
1982 public boolean convertToTranslucent(IBinder token, Bundle options) {
1983 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1984 final long origId = Binder.clearCallingIdentity();
1985 try {
1986 synchronized (mGlobalLock) {
1987 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return false;
1990 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001991 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 int index = task.mActivities.lastIndexOf(r);
1993 if (index > 0) {
1994 ActivityRecord under = task.mActivities.get(index - 1);
1995 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1996 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001997 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 }
1999 } finally {
2000 Binder.restoreCallingIdentity(origId);
2001 }
2002 }
2003
2004 @Override
2005 public void notifyActivityDrawn(IBinder token) {
2006 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2007 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002008 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002010 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 }
2012 }
2013 }
2014
2015 @Override
2016 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2017 synchronized (mGlobalLock) {
2018 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2019 if (r == null) {
2020 return;
2021 }
2022 r.reportFullyDrawnLocked(restoredFromBundle);
2023 }
2024 }
2025
2026 @Override
2027 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2028 synchronized (mGlobalLock) {
2029 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2030 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2031 return stack.mDisplayId;
2032 }
2033 return DEFAULT_DISPLAY;
2034 }
2035 }
2036
2037 @Override
2038 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002039 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 long ident = Binder.clearCallingIdentity();
2041 try {
2042 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002043 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002045 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 }
2047 return null;
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(ident);
2051 }
2052 }
2053
2054 @Override
2055 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002056 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2058 final long callingId = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (stack == null) {
2063 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2064 return;
2065 }
2066 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002067 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 }
2070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(callingId);
2073 }
2074 }
2075
2076 @Override
2077 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002078 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2080 final long callingId = Binder.clearCallingIdentity();
2081 try {
2082 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002083 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002084 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (task == null) {
2086 return;
2087 }
2088 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002089 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002090 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 }
2092 }
2093 } finally {
2094 Binder.restoreCallingIdentity(callingId);
2095 }
2096 }
2097
2098 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002099 public void restartActivityProcessIfVisible(IBinder activityToken) {
2100 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2101 final long callingId = Binder.clearCallingIdentity();
2102 try {
2103 synchronized (mGlobalLock) {
2104 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2105 if (r == null) {
2106 return;
2107 }
2108 r.restartProcessIfVisible();
2109 }
2110 } finally {
2111 Binder.restoreCallingIdentity(callingId);
2112 }
2113 }
2114
2115 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002117 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 synchronized (mGlobalLock) {
2119 final long ident = Binder.clearCallingIdentity();
2120 try {
2121 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2122 "remove-task");
2123 } finally {
2124 Binder.restoreCallingIdentity(ident);
2125 }
2126 }
2127 }
2128
2129 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002130 public void removeAllVisibleRecentTasks() {
2131 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2132 synchronized (mGlobalLock) {
2133 final long ident = Binder.clearCallingIdentity();
2134 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002135 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002136 } finally {
2137 Binder.restoreCallingIdentity(ident);
2138 }
2139 }
2140 }
2141
2142 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2144 synchronized (mGlobalLock) {
2145 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2146 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002147 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002148 }
2149 }
2150 return false;
2151 }
2152
2153 @Override
2154 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2155 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002156
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002157 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002158 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2159 if (r != null) {
2160 return r.getActivityStack().navigateUpToLocked(
2161 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002162 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002163 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 }
2165 }
2166
2167 /**
2168 * Attempts to move a task backwards in z-order (the order of activities within the task is
2169 * unchanged).
2170 *
2171 * There are several possible results of this call:
2172 * - if the task is locked, then we will show the lock toast
2173 * - if there is a task behind the provided task, then that task is made visible and resumed as
2174 * this task is moved to the back
2175 * - otherwise, if there are no other tasks in the stack:
2176 * - if this task is in the pinned stack, then we remove the stack completely, which will
2177 * have the effect of moving the task to the top or bottom of the fullscreen stack
2178 * (depending on whether it is visible)
2179 * - otherwise, we simply return home and hide this task
2180 *
2181 * @param token A reference to the activity we wish to move
2182 * @param nonRoot If false then this only works if the activity is the root
2183 * of a task; if true it will work for any activity in a task.
2184 * @return Returns true if the move completed, false if not.
2185 */
2186 @Override
2187 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002188 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 synchronized (mGlobalLock) {
2190 final long origId = Binder.clearCallingIdentity();
2191 try {
2192 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002193 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 if (task != null) {
2195 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2196 }
2197 } finally {
2198 Binder.restoreCallingIdentity(origId);
2199 }
2200 }
2201 return false;
2202 }
2203
2204 @Override
2205 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 long ident = Binder.clearCallingIdentity();
2208 Rect rect = new Rect();
2209 try {
2210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002211 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2213 if (task == null) {
2214 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2215 return rect;
2216 }
2217 if (task.getStack() != null) {
2218 // Return the bounds from window manager since it will be adjusted for various
2219 // things like the presense of a docked stack for tasks that aren't resizeable.
2220 task.getWindowContainerBounds(rect);
2221 } else {
2222 // Task isn't in window manager yet since it isn't associated with a stack.
2223 // Return the persist value from activity manager
2224 if (!task.matchParentBounds()) {
2225 rect.set(task.getBounds());
2226 } else if (task.mLastNonFullscreenBounds != null) {
2227 rect.set(task.mLastNonFullscreenBounds);
2228 }
2229 }
2230 }
2231 } finally {
2232 Binder.restoreCallingIdentity(ident);
2233 }
2234 return rect;
2235 }
2236
2237 @Override
2238 public ActivityManager.TaskDescription getTaskDescription(int id) {
2239 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002240 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002242 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2244 if (tr != null) {
2245 return tr.lastTaskDescription;
2246 }
2247 }
2248 return null;
2249 }
2250
2251 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002252 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2253 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2254 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2255 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2256 return;
2257 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002258 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 synchronized (mGlobalLock) {
2260 final long ident = Binder.clearCallingIdentity();
2261 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002262 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002263 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002264 if (task == null) {
2265 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2266 return;
2267 }
2268
2269 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2270 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2271
2272 if (!task.isActivityTypeStandardOrUndefined()) {
2273 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2274 + " non-standard task " + taskId + " to windowing mode="
2275 + windowingMode);
2276 }
2277
2278 final ActivityStack stack = task.getStack();
2279 if (toTop) {
2280 stack.moveToFront("setTaskWindowingMode", task);
2281 }
2282 stack.setWindowingMode(windowingMode);
2283 } finally {
2284 Binder.restoreCallingIdentity(ident);
2285 }
2286 }
2287 }
2288
2289 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002291 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 ActivityRecord r = getCallingRecordLocked(token);
2293 return r != null ? r.info.packageName : null;
2294 }
2295 }
2296
2297 @Override
2298 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002299 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 ActivityRecord r = getCallingRecordLocked(token);
2301 return r != null ? r.intent.getComponent() : null;
2302 }
2303 }
2304
2305 private ActivityRecord getCallingRecordLocked(IBinder token) {
2306 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2307 if (r == null) {
2308 return null;
2309 }
2310 return r.resultTo;
2311 }
2312
2313 @Override
2314 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002315 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002316
2317 synchronized (mGlobalLock) {
2318 final long origId = Binder.clearCallingIdentity();
2319 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002320 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321 } finally {
2322 Binder.restoreCallingIdentity(origId);
2323 }
2324 }
2325 }
2326
Mark Renouf446251d2019-04-26 10:22:41 -04002327 @Override
2328 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2329 synchronized (mGlobalLock) {
2330 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2331 if (r == null) {
2332 return;
2333 }
2334 ActivityStack stack = r.getActivityStack();
2335 if (stack != null && stack.isSingleTaskInstance()) {
2336 // Single-task stacks are used for activities which are presented in floating
2337 // windows above full screen activities. Instead of directly finishing the
2338 // task, a task change listener is used to notify SystemUI so the action can be
2339 // handled specially.
2340 final TaskRecord task = r.getTaskRecord();
2341 mTaskChangeNotificationController
2342 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2343 } else {
2344 try {
2345 callback.requestFinish();
2346 } catch (RemoteException e) {
2347 Slog.e(TAG, "Failed to invoke request finish callback", e);
2348 }
2349 }
2350 }
2351 }
2352
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002353 /**
2354 * TODO: Add mController hook
2355 */
2356 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2358 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002359 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360
2361 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2362 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2364 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365 }
2366 }
2367
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2369 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002371
Ricky Waiaca8a772019-04-04 16:01:06 +01002372 final int callingPid = Binder.getCallingPid();
2373 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002374 if (!isSameApp(callingUid, callingPackage)) {
2375 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2376 + Binder.getCallingPid() + " as package " + callingPackage;
2377 Slog.w(TAG, msg);
2378 throw new SecurityException(msg);
2379 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002381 SafeActivityOptions.abort(options);
2382 return;
2383 }
2384 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002385 WindowProcessController callerApp = null;
2386 if (appThread != null) {
2387 callerApp = getProcessController(appThread);
2388 }
2389 final ActivityStarter starter = getActivityStartController().obtainStarter(
2390 null /* intent */, "moveTaskToFront");
2391 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2392 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002393 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002394 return;
2395 }
2396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002398 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 if (task == null) {
2400 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002401 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 return;
2403 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002404 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002406 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 return;
2408 }
2409 ActivityOptions realOptions = options != null
2410 ? options.getOptions(mStackSupervisor)
2411 : null;
2412 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2413 false /* forceNonResizable */);
2414
2415 final ActivityRecord topActivity = task.getTopActivity();
2416 if (topActivity != null) {
2417
2418 // We are reshowing a task, use a starting window to hide the initial draw delay
2419 // so the transition can start earlier.
2420 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2421 true /* taskSwitch */, fromRecents);
2422 }
2423 } finally {
2424 Binder.restoreCallingIdentity(origId);
2425 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426 }
2427
Ricky Waiaca8a772019-04-04 16:01:06 +01002428 /**
2429 * Return true if callingUid is system, or packageName belongs to that callingUid.
2430 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002431 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002432 try {
2433 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2434 if (packageName == null) {
2435 return false;
2436 }
2437 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2438 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2439 UserHandle.getUserId(callingUid));
2440 return UserHandle.isSameApp(callingUid, uid);
2441 }
2442 } catch (RemoteException e) {
2443 // Should not happen
2444 }
2445 return true;
2446 }
2447
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2449 int callingPid, int callingUid, String name) {
2450 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2451 return true;
2452 }
2453
2454 if (getRecentTasks().isCallerRecents(sourceUid)) {
2455 return true;
2456 }
2457
2458 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2459 if (perm == PackageManager.PERMISSION_GRANTED) {
2460 return true;
2461 }
2462 if (checkAllowAppSwitchUid(sourceUid)) {
2463 return true;
2464 }
2465
2466 // If the actual IPC caller is different from the logical source, then
2467 // also see if they are allowed to control app switches.
2468 if (callingUid != -1 && callingUid != sourceUid) {
2469 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2470 if (perm == PackageManager.PERMISSION_GRANTED) {
2471 return true;
2472 }
2473 if (checkAllowAppSwitchUid(callingUid)) {
2474 return true;
2475 }
2476 }
2477
2478 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2479 return false;
2480 }
2481
2482 private boolean checkAllowAppSwitchUid(int uid) {
2483 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2484 if (types != null) {
2485 for (int i = types.size() - 1; i >= 0; i--) {
2486 if (types.valueAt(i).intValue() == uid) {
2487 return true;
2488 }
2489 }
2490 }
2491 return false;
2492 }
2493
2494 @Override
2495 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2496 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2497 "setActivityController()");
2498 synchronized (mGlobalLock) {
2499 mController = controller;
2500 mControllerIsAMonkey = imAMonkey;
2501 Watchdog.getInstance().setActivityController(controller);
2502 }
2503 }
2504
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002505 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002506 synchronized (mGlobalLock) {
2507 return mController != null && mControllerIsAMonkey;
2508 }
2509 }
2510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002511 @Override
2512 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2513 synchronized (mGlobalLock) {
2514 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2515 }
2516 }
2517
2518 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2520 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2521 }
2522
2523 @Override
2524 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2525 @WindowConfiguration.ActivityType int ignoreActivityType,
2526 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2527 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002528 final int callingPid = Binder.getCallingPid();
2529 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002530 final int[] profileIds = getUserManager().getProfileIds(
2531 UserHandle.getUserId(callingUid), true);
2532 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2533 for (int i = 0; i < profileIds.length; i++) {
2534 callingProfileIds.add(profileIds[i]);
2535 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002536 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2537
2538 synchronized (mGlobalLock) {
2539 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2540
Nicholas Sauer0259e532019-08-30 08:24:55 -07002541 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002542 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002543 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 }
2545
2546 return list;
2547 }
2548
2549 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2551 synchronized (mGlobalLock) {
2552 final long origId = Binder.clearCallingIdentity();
2553 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2554 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002555 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 }
2557 Binder.restoreCallingIdentity(origId);
2558 }
2559 }
2560
2561 @Override
2562 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002563 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564 ActivityStack stack = ActivityRecord.getStackLocked(token);
2565 if (stack != null) {
2566 return stack.willActivityBeVisibleLocked(token);
2567 }
2568 return false;
2569 }
2570 }
2571
2572 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002575 synchronized (mGlobalLock) {
2576 final long ident = Binder.clearCallingIdentity();
2577 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002578 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002579 if (task == null) {
2580 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2581 return;
2582 }
2583
2584 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2585 + " to stackId=" + stackId + " toTop=" + toTop);
2586
Wale Ogunwaled32da472018-11-16 07:19:28 -08002587 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 if (stack == null) {
2589 throw new IllegalStateException(
2590 "moveTaskToStack: No stack for stackId=" + stackId);
2591 }
2592 if (!stack.isActivityTypeStandardOrUndefined()) {
2593 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2594 + taskId + " to stack " + stackId);
2595 }
2596 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002597 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2599 }
2600 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2601 "moveTaskToStack");
2602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
2605 }
2606 }
2607
2608 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002609 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2610 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611
2612 final long ident = Binder.clearCallingIdentity();
2613 try {
2614 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002615 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2616 if (stack == null) {
2617 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2618 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002620 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2621 throw new IllegalArgumentException("Stack: " + stackId
2622 + " doesn't support animated resize.");
2623 }
2624 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2625 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 }
2627 } finally {
2628 Binder.restoreCallingIdentity(ident);
2629 }
2630 }
2631
wilsonshih5c4cf522019-01-25 09:03:47 +08002632 @Override
2633 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2634 int animationDuration) {
2635 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2636
2637 final long ident = Binder.clearCallingIdentity();
2638 try {
2639 synchronized (mGlobalLock) {
2640 if (xOffset == 0 && yOffset == 0) {
2641 return;
2642 }
2643 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2644 if (stack == null) {
2645 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2646 return;
2647 }
2648 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2649 throw new IllegalArgumentException("Stack: " + stackId
2650 + " doesn't support animated resize.");
2651 }
2652 final Rect destBounds = new Rect();
2653 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002654 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002655 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2656 return;
2657 }
2658 destBounds.offset(xOffset, yOffset);
2659 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2660 animationDuration, false /* fromFullscreen */);
2661 }
2662 } finally {
2663 Binder.restoreCallingIdentity(ident);
2664 }
2665 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002666 /**
2667 * Moves the specified task to the primary-split-screen stack.
2668 *
2669 * @param taskId Id of task to move.
2670 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2671 * exist already. See
2672 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2673 * and
2674 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2675 * @param toTop If the task and stack should be moved to the top.
2676 * @param animate Whether we should play an animation for the moving the task.
2677 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2678 * stack. Pass {@code null} to use default bounds.
2679 * @param showRecents If the recents activity should be shown on the other side of the task
2680 * going into split-screen mode.
2681 */
2682 @Override
2683 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2684 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002685 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686 "setTaskWindowingModeSplitScreenPrimary()");
2687 synchronized (mGlobalLock) {
2688 final long ident = Binder.clearCallingIdentity();
2689 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002690 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002691 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 if (task == null) {
2693 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2694 return false;
2695 }
2696 if (DEBUG_STACK) Slog.d(TAG_STACK,
2697 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2698 + " to createMode=" + createMode + " toTop=" + toTop);
2699 if (!task.isActivityTypeStandardOrUndefined()) {
2700 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2701 + " non-standard task " + taskId + " to split-screen windowing mode");
2702 }
2703
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002704 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 final int windowingMode = task.getWindowingMode();
2706 final ActivityStack stack = task.getStack();
2707 if (toTop) {
2708 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2709 }
2710 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002711 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2712 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 return windowingMode != task.getWindowingMode();
2714 } finally {
2715 Binder.restoreCallingIdentity(ident);
2716 }
2717 }
2718 }
2719
2720 /**
2721 * Removes stacks in the input windowing modes from the system if they are of activity type
2722 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2723 */
2724 @Override
2725 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002726 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 "removeStacksInWindowingModes()");
2728
2729 synchronized (mGlobalLock) {
2730 final long ident = Binder.clearCallingIdentity();
2731 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002732 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737 }
2738
2739 @Override
2740 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 "removeStacksWithActivityTypes()");
2743
2744 synchronized (mGlobalLock) {
2745 final long ident = Binder.clearCallingIdentity();
2746 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002747 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002753
2754 @Override
2755 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2756 int userId) {
2757 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002758 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2759 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002761 final boolean detailed = checkGetTasksPermission(
2762 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2763 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 == PackageManager.PERMISSION_GRANTED;
2765
2766 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002767 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 callingUid);
2769 }
2770 }
2771
2772 @Override
2773 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002774 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 long ident = Binder.clearCallingIdentity();
2776 try {
2777 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002778 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 }
2780 } finally {
2781 Binder.restoreCallingIdentity(ident);
2782 }
2783 }
2784
2785 @Override
2786 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 long ident = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002791 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 } finally {
2794 Binder.restoreCallingIdentity(ident);
2795 }
2796 }
2797
2798 @Override
2799 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 final long callingUid = Binder.getCallingUid();
2802 final long origId = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
2805 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002806 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2808 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(origId);
2812 }
2813 }
2814
2815 @Override
2816 public void startLockTaskModeByToken(IBinder token) {
2817 synchronized (mGlobalLock) {
2818 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2819 if (r == null) {
2820 return;
2821 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002822 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 }
2824 }
2825
2826 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002827 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002828 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 // This makes inner call to look as if it was initiated by system.
2830 long ident = Binder.clearCallingIdentity();
2831 try {
2832 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002833 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002834 MATCH_TASK_IN_STACKS_ONLY);
2835 if (task == null) {
2836 return;
2837 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838
2839 // When starting lock task mode the stack must be in front and focused
2840 task.getStack().moveToFront("startSystemLockTaskMode");
2841 startLockTaskModeLocked(task, true /* isSystemCaller */);
2842 }
2843 } finally {
2844 Binder.restoreCallingIdentity(ident);
2845 }
2846 }
2847
2848 @Override
2849 public void stopLockTaskModeByToken(IBinder token) {
2850 synchronized (mGlobalLock) {
2851 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2852 if (r == null) {
2853 return;
2854 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002855 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 }
2857 }
2858
2859 /**
2860 * This API should be called by SystemUI only when user perform certain action to dismiss
2861 * lock task mode. We should only dismiss pinned lock task mode in this case.
2862 */
2863 @Override
2864 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002865 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2867 }
2868
2869 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2870 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2871 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2872 return;
2873 }
2874
Wale Ogunwaled32da472018-11-16 07:19:28 -08002875 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 if (stack == null || task != stack.topTask()) {
2877 throw new IllegalArgumentException("Invalid task, not in foreground");
2878 }
2879
2880 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2881 // system or a specific app.
2882 // * System-initiated requests will only start the pinned mode (screen pinning)
2883 // * App-initiated requests
2884 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2885 // - will start the pinned mode, otherwise
2886 final int callingUid = Binder.getCallingUid();
2887 long ident = Binder.clearCallingIdentity();
2888 try {
2889 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002890 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002892 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893 } finally {
2894 Binder.restoreCallingIdentity(ident);
2895 }
2896 }
2897
2898 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2899 final int callingUid = Binder.getCallingUid();
2900 long ident = Binder.clearCallingIdentity();
2901 try {
2902 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002903 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904 }
2905 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2906 // task and jumping straight into a call in the case of emergency call back.
2907 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2908 if (tm != null) {
2909 tm.showInCallScreen(false);
2910 }
2911 } finally {
2912 Binder.restoreCallingIdentity(ident);
2913 }
2914 }
2915
2916 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002917 public void updateLockTaskPackages(int userId, String[] packages) {
2918 final int callingUid = Binder.getCallingUid();
2919 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2920 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2921 "updateLockTaskPackages()");
2922 }
2923 synchronized (this) {
2924 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2925 + Arrays.toString(packages));
2926 getLockTaskController().updateLockTaskPackages(userId, packages);
2927 }
2928 }
2929
2930 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 public boolean isInLockTaskMode() {
2932 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2933 }
2934
2935 @Override
2936 public int getLockTaskModeState() {
2937 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002938 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941
2942 @Override
2943 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2944 synchronized (mGlobalLock) {
2945 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2946 if (r != null) {
2947 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002948 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002950 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 }
2952 }
2953 }
2954
2955 @Override
2956 public Bundle getActivityOptions(IBinder token) {
2957 final long origId = Binder.clearCallingIdentity();
2958 try {
2959 synchronized (mGlobalLock) {
2960 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2961 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002962 final ActivityOptions activityOptions = r.takeOptionsLocked(
2963 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 return activityOptions == null ? null : activityOptions.toBundle();
2965 }
2966 return null;
2967 }
2968 } finally {
2969 Binder.restoreCallingIdentity(origId);
2970 }
2971 }
2972
2973 @Override
2974 public List<IBinder> getAppTasks(String callingPackage) {
2975 int callingUid = Binder.getCallingUid();
2976 long ident = Binder.clearCallingIdentity();
2977 try {
2978 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002979 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 }
2981 } finally {
2982 Binder.restoreCallingIdentity(ident);
2983 }
2984 }
2985
2986 @Override
2987 public void finishVoiceTask(IVoiceInteractionSession session) {
2988 synchronized (mGlobalLock) {
2989 final long origId = Binder.clearCallingIdentity();
2990 try {
2991 // TODO: VI Consider treating local voice interactions and voice tasks
2992 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002993 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 } finally {
2995 Binder.restoreCallingIdentity(origId);
2996 }
2997 }
2998
2999 }
3000
3001 @Override
3002 public boolean isTopOfTask(IBinder token) {
3003 synchronized (mGlobalLock) {
3004 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003005 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008
3009 @Override
3010 public void notifyLaunchTaskBehindComplete(IBinder token) {
3011 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3012 }
3013
3014 @Override
3015 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003016 mH.post(() -> {
3017 synchronized (mGlobalLock) {
3018 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003019 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003020 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003021 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003022 } catch (RemoteException e) {
3023 }
3024 }
3025 }
3026
3027 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 }
3029
3030 /** Called from an app when assist data is ready. */
3031 @Override
3032 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3033 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003034 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 synchronized (pae) {
3036 pae.result = extras;
3037 pae.structure = structure;
3038 pae.content = content;
3039 if (referrer != null) {
3040 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3041 }
3042 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003043 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003044 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3045 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 structure.setHomeActivity(pae.isHome);
3047 }
3048 pae.haveResult = true;
3049 pae.notifyAll();
3050 if (pae.intent == null && pae.receiver == null) {
3051 // Caller is just waiting for the result.
3052 return;
3053 }
3054 }
3055 // We are now ready to launch the assist activity.
3056 IAssistDataReceiver sendReceiver = null;
3057 Bundle sendBundle = null;
3058 synchronized (mGlobalLock) {
3059 buildAssistBundleLocked(pae, extras);
3060 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003061 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 if (!exists) {
3063 // Timed out.
3064 return;
3065 }
3066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003067 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 // Caller wants result sent back to them.
3069 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003070 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3071 pae.activity.getTaskRecord().taskId);
3072 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3073 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3075 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3076 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3077 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3078 }
3079 }
3080 if (sendReceiver != null) {
3081 try {
3082 sendReceiver.onHandleAssistData(sendBundle);
3083 } catch (RemoteException e) {
3084 }
3085 return;
3086 }
3087
3088 final long ident = Binder.clearCallingIdentity();
3089 try {
3090 if (TextUtils.equals(pae.intent.getAction(),
3091 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003092 // Start voice interaction through VoiceInteractionManagerService.
3093 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3094 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 } else {
3096 pae.intent.replaceExtras(pae.extras);
3097 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3098 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3099 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003100 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003101
3102 try {
3103 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3104 } catch (ActivityNotFoundException e) {
3105 Slog.w(TAG, "No activity to handle assist action.", e);
3106 }
3107 }
3108 } finally {
3109 Binder.restoreCallingIdentity(ident);
3110 }
3111 }
3112
3113 @Override
3114 public int addAppTask(IBinder activityToken, Intent intent,
3115 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3116 final int callingUid = Binder.getCallingUid();
3117 final long callingIdent = Binder.clearCallingIdentity();
3118
3119 try {
3120 synchronized (mGlobalLock) {
3121 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3122 if (r == null) {
3123 throw new IllegalArgumentException("Activity does not exist; token="
3124 + activityToken);
3125 }
3126 ComponentName comp = intent.getComponent();
3127 if (comp == null) {
3128 throw new IllegalArgumentException("Intent " + intent
3129 + " must specify explicit component");
3130 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003131 if (thumbnail.getWidth() != mThumbnailWidth
3132 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 throw new IllegalArgumentException("Bad thumbnail size: got "
3134 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003136 }
3137 if (intent.getSelector() != null) {
3138 intent.setSelector(null);
3139 }
3140 if (intent.getSourceBounds() != null) {
3141 intent.setSourceBounds(null);
3142 }
3143 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3144 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3145 // The caller has added this as an auto-remove task... that makes no
3146 // sense, so turn off auto-remove.
3147 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3148 }
3149 }
3150 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3151 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3152 if (ainfo.applicationInfo.uid != callingUid) {
3153 throw new SecurityException(
3154 "Can't add task for another application: target uid="
3155 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3156 }
3157
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003158 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003160 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003162 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 // The app has too many tasks already and we can't add any more
3164 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3165 return INVALID_TASK_ID;
3166 }
3167 task.lastTaskDescription.copyFrom(description);
3168
3169 // TODO: Send the thumbnail to WM to store it.
3170
3171 return task.taskId;
3172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(callingIdent);
3175 }
3176 }
3177
3178 @Override
3179 public Point getAppTaskThumbnailSize() {
3180 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003181 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 }
3183 }
3184
3185 @Override
3186 public void setTaskResizeable(int taskId, int resizeableMode) {
3187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003188 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3190 if (task == null) {
3191 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3192 return;
3193 }
3194 task.setResizeMode(resizeableMode);
3195 }
3196 }
3197
3198 @Override
3199 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 long ident = Binder.clearCallingIdentity();
3202 try {
3203 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003204 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003205 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 if (task == null) {
3207 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3208 return;
3209 }
3210 // Place the task in the right stack if it isn't there already based on
3211 // the requested bounds.
3212 // The stack transition logic is:
3213 // - a null bounds on a freeform task moves that task to fullscreen
3214 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3215 // that task to freeform
3216 // - otherwise the task is not moved
3217 ActivityStack stack = task.getStack();
3218 if (!task.getWindowConfiguration().canResizeTask()) {
3219 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3220 }
3221 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3222 stack = stack.getDisplay().getOrCreateStack(
3223 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3224 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3225 stack = stack.getDisplay().getOrCreateStack(
3226 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3227 }
3228
3229 // Reparent the task to the right stack if necessary
3230 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3231 if (stack != task.getStack()) {
3232 // Defer resume until the task is resized below
3233 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3234 DEFER_RESUME, "resizeTask");
3235 preserveWindow = false;
3236 }
3237
3238 // After reparenting (which only resizes the task to the stack bounds), resize the
3239 // task to the actual bounds provided
3240 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3241 }
3242 } finally {
3243 Binder.restoreCallingIdentity(ident);
3244 }
3245 }
3246
3247 @Override
3248 public boolean releaseActivityInstance(IBinder token) {
3249 synchronized (mGlobalLock) {
3250 final long origId = Binder.clearCallingIdentity();
3251 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003252 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3253 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 return false;
3255 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003256 r.destroyImmediately(true /* removeFromApp */, "app-req");
3257 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 } finally {
3259 Binder.restoreCallingIdentity(origId);
3260 }
3261 }
3262 }
3263
3264 @Override
3265 public void releaseSomeActivities(IApplicationThread appInt) {
3266 synchronized (mGlobalLock) {
3267 final long origId = Binder.clearCallingIdentity();
3268 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003269 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003270 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 } finally {
3272 Binder.restoreCallingIdentity(origId);
3273 }
3274 }
3275 }
3276
3277 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003278 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 != PackageManager.PERMISSION_GRANTED) {
3281 throw new SecurityException("Requires permission "
3282 + android.Manifest.permission.DEVICE_POWER);
3283 }
3284
3285 synchronized (mGlobalLock) {
3286 long ident = Binder.clearCallingIdentity();
3287 if (mKeyguardShown != keyguardShowing) {
3288 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003289 final Message msg = PooledLambda.obtainMessage(
3290 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3291 keyguardShowing);
3292 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 }
3294 try {
wilsonshih177261f2019-02-22 12:02:18 +08003295 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 } finally {
3297 Binder.restoreCallingIdentity(ident);
3298 }
3299 }
3300
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 mH.post(() -> {
3302 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3303 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3304 }
3305 });
3306 }
3307
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003308 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003309 mH.post(() -> {
3310 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3311 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3312 }
3313 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 }
3315
3316 @Override
3317 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003318 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3319 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320
3321 final File passedIconFile = new File(filePath);
3322 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3323 passedIconFile.getName());
3324 if (!legitIconFile.getPath().equals(filePath)
3325 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3326 throw new IllegalArgumentException("Bad file path: " + filePath
3327 + " passed for userId " + userId);
3328 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003329 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003330 }
3331
3332 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3335 final ActivityOptions activityOptions = safeOptions != null
3336 ? safeOptions.getOptions(mStackSupervisor)
3337 : null;
3338 if (activityOptions == null
3339 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3340 || activityOptions.getCustomInPlaceResId() == 0) {
3341 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3342 "with valid animation");
3343 }
lumark588a3e82018-07-20 18:53:54 +08003344 // Get top display of front most application.
3345 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3346 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003347 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3348 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3349 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003350 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003351 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003352 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 }
3354
3355 @Override
3356 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003357 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 synchronized (mGlobalLock) {
3359 final long ident = Binder.clearCallingIdentity();
3360 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003361 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 if (stack == null) {
3363 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3364 return;
3365 }
3366 if (!stack.isActivityTypeStandardOrUndefined()) {
3367 throw new IllegalArgumentException(
3368 "Removing non-standard stack is not allowed.");
3369 }
3370 mStackSupervisor.removeStack(stack);
3371 } finally {
3372 Binder.restoreCallingIdentity(ident);
3373 }
3374 }
3375 }
3376
3377 @Override
3378 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003379 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380
3381 synchronized (mGlobalLock) {
3382 final long ident = Binder.clearCallingIdentity();
3383 try {
3384 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3385 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003386 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 } finally {
3388 Binder.restoreCallingIdentity(ident);
3389 }
3390 }
3391 }
3392
3393 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003394 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 synchronized (mGlobalLock) {
3396 long ident = Binder.clearCallingIdentity();
3397 try {
3398 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3399 if (r == null) {
3400 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003401 "toggleFreeformWindowingMode: No activity record matching token="
3402 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003403 }
3404
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003405 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003406 if (stack == null) {
3407 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3408 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 }
3410
Yunfan Chend967af82019-01-17 18:30:18 +09003411 if (!stack.inFreeformWindowingMode()
3412 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3413 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3414 + "toggle between fullscreen and freeform.");
3415 }
3416
3417 if (stack.inFreeformWindowingMode()) {
3418 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003419 } else if (stack.getParent().inFreeformWindowingMode()) {
3420 // If the window is on a freeform display, set it to undefined. It will be
3421 // resolved to freeform and it can adjust windowing mode when the display mode
3422 // changes in runtime.
3423 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003424 } else {
3425 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3426 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 } finally {
3428 Binder.restoreCallingIdentity(ident);
3429 }
3430 }
3431 }
3432
3433 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3434 @Override
3435 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003436 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003438 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 }
3440
3441 /** Unregister a task stack listener so that it stops receiving callbacks. */
3442 @Override
3443 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003444 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003446 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 }
3448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 @Override
3450 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3451 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3452 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3453 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3454 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3455 }
3456
3457 @Override
3458 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3459 IBinder activityToken, int flags) {
3460 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3461 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3462 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3463 }
3464
3465 @Override
3466 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3467 Bundle args) {
3468 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3469 true /* focused */, true /* newSessionId */, userHandle, args,
3470 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3471 }
3472
3473 @Override
3474 public Bundle getAssistContextExtras(int requestType) {
3475 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3476 null, null, true /* focused */, true /* newSessionId */,
3477 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3478 if (pae == null) {
3479 return null;
3480 }
3481 synchronized (pae) {
3482 while (!pae.haveResult) {
3483 try {
3484 pae.wait();
3485 } catch (InterruptedException e) {
3486 }
3487 }
3488 }
3489 synchronized (mGlobalLock) {
3490 buildAssistBundleLocked(pae, pae.result);
3491 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003492 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 }
3494 return pae.extras;
3495 }
3496
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003497 /**
3498 * Binder IPC calls go through the public entry point.
3499 * This can be called with or without the global lock held.
3500 */
3501 private static int checkCallingPermission(String permission) {
3502 return checkPermission(
3503 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3504 }
3505
3506 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003507 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003508 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3509 mAmInternal.enforceCallingPermission(permission, func);
3510 }
3511 }
3512
3513 @VisibleForTesting
3514 int checkGetTasksPermission(String permission, int pid, int uid) {
3515 return checkPermission(permission, pid, uid);
3516 }
3517
3518 static int checkPermission(String permission, int pid, int uid) {
3519 if (permission == null) {
3520 return PackageManager.PERMISSION_DENIED;
3521 }
3522 return checkComponentPermission(permission, pid, uid, -1, true);
3523 }
3524
Wale Ogunwale214f3482018-10-04 11:00:47 -07003525 public static int checkComponentPermission(String permission, int pid, int uid,
3526 int owningUid, boolean exported) {
3527 return ActivityManagerService.checkComponentPermission(
3528 permission, pid, uid, owningUid, exported);
3529 }
3530
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003531 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3532 if (getRecentTasks().isCallerRecents(callingUid)) {
3533 // Always allow the recents component to get tasks
3534 return true;
3535 }
3536
3537 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3538 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3539 if (!allowed) {
3540 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3541 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3542 // Temporary compatibility: some existing apps on the system image may
3543 // still be requesting the old permission and not switched to the new
3544 // one; if so, we'll still allow them full access. This means we need
3545 // to see if they are holding the old permission and are a system app.
3546 try {
3547 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3548 allowed = true;
3549 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3550 + " is using old GET_TASKS but privileged; allowing");
3551 }
3552 } catch (RemoteException e) {
3553 }
3554 }
3555 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3556 + " does not hold REAL_GET_TASKS; limiting output");
3557 }
3558 return allowed;
3559 }
3560
Nicholas Sauer0259e532019-08-30 08:24:55 -07003561 boolean isCrossUserAllowed(int pid, int uid) {
3562 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3563 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3564 }
3565
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3567 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3568 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3569 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 "enqueueAssistContext()");
3572
3573 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003574 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003575 if (activity == null) {
3576 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3577 return null;
3578 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003579 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003580 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3581 return null;
3582 }
3583 if (focused) {
3584 if (activityToken != null) {
3585 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3586 if (activity != caller) {
3587 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3588 + " is not current top " + activity);
3589 return null;
3590 }
3591 }
3592 } else {
3593 activity = ActivityRecord.forTokenLocked(activityToken);
3594 if (activity == null) {
3595 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3596 + " couldn't be found");
3597 return null;
3598 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3601 return null;
3602 }
3603 }
3604
3605 PendingAssistExtras pae;
3606 Bundle extras = new Bundle();
3607 if (args != null) {
3608 extras.putAll(args);
3609 }
3610 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003611 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612
3613 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3614 userHandle);
3615 pae.isHome = activity.isActivityTypeHome();
3616
3617 // Increment the sessionId if necessary
3618 if (newSessionId) {
3619 mViSessionId++;
3620 }
3621 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003622 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3623 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003625 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 } catch (RemoteException e) {
3627 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3628 return null;
3629 }
3630 return pae;
3631 }
3632 }
3633
3634 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3635 if (result != null) {
3636 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3637 }
3638 if (pae.hint != null) {
3639 pae.extras.putBoolean(pae.hint, true);
3640 }
3641 }
3642
3643 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3644 IAssistDataReceiver receiver;
3645 synchronized (mGlobalLock) {
3646 mPendingAssistExtras.remove(pae);
3647 receiver = pae.receiver;
3648 }
3649 if (receiver != null) {
3650 // Caller wants result sent back to them.
3651 Bundle sendBundle = new Bundle();
3652 // At least return the receiver extras
3653 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3654 try {
3655 pae.receiver.onHandleAssistData(sendBundle);
3656 } catch (RemoteException e) {
3657 }
3658 }
3659 }
3660
3661 public class PendingAssistExtras extends Binder implements Runnable {
3662 public final ActivityRecord activity;
3663 public boolean isHome;
3664 public final Bundle extras;
3665 public final Intent intent;
3666 public final String hint;
3667 public final IAssistDataReceiver receiver;
3668 public final int userHandle;
3669 public boolean haveResult = false;
3670 public Bundle result = null;
3671 public AssistStructure structure = null;
3672 public AssistContent content = null;
3673 public Bundle receiverExtras;
3674
3675 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3676 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3677 int _userHandle) {
3678 activity = _activity;
3679 extras = _extras;
3680 intent = _intent;
3681 hint = _hint;
3682 receiver = _receiver;
3683 receiverExtras = _receiverExtras;
3684 userHandle = _userHandle;
3685 }
3686
3687 @Override
3688 public void run() {
3689 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3690 synchronized (this) {
3691 haveResult = true;
3692 notifyAll();
3693 }
3694 pendingAssistExtrasTimedOut(this);
3695 }
3696 }
3697
3698 @Override
3699 public boolean isAssistDataAllowedOnCurrentActivity() {
3700 int userId;
3701 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003702 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3704 return false;
3705 }
3706
3707 final ActivityRecord activity = focusedStack.getTopActivity();
3708 if (activity == null) {
3709 return false;
3710 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003711 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003712 }
3713 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3714 }
3715
3716 @Override
3717 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3718 long ident = Binder.clearCallingIdentity();
3719 try {
3720 synchronized (mGlobalLock) {
3721 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003722 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 if (top != caller) {
3724 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3725 + " is not current top " + top);
3726 return false;
3727 }
3728 if (!top.nowVisible) {
3729 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3730 + " is not visible");
3731 return false;
3732 }
3733 }
3734 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3735 token);
3736 } finally {
3737 Binder.restoreCallingIdentity(ident);
3738 }
3739 }
3740
3741 @Override
3742 public boolean isRootVoiceInteraction(IBinder token) {
3743 synchronized (mGlobalLock) {
3744 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3745 if (r == null) {
3746 return false;
3747 }
3748 return r.rootVoiceInteraction;
3749 }
3750 }
3751
Wale Ogunwalef6733932018-06-27 05:14:34 -07003752 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3753 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3754 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3755 if (activityToCallback == null) return;
3756 activityToCallback.setVoiceSessionLocked(voiceSession);
3757
3758 // Inform the activity
3759 try {
3760 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3761 voiceInteractor);
3762 long token = Binder.clearCallingIdentity();
3763 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003764 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003765 } finally {
3766 Binder.restoreCallingIdentity(token);
3767 }
3768 // TODO: VI Should we cache the activity so that it's easier to find later
3769 // rather than scan through all the stacks and activities?
3770 } catch (RemoteException re) {
3771 activityToCallback.clearVoiceSessionLocked();
3772 // TODO: VI Should this terminate the voice session?
3773 }
3774 }
3775
3776 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3777 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3778 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3779 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3780 boolean wasRunningVoice = mRunningVoice != null;
3781 mRunningVoice = session;
3782 if (!wasRunningVoice) {
3783 mVoiceWakeLock.acquire();
3784 updateSleepIfNeededLocked();
3785 }
3786 }
3787 }
3788
3789 void finishRunningVoiceLocked() {
3790 if (mRunningVoice != null) {
3791 mRunningVoice = null;
3792 mVoiceWakeLock.release();
3793 updateSleepIfNeededLocked();
3794 }
3795 }
3796
3797 @Override
3798 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3799 synchronized (mGlobalLock) {
3800 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3801 if (keepAwake) {
3802 mVoiceWakeLock.acquire();
3803 } else {
3804 mVoiceWakeLock.release();
3805 }
3806 }
3807 }
3808 }
3809
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 @Override
3811 public ComponentName getActivityClassForToken(IBinder token) {
3812 synchronized (mGlobalLock) {
3813 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3814 if (r == null) {
3815 return null;
3816 }
3817 return r.intent.getComponent();
3818 }
3819 }
3820
3821 @Override
3822 public String getPackageForToken(IBinder token) {
3823 synchronized (mGlobalLock) {
3824 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3825 if (r == null) {
3826 return null;
3827 }
3828 return r.packageName;
3829 }
3830 }
3831
3832 @Override
3833 public void showLockTaskEscapeMessage(IBinder token) {
3834 synchronized (mGlobalLock) {
3835 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3836 if (r == null) {
3837 return;
3838 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003839 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 }
3841 }
3842
3843 @Override
3844 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003845 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 final long token = Binder.clearCallingIdentity();
3847 try {
3848 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003849 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 }
3851 } finally {
3852 Binder.restoreCallingIdentity(token);
3853 }
3854 }
3855
3856 /**
3857 * Try to place task to provided position. The final position might be different depending on
3858 * current user and stacks state. The task will be moved to target stack if it's currently in
3859 * different stack.
3860 */
3861 @Override
3862 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003863 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 synchronized (mGlobalLock) {
3865 long ident = Binder.clearCallingIdentity();
3866 try {
3867 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3868 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003869 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 if (task == null) {
3871 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3872 + taskId);
3873 }
3874
Wale Ogunwaled32da472018-11-16 07:19:28 -08003875 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876
3877 if (stack == null) {
3878 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3879 + stackId);
3880 }
3881 if (!stack.isActivityTypeStandardOrUndefined()) {
3882 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3883 + " the position of task " + taskId + " in/to non-standard stack");
3884 }
3885
3886 // TODO: Have the callers of this API call a separate reparent method if that is
3887 // what they intended to do vs. having this method also do reparenting.
3888 if (task.getStack() == stack) {
3889 // Change position in current stack.
3890 stack.positionChildAt(task, position);
3891 } else {
3892 // Reparent to new stack.
3893 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3894 !DEFER_RESUME, "positionTaskInStack");
3895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(ident);
3898 }
3899 }
3900 }
3901
3902 @Override
3903 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3904 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3905 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003906 + Arrays.toString(horizontalSizeConfiguration) + " "
3907 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 synchronized (mGlobalLock) {
3909 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3910 if (record == null) {
3911 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3912 + "found for: " + token);
3913 }
3914 record.setSizeConfigurations(horizontalSizeConfiguration,
3915 verticalSizeConfigurations, smallestSizeConfigurations);
3916 }
3917 }
3918
3919 /**
3920 * Dismisses split-screen multi-window mode.
3921 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3922 */
3923 @Override
3924 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003925 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003926 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3927 final long ident = Binder.clearCallingIdentity();
3928 try {
3929 synchronized (mGlobalLock) {
3930 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003931 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 if (stack == null) {
3933 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3934 return;
3935 }
3936
3937 if (toTop) {
3938 // Caller wants the current split-screen primary stack to be the top stack after
3939 // it goes fullscreen, so move it to the front.
3940 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003941 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003942 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003943 // stack after it goes fullscreen, so we move the focus to the top-most
3944 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3946 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3947 if (otherStack != null) {
3948 otherStack.moveToFront("dismissSplitScreenMode_other");
3949 }
3950 }
3951
Evan Rosky10475742018-09-05 19:02:48 -07003952 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 }
3954 } finally {
3955 Binder.restoreCallingIdentity(ident);
3956 }
3957 }
3958
3959 /**
3960 * Dismisses Pip
3961 * @param animate True if the dismissal should be animated.
3962 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3963 * default animation duration should be used.
3964 */
3965 @Override
3966 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003967 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003968 final long ident = Binder.clearCallingIdentity();
3969 try {
3970 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003971 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003972 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 if (stack == null) {
3974 Slog.w(TAG, "dismissPip: pinned stack not found.");
3975 return;
3976 }
3977 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3978 throw new IllegalArgumentException("Stack: " + stack
3979 + " doesn't support animated resize.");
3980 }
3981 if (animate) {
3982 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3983 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3984 } else {
3985 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3986 }
3987 }
3988 } finally {
3989 Binder.restoreCallingIdentity(ident);
3990 }
3991 }
3992
3993 @Override
3994 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 synchronized (mGlobalLock) {
3997 mSuppressResizeConfigChanges = suppress;
3998 }
3999 }
4000
4001 /**
4002 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4003 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4004 * activity and clearing the task at the same time.
4005 */
4006 @Override
4007 // TODO: API should just be about changing windowing modes...
4008 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 "moveTasksToFullscreenStack()");
4011 synchronized (mGlobalLock) {
4012 final long origId = Binder.clearCallingIdentity();
4013 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004014 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 if (stack != null){
4016 if (!stack.isActivityTypeStandardOrUndefined()) {
4017 throw new IllegalArgumentException(
4018 "You can't move tasks from non-standard stacks.");
4019 }
4020 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4021 }
4022 } finally {
4023 Binder.restoreCallingIdentity(origId);
4024 }
4025 }
4026 }
4027
4028 /**
4029 * Moves the top activity in the input stackId to the pinned stack.
4030 *
4031 * @param stackId Id of stack to move the top activity to pinned stack.
4032 * @param bounds Bounds to use for pinned stack.
4033 *
4034 * @return True if the top activity of the input stack was successfully moved to the pinned
4035 * stack.
4036 */
4037 @Override
4038 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 "moveTopActivityToPinnedStack()");
4041 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004042 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4044 + "Device doesn't support picture-in-picture mode");
4045 }
4046
4047 long ident = Binder.clearCallingIdentity();
4048 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004049 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 } finally {
4051 Binder.restoreCallingIdentity(ident);
4052 }
4053 }
4054 }
4055
4056 @Override
4057 public boolean isInMultiWindowMode(IBinder token) {
4058 final long origId = Binder.clearCallingIdentity();
4059 try {
4060 synchronized (mGlobalLock) {
4061 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4062 if (r == null) {
4063 return false;
4064 }
4065 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4066 return r.inMultiWindowMode();
4067 }
4068 } finally {
4069 Binder.restoreCallingIdentity(origId);
4070 }
4071 }
4072
4073 @Override
4074 public boolean isInPictureInPictureMode(IBinder token) {
4075 final long origId = Binder.clearCallingIdentity();
4076 try {
4077 synchronized (mGlobalLock) {
4078 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4079 }
4080 } finally {
4081 Binder.restoreCallingIdentity(origId);
4082 }
4083 }
4084
4085 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004086 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4087 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 return false;
4089 }
4090
4091 // If we are animating to fullscreen then we have already dispatched the PIP mode
4092 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004093 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4094 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 }
4096
4097 @Override
4098 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4099 final long origId = Binder.clearCallingIdentity();
4100 try {
4101 synchronized (mGlobalLock) {
4102 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4103 "enterPictureInPictureMode", token, params);
4104
4105 // If the activity is already in picture in picture mode, then just return early
4106 if (isInPictureInPictureMode(r)) {
4107 return true;
4108 }
4109
4110 // Activity supports picture-in-picture, now check that we can enter PiP at this
4111 // point, if it is
4112 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4113 false /* beforeStopping */)) {
4114 return false;
4115 }
4116
4117 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004118 synchronized (mGlobalLock) {
4119 // Only update the saved args from the args that are set
4120 r.pictureInPictureArgs.copyOnlySet(params);
4121 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4122 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4123 // Adjust the source bounds by the insets for the transition down
4124 final Rect sourceBounds = new Rect(
4125 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004126 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004127 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004128 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004129 stack.setPictureInPictureAspectRatio(aspectRatio);
4130 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004131 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4132 r.info.applicationInfo.uid, r.shortComponentName,
4133 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004134 logPictureInPictureArgs(params);
4135 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004136 };
4137
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004138 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 // If the keyguard is showing or occluded, then try and dismiss it before
4140 // entering picture-in-picture (this will prompt the user to authenticate if the
4141 // device is currently locked).
4142 dismissKeyguard(token, new KeyguardDismissCallback() {
4143 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 public void onDismissSucceeded() {
4145 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 }
4147 }, null /* message */);
4148 } else {
4149 // Enter picture in picture immediately otherwise
4150 enterPipRunnable.run();
4151 }
4152 return true;
4153 }
4154 } finally {
4155 Binder.restoreCallingIdentity(origId);
4156 }
4157 }
4158
4159 @Override
4160 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4161 final long origId = Binder.clearCallingIdentity();
4162 try {
4163 synchronized (mGlobalLock) {
4164 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4165 "setPictureInPictureParams", token, params);
4166
4167 // Only update the saved args from the args that are set
4168 r.pictureInPictureArgs.copyOnlySet(params);
4169 if (r.inPinnedWindowingMode()) {
4170 // If the activity is already in picture-in-picture, update the pinned stack now
4171 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4172 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004173 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 if (!stack.isAnimatingBoundsToFullscreen()) {
4175 stack.setPictureInPictureAspectRatio(
4176 r.pictureInPictureArgs.getAspectRatio());
4177 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4178 }
4179 }
4180 logPictureInPictureArgs(params);
4181 }
4182 } finally {
4183 Binder.restoreCallingIdentity(origId);
4184 }
4185 }
4186
4187 @Override
4188 public int getMaxNumPictureInPictureActions(IBinder token) {
4189 // Currently, this is a static constant, but later, we may change this to be dependent on
4190 // the context of the activity
4191 return 3;
4192 }
4193
4194 private void logPictureInPictureArgs(PictureInPictureParams params) {
4195 if (params.hasSetActions()) {
4196 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4197 params.getActions().size());
4198 }
4199 if (params.hasSetAspectRatio()) {
4200 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4201 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4202 MetricsLogger.action(lm);
4203 }
4204 }
4205
4206 /**
4207 * Checks the state of the system and the activity associated with the given {@param token} to
4208 * verify that picture-in-picture is supported for that activity.
4209 *
4210 * @return the activity record for the given {@param token} if all the checks pass.
4211 */
4212 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4213 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 throw new IllegalStateException(caller
4216 + ": Device doesn't support picture-in-picture mode.");
4217 }
4218
4219 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4220 if (r == null) {
4221 throw new IllegalStateException(caller
4222 + ": Can't find activity for token=" + token);
4223 }
4224
4225 if (!r.supportsPictureInPicture()) {
4226 throw new IllegalStateException(caller
4227 + ": Current activity does not support picture-in-picture.");
4228 }
4229
4230 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004231 && !mWindowManager.isValidPictureInPictureAspectRatio(
4232 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 final float minAspectRatio = mContext.getResources().getFloat(
4234 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4235 final float maxAspectRatio = mContext.getResources().getFloat(
4236 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4237 throw new IllegalArgumentException(String.format(caller
4238 + ": Aspect ratio is too extreme (must be between %f and %f).",
4239 minAspectRatio, maxAspectRatio));
4240 }
4241
4242 // Truncate the number of actions if necessary
4243 params.truncateActions(getMaxNumPictureInPictureActions(token));
4244
4245 return r;
4246 }
4247
4248 @Override
4249 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 synchronized (mGlobalLock) {
4252 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4253 if (r == null) {
4254 throw new IllegalArgumentException("Activity does not exist; token="
4255 + activityToken);
4256 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004257 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 }
4259 }
4260
4261 @Override
4262 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4263 Rect tempDockedTaskInsetBounds,
4264 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 long ident = Binder.clearCallingIdentity();
4267 try {
4268 synchronized (mGlobalLock) {
4269 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4270 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4271 PRESERVE_WINDOWS);
4272 }
4273 } finally {
4274 Binder.restoreCallingIdentity(ident);
4275 }
4276 }
4277
4278 @Override
4279 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004280 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 final long ident = Binder.clearCallingIdentity();
4282 try {
4283 synchronized (mGlobalLock) {
4284 mStackSupervisor.setSplitScreenResizing(resizing);
4285 }
4286 } finally {
4287 Binder.restoreCallingIdentity(ident);
4288 }
4289 }
4290
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 /**
4292 * Check that we have the features required for VR-related API calls, and throw an exception if
4293 * not.
4294 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004295 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 if (!mContext.getPackageManager().hasSystemFeature(
4297 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4298 throw new UnsupportedOperationException("VR mode not supported on this device!");
4299 }
4300 }
4301
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 @Override
4303 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004304 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305
4306 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4307
4308 ActivityRecord r;
4309 synchronized (mGlobalLock) {
4310 r = ActivityRecord.isInStackLocked(token);
4311 }
4312
4313 if (r == null) {
4314 throw new IllegalArgumentException();
4315 }
4316
4317 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004318 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 VrManagerInternal.NO_ERROR) {
4320 return err;
4321 }
4322
4323 // Clear the binder calling uid since this path may call moveToTask().
4324 final long callingId = Binder.clearCallingIdentity();
4325 try {
4326 synchronized (mGlobalLock) {
4327 r.requestedVrComponent = (enabled) ? packageName : null;
4328
4329 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004330 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004331 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 }
4333 return 0;
4334 }
4335 } finally {
4336 Binder.restoreCallingIdentity(callingId);
4337 }
4338 }
4339
4340 @Override
4341 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4342 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4343 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004344 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4346 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4347 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004348 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 || activity.voiceSession != null) {
4350 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4351 return;
4352 }
4353 if (activity.pendingVoiceInteractionStart) {
4354 Slog.w(TAG, "Pending start of voice interaction already.");
4355 return;
4356 }
4357 activity.pendingVoiceInteractionStart = true;
4358 }
4359 LocalServices.getService(VoiceInteractionManagerInternal.class)
4360 .startLocalVoiceInteraction(callingActivity, options);
4361 }
4362
4363 @Override
4364 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4365 LocalServices.getService(VoiceInteractionManagerInternal.class)
4366 .stopLocalVoiceInteraction(callingActivity);
4367 }
4368
4369 @Override
4370 public boolean supportsLocalVoiceInteraction() {
4371 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4372 .supportsLocalVoiceInteraction();
4373 }
4374
4375 /** Notifies all listeners when the pinned stack animation starts. */
4376 @Override
4377 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380
4381 /** Notifies all listeners when the pinned stack animation ends. */
4382 @Override
4383 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004384 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 }
4386
4387 @Override
4388 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 final long ident = Binder.clearCallingIdentity();
4391 try {
4392 synchronized (mGlobalLock) {
4393 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4394 }
4395 } finally {
4396 Binder.restoreCallingIdentity(ident);
4397 }
4398 }
4399
4400 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403
4404 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004405 if (mWindowManager == null) {
4406 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4407 return false;
4408 }
4409
4410 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
4414
Riddle Hsua0022cd2019-09-09 21:12:41 +08004415 mH.sendMessage(PooledLambda.obtainMessage(
4416 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4417 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418
4419 final long origId = Binder.clearCallingIdentity();
4420 try {
4421 if (values != null) {
4422 Settings.System.clearConfiguration(values);
4423 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 UserHandle.USER_NULL, false /* deferResume */,
4426 mTmpUpdateConfigurationResult);
4427 return mTmpUpdateConfigurationResult.changes != 0;
4428 } finally {
4429 Binder.restoreCallingIdentity(origId);
4430 }
4431 }
4432 }
4433
4434 @Override
4435 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4436 CharSequence message) {
4437 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4440 }
4441 final long callingId = Binder.clearCallingIdentity();
4442 try {
4443 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004444 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 }
4446 } finally {
4447 Binder.restoreCallingIdentity(callingId);
4448 }
4449 }
4450
4451 @Override
4452 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 "cancelTaskWindowTransition()");
4455 final long ident = Binder.clearCallingIdentity();
4456 try {
4457 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004458 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 MATCH_TASK_IN_STACKS_ONLY);
4460 if (task == null) {
4461 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4462 return;
4463 }
4464 task.cancelWindowTransition();
4465 }
4466 } finally {
4467 Binder.restoreCallingIdentity(ident);
4468 }
4469 }
4470
4471 @Override
4472 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 final long ident = Binder.clearCallingIdentity();
4475 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004476 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 } finally {
4478 Binder.restoreCallingIdentity(ident);
4479 }
4480 }
4481
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004482 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4483 boolean restoreFromDisk) {
4484 final TaskRecord task;
4485 synchronized (mGlobalLock) {
4486 task = mRootActivityContainer.anyTaskForId(taskId,
4487 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4488 if (task == null) {
4489 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4490 return null;
4491 }
4492 }
4493 // Don't call this while holding the lock as this operation might hit the disk.
4494 return task.getSnapshot(reducedResolution, restoreFromDisk);
4495 }
4496
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 @Override
4498 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4499 synchronized (mGlobalLock) {
4500 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4501 if (r == null) {
4502 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4503 + token);
4504 return;
4505 }
4506 final long origId = Binder.clearCallingIdentity();
4507 try {
4508 r.setDisablePreviewScreenshots(disable);
4509 } finally {
4510 Binder.restoreCallingIdentity(origId);
4511 }
4512 }
4513 }
4514
4515 /** Return the user id of the last resumed activity. */
4516 @Override
4517 public @UserIdInt
4518 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4521 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004522 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004523 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004524 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004525 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 }
4527 }
4528
4529 @Override
4530 public void updateLockTaskFeatures(int userId, int flags) {
4531 final int callingUid = Binder.getCallingUid();
4532 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004533 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 "updateLockTaskFeatures()");
4535 }
4536 synchronized (mGlobalLock) {
4537 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4538 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004539 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 }
4541 }
4542
4543 @Override
4544 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4545 synchronized (mGlobalLock) {
4546 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4547 if (r == null) {
4548 return;
4549 }
4550 final long origId = Binder.clearCallingIdentity();
4551 try {
4552 r.setShowWhenLocked(showWhenLocked);
4553 } finally {
4554 Binder.restoreCallingIdentity(origId);
4555 }
4556 }
4557 }
4558
4559 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004560 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4561 synchronized (mGlobalLock) {
4562 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4563 if (r == null) {
4564 return;
4565 }
4566 final long origId = Binder.clearCallingIdentity();
4567 try {
4568 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4569 } finally {
4570 Binder.restoreCallingIdentity(origId);
4571 }
4572 }
4573 }
4574
4575 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4577 synchronized (mGlobalLock) {
4578 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4579 if (r == null) {
4580 return;
4581 }
4582 final long origId = Binder.clearCallingIdentity();
4583 try {
4584 r.setTurnScreenOn(turnScreenOn);
4585 } finally {
4586 Binder.restoreCallingIdentity(origId);
4587 }
4588 }
4589 }
4590
4591 @Override
4592 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004593 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004595 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 synchronized (mGlobalLock) {
4597 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4598 if (r == null) {
4599 return;
4600 }
4601 final long origId = Binder.clearCallingIdentity();
4602 try {
4603 r.registerRemoteAnimations(definition);
4604 } finally {
4605 Binder.restoreCallingIdentity(origId);
4606 }
4607 }
4608 }
4609
4610 @Override
4611 public void registerRemoteAnimationForNextActivityStart(String packageName,
4612 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004613 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004614 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004615 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004616 synchronized (mGlobalLock) {
4617 final long origId = Binder.clearCallingIdentity();
4618 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004619 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004620 packageName, adapter);
4621 } finally {
4622 Binder.restoreCallingIdentity(origId);
4623 }
4624 }
4625 }
4626
Evan Rosky966759f2019-01-15 10:33:58 -08004627 @Override
4628 public void registerRemoteAnimationsForDisplay(int displayId,
4629 RemoteAnimationDefinition definition) {
4630 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4631 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004632 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004633 synchronized (mGlobalLock) {
4634 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4635 if (display == null) {
4636 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4637 return;
4638 }
4639 final long origId = Binder.clearCallingIdentity();
4640 try {
4641 display.mDisplayContent.registerRemoteAnimations(definition);
4642 } finally {
4643 Binder.restoreCallingIdentity(origId);
4644 }
4645 }
4646 }
4647
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4649 @Override
4650 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4651 synchronized (mGlobalLock) {
4652 final long origId = Binder.clearCallingIdentity();
4653 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004654 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 } finally {
4656 Binder.restoreCallingIdentity(origId);
4657 }
4658 }
4659 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004660
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004661 @Override
4662 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004663 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004665 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004666 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004667 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004668 }
4669 }
4670
4671 @Override
4672 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004674 != PERMISSION_GRANTED) {
4675 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4676 + Binder.getCallingPid()
4677 + ", uid=" + Binder.getCallingUid()
4678 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4679 Slog.w(TAG, msg);
4680 throw new SecurityException(msg);
4681 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004682 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004683 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004684 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004685 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004686 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004687 }
4688 }
4689
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004690 @Override
4691 public void stopAppSwitches() {
4692 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4693 synchronized (mGlobalLock) {
4694 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004695 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 mDidAppSwitch = false;
4697 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4698 }
4699 }
4700
4701 @Override
4702 public void resumeAppSwitches() {
4703 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4704 synchronized (mGlobalLock) {
4705 // Note that we don't execute any pending app switches... we will
4706 // let those wait until either the timeout, or the next start
4707 // activity request.
4708 mAppSwitchesAllowedTime = 0;
4709 }
4710 }
4711
Ricky Wai906af482019-06-03 17:25:28 +01004712 long getLastStopAppSwitchesTime() {
4713 return mLastStopAppSwitchesTime;
4714 }
4715
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004716 void onStartActivitySetDidAppSwitch() {
4717 if (mDidAppSwitch) {
4718 // This is the second allowed switch since we stopped switches, so now just generally
4719 // allow switches. Use case:
4720 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4721 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4722 // anyone to switch again).
4723 mAppSwitchesAllowedTime = 0;
4724 } else {
4725 mDidAppSwitch = true;
4726 }
4727 }
4728
4729 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 boolean shouldDisableNonVrUiLocked() {
4731 return mVrController.shouldDisableNonVrUiLocked();
4732 }
4733
Wale Ogunwale53783742018-09-16 10:21:51 -07004734 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 // 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 +00004736 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004738 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4739 + " to main display for VR");
4740 mRootActivityContainer.moveStackToDisplay(
4741 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 }
4743 mH.post(() -> {
4744 if (!mVrController.onVrModeChanged(r)) {
4745 return;
4746 }
4747 synchronized (mGlobalLock) {
4748 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4749 mWindowManager.disableNonVrUi(disableNonVrUi);
4750 if (disableNonVrUi) {
4751 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4752 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004753 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004754 }
4755 }
4756 });
4757 }
4758
Wale Ogunwale53783742018-09-16 10:21:51 -07004759 @Override
4760 public int getPackageScreenCompatMode(String packageName) {
4761 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4762 synchronized (mGlobalLock) {
4763 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4764 }
4765 }
4766
4767 @Override
4768 public void setPackageScreenCompatMode(String packageName, int mode) {
4769 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4770 "setPackageScreenCompatMode");
4771 synchronized (mGlobalLock) {
4772 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4773 }
4774 }
4775
4776 @Override
4777 public boolean getPackageAskScreenCompat(String packageName) {
4778 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4779 synchronized (mGlobalLock) {
4780 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4781 }
4782 }
4783
4784 @Override
4785 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4786 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4787 "setPackageAskScreenCompat");
4788 synchronized (mGlobalLock) {
4789 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4790 }
4791 }
4792
Wale Ogunwale64258362018-10-16 15:13:37 -07004793 public static String relaunchReasonToString(int relaunchReason) {
4794 switch (relaunchReason) {
4795 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4796 return "window_resize";
4797 case RELAUNCH_REASON_FREE_RESIZE:
4798 return "free_resize";
4799 default:
4800 return null;
4801 }
4802 }
4803
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004804 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004805 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004806 }
4807
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004808 /** Pokes the task persister. */
4809 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4810 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4811 }
4812
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004813 boolean isKeyguardLocked() {
4814 return mKeyguardController.isKeyguardLocked();
4815 }
4816
Garfield Tan01548632018-11-27 10:15:48 -08004817 /**
4818 * Clears launch params for the given package.
4819 * @param packageNames the names of the packages of which the launch params are to be cleared
4820 */
4821 @Override
4822 public void clearLaunchParamsForPackages(List<String> packageNames) {
4823 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4824 "clearLaunchParamsForPackages");
4825 synchronized (mGlobalLock) {
4826 for (int i = 0; i < packageNames.size(); ++i) {
4827 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4828 }
4829 }
4830 }
4831
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004832 /**
4833 * Makes the display with the given id a single task instance display. I.e the display can only
4834 * contain one task.
4835 */
4836 @Override
4837 public void setDisplayToSingleTaskInstance(int displayId) {
4838 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4839 "setDisplayToSingleTaskInstance");
4840 final long origId = Binder.clearCallingIdentity();
4841 try {
4842 final ActivityDisplay display =
4843 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4844 if (display != null) {
4845 display.setDisplayToSingleTaskInstance();
4846 }
4847 } finally {
4848 Binder.restoreCallingIdentity(origId);
4849 }
4850 }
4851
Wale Ogunwale31913b52018-10-13 08:29:31 -07004852 void dumpLastANRLocked(PrintWriter pw) {
4853 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4854 if (mLastANRState == null) {
4855 pw.println(" <no ANR has occurred since boot>");
4856 } else {
4857 pw.println(mLastANRState);
4858 }
4859 }
4860
4861 void dumpLastANRTracesLocked(PrintWriter pw) {
4862 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4863
4864 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4865 if (ArrayUtils.isEmpty(files)) {
4866 pw.println(" <no ANR has occurred since boot>");
4867 return;
4868 }
4869 // Find the latest file.
4870 File latest = null;
4871 for (File f : files) {
4872 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4873 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004874 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004875 }
4876 pw.print("File: ");
4877 pw.print(latest.getName());
4878 pw.println();
4879 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4880 String line;
4881 while ((line = in.readLine()) != null) {
4882 pw.println(line);
4883 }
4884 } catch (IOException e) {
4885 pw.print("Unable to read: ");
4886 pw.print(e);
4887 pw.println();
4888 }
4889 }
4890
4891 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4892 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4893 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4894 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4895 }
4896
4897 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4898 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4899 pw.println(header);
4900
Wale Ogunwaled32da472018-11-16 07:19:28 -08004901 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004902 dumpPackage);
4903 boolean needSep = printedAnything;
4904
4905 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004906 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004907 " ResumedActivity: ");
4908 if (printed) {
4909 printedAnything = true;
4910 needSep = false;
4911 }
4912
4913 if (dumpPackage == null) {
4914 if (needSep) {
4915 pw.println();
4916 }
4917 printedAnything = true;
4918 mStackSupervisor.dump(pw, " ");
4919 }
4920
4921 if (!printedAnything) {
4922 pw.println(" (nothing)");
4923 }
4924 }
4925
4926 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004927 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004928 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004929 pw.println(" ");
4930 }
4931
4932 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4933 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4934 getActivityStartController().dump(pw, "", dumpPackage);
4935 }
4936
4937 /**
4938 * There are three things that cmd can be:
4939 * - a flattened component name that matches an existing activity
4940 * - the cmd arg isn't the flattened component name of an existing activity:
4941 * dump all activity whose component contains the cmd as a substring
4942 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004943 * <p>
4944 * The caller should not hold lock when calling this method because it will wait for the
4945 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004946 *
4947 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4948 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4949 */
4950 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4951 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4952 ArrayList<ActivityRecord> activities;
4953
4954 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004955 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004956 dumpFocusedStackOnly);
4957 }
4958
4959 if (activities.size() <= 0) {
4960 return false;
4961 }
4962
4963 String[] newArgs = new String[args.length - opti];
4964 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4965
4966 TaskRecord lastTask = null;
4967 boolean needSep = false;
4968 for (int i = activities.size() - 1; i >= 0; i--) {
4969 ActivityRecord r = activities.get(i);
4970 if (needSep) {
4971 pw.println();
4972 }
4973 needSep = true;
4974 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004975 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 if (lastTask != task) {
4977 lastTask = task;
4978 pw.print("TASK "); pw.print(lastTask.affinity);
4979 pw.print(" id="); pw.print(lastTask.taskId);
4980 pw.print(" userId="); pw.println(lastTask.userId);
4981 if (dumpAll) {
4982 lastTask.dump(pw, " ");
4983 }
4984 }
4985 }
4986 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4987 }
4988 return true;
4989 }
4990
4991 /**
4992 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4993 * there is a thread associated with the activity.
4994 */
4995 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4996 final ActivityRecord r, String[] args, boolean dumpAll) {
4997 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004998 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 synchronized (mGlobalLock) {
5000 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5001 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5002 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005003 if (r.hasProcess()) {
5004 pw.println(r.app.getPid());
5005 appThread = r.app.getThread();
5006 } else {
5007 pw.println("(not running)");
5008 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 if (dumpAll) {
5010 r.dump(pw, innerPrefix);
5011 }
5012 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005013 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005014 // flush anything that is already in the PrintWriter since the thread is going
5015 // to write to the file descriptor directly
5016 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005017 try (TransferPipe tp = new TransferPipe()) {
5018 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5019 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005020 } catch (IOException e) {
5021 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5022 } catch (RemoteException e) {
5023 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5024 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005026 }
5027
sanryhuang498e77e2018-12-06 14:57:01 +08005028 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5029 boolean testPssMode) {
5030 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5031 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5032 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005033 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005034 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5035 st.toString());
5036 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005037 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5038 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5039 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005040 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5041 testPssMode);
5042 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005043 }
5044
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045 int getCurrentUserId() {
5046 return mAmInternal.getCurrentUserId();
5047 }
5048
5049 private void enforceNotIsolatedCaller(String caller) {
5050 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5051 throw new SecurityException("Isolated process not allowed to call " + caller);
5052 }
5053 }
5054
Wale Ogunwalef6733932018-06-27 05:14:34 -07005055 public Configuration getConfiguration() {
5056 Configuration ci;
5057 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005058 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005059 ci.userSetLocale = false;
5060 }
5061 return ci;
5062 }
5063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064 /**
5065 * Current global configuration information. Contains general settings for the entire system,
5066 * also corresponds to the merged configuration of the default display.
5067 */
5068 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005069 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 }
5071
5072 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5073 boolean initLocale) {
5074 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5075 }
5076
5077 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5078 boolean initLocale, boolean deferResume) {
5079 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5080 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5081 UserHandle.USER_NULL, deferResume);
5082 }
5083
Wale Ogunwale59507092018-10-29 09:00:30 -07005084 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005085 final long origId = Binder.clearCallingIdentity();
5086 try {
5087 synchronized (mGlobalLock) {
5088 updateConfigurationLocked(values, null, false, true, userId,
5089 false /* deferResume */);
5090 }
5091 } finally {
5092 Binder.restoreCallingIdentity(origId);
5093 }
5094 }
5095
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005096 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5097 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5098 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5099 deferResume, null /* result */);
5100 }
5101
5102 /**
5103 * Do either or both things: (1) change the current configuration, and (2)
5104 * make sure the given activity is running with the (now) current
5105 * configuration. Returns true if the activity has been left running, or
5106 * false if <var>starting</var> is being destroyed to match the new
5107 * configuration.
5108 *
5109 * @param userId is only used when persistent parameter is set to true to persist configuration
5110 * for that particular user
5111 */
5112 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5113 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5114 ActivityTaskManagerService.UpdateConfigurationResult result) {
5115 int changes = 0;
5116 boolean kept = true;
5117
Riddle Hsua0022cd2019-09-09 21:12:41 +08005118 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 try {
5120 if (values != null) {
5121 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5122 deferResume);
5123 }
5124
5125 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5126 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005127 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 }
5129
5130 if (result != null) {
5131 result.changes = changes;
5132 result.activityRelaunched = !kept;
5133 }
5134 return kept;
5135 }
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005138 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005140
5141 final ActivityDisplay defaultDisplay =
5142 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5143
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005144 mTempConfig.setTo(getGlobalConfiguration());
5145 final int changes = mTempConfig.updateFrom(values);
5146 if (changes == 0) {
5147 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5148 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5149 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5150 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005151 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 return 0;
5153 }
5154
5155 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5156 "Updating global configuration to: " + values);
5157
5158 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5159 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5160 values.colorMode,
5161 values.densityDpi,
5162 values.fontScale,
5163 values.hardKeyboardHidden,
5164 values.keyboard,
5165 values.keyboardHidden,
5166 values.mcc,
5167 values.mnc,
5168 values.navigation,
5169 values.navigationHidden,
5170 values.orientation,
5171 values.screenHeightDp,
5172 values.screenLayout,
5173 values.screenWidthDp,
5174 values.smallestScreenWidthDp,
5175 values.touchscreen,
5176 values.uiMode);
5177
5178
5179 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5180 final LocaleList locales = values.getLocales();
5181 int bestLocaleIndex = 0;
5182 if (locales.size() > 1) {
5183 if (mSupportedSystemLocales == null) {
5184 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5185 }
5186 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5187 }
5188 SystemProperties.set("persist.sys.locale",
5189 locales.get(bestLocaleIndex).toLanguageTag());
5190 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005191
5192 final Message m = PooledLambda.obtainMessage(
5193 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5194 locales.get(bestLocaleIndex));
5195 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196 }
5197
Yunfan Chen75157d72018-07-27 14:47:21 +09005198 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199
5200 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005201 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202
5203 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5204 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005205 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206
5207 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209
5210 AttributeCache ac = AttributeCache.instance();
5211 if (ac != null) {
5212 ac.updateConfiguration(mTempConfig);
5213 }
5214
5215 // Make sure all resources in our process are updated right now, so that anyone who is going
5216 // to retrieve resource values after we return will be sure to get the new ones. This is
5217 // especially important during boot, where the first config change needs to guarantee all
5218 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005219 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220
5221 // We need another copy of global config because we're scheduling some calls instead of
5222 // running them in place. We need to be sure that object we send will be handled unchanged.
5223 final Configuration configCopy = new Configuration(mTempConfig);
5224 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005225 final Message msg = PooledLambda.obtainMessage(
5226 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5227 this, userId, configCopy);
5228 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 }
5230
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005231 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5232 for (int i = pidMap.size() - 1; i >= 0; i--) {
5233 final int pid = pidMap.keyAt(i);
5234 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005235 if (DEBUG_CONFIGURATION) {
5236 Slog.v(TAG_CONFIGURATION, "Update process config of "
5237 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005239 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 }
5241
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005242 final Message msg = PooledLambda.obtainMessage(
5243 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5244 mAmInternal, changes, initLocale);
5245 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246
5247 // Override configuration of the default display duplicates global config, so we need to
5248 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005249 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5250 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251
5252 return changes;
5253 }
5254
Riddle Hsua0022cd2019-09-09 21:12:41 +08005255 /** @see WindowSurfacePlacer#deferLayout */
5256 void deferWindowLayout() {
5257 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5258 // Reset the reasons at the first entrance because we only care about the changes in the
5259 // deferred scope.
5260 mLayoutReasons = 0;
5261 }
5262
5263 mWindowManager.mWindowPlacerLocked.deferLayout();
5264 }
5265
5266 /** @see WindowSurfacePlacer#continueLayout */
5267 void continueWindowLayout() {
5268 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5269 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5270 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5271 }
5272 }
5273
5274 /**
5275 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5276 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5277 * defer count is gone.
5278 */
5279 void addWindowLayoutReasons(@LayoutReason int reasons) {
5280 mLayoutReasons |= reasons;
5281 }
5282
Wale Ogunwalef6733932018-06-27 05:14:34 -07005283 private void updateEventDispatchingLocked(boolean booted) {
5284 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5285 }
5286
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005287 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5288 final ContentResolver resolver = mContext.getContentResolver();
5289 Settings.System.putConfigurationForUser(resolver, config, userId);
5290 }
5291
5292 private void sendLocaleToMountDaemonMsg(Locale l) {
5293 try {
5294 IBinder service = ServiceManager.getService("mount");
5295 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5296 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5297 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5298 } catch (RemoteException e) {
5299 Log.e(TAG, "Error storing locale for decryption UI", e);
5300 }
5301 }
5302
Alison Cichowlas3e340502018-08-07 17:15:01 -04005303 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5304 mStartActivitySources.remove(permissionToken);
5305 mExpiredStartAsCallerTokens.add(permissionToken);
5306 }
5307
5308 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5309 mExpiredStartAsCallerTokens.remove(permissionToken);
5310 }
5311
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005312 boolean isActivityStartsLoggingEnabled() {
5313 return mAmInternal.isActivityStartsLoggingEnabled();
5314 }
5315
Michal Karpinski8596ded2018-11-14 14:43:48 +00005316 boolean isBackgroundActivityStartsEnabled() {
5317 return mAmInternal.isBackgroundActivityStartsEnabled();
5318 }
5319
Wale Ogunwalef6733932018-06-27 05:14:34 -07005320 void enableScreenAfterBoot(boolean booted) {
5321 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5322 SystemClock.uptimeMillis());
5323 mWindowManager.enableScreenAfterBoot();
5324
5325 synchronized (mGlobalLock) {
5326 updateEventDispatchingLocked(booted);
5327 }
5328 }
5329
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005330 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5331 if (r == null || !r.hasProcess()) {
5332 return KEY_DISPATCHING_TIMEOUT_MS;
5333 }
5334 return getInputDispatchingTimeoutLocked(r.app);
5335 }
5336
5337 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005338 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005339 }
5340
Wale Ogunwalef6733932018-06-27 05:14:34 -07005341 /**
5342 * Decide based on the configuration whether we should show the ANR,
5343 * crash, etc dialogs. The idea is that if there is no affordance to
5344 * press the on-screen buttons, or the user experience would be more
5345 * greatly impacted than the crash itself, we shouldn't show the dialog.
5346 *
5347 * A thought: SystemUI might also want to get told about this, the Power
5348 * dialog / global actions also might want different behaviors.
5349 */
5350 private void updateShouldShowDialogsLocked(Configuration config) {
5351 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5352 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5353 && config.navigation == Configuration.NAVIGATION_NONAV);
5354 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5355 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5356 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5357 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5358 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5359 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5360 HIDE_ERROR_DIALOGS, 0) != 0;
5361 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5362 }
5363
5364 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5365 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5366 FONT_SCALE, 1.0f, userId);
5367
5368 synchronized (this) {
5369 if (getGlobalConfiguration().fontScale == scaleFactor) {
5370 return;
5371 }
5372
5373 final Configuration configuration
5374 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5375 configuration.fontScale = scaleFactor;
5376 updatePersistentConfiguration(configuration, userId);
5377 }
5378 }
5379
5380 // Actually is sleeping or shutting down or whatever else in the future
5381 // is an inactive state.
5382 boolean isSleepingOrShuttingDownLocked() {
5383 return isSleepingLocked() || mShuttingDown;
5384 }
5385
5386 boolean isSleepingLocked() {
5387 return mSleeping;
5388 }
5389
Riddle Hsu16567132018-08-16 21:37:47 +08005390 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005391 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005392 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005393 if (task.isActivityTypeStandard()) {
5394 if (mCurAppTimeTracker != r.appTimeTracker) {
5395 // We are switching app tracking. Complete the current one.
5396 if (mCurAppTimeTracker != null) {
5397 mCurAppTimeTracker.stop();
5398 mH.obtainMessage(
5399 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005400 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005401 mCurAppTimeTracker = null;
5402 }
5403 if (r.appTimeTracker != null) {
5404 mCurAppTimeTracker = r.appTimeTracker;
5405 startTimeTrackingFocusedActivityLocked();
5406 }
5407 } else {
5408 startTimeTrackingFocusedActivityLocked();
5409 }
5410 } else {
5411 r.appTimeTracker = null;
5412 }
5413 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5414 // TODO: Probably not, because we don't want to resume voice on switching
5415 // back to this activity
5416 if (task.voiceInteractor != null) {
5417 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5418 } else {
5419 finishRunningVoiceLocked();
5420
5421 if (mLastResumedActivity != null) {
5422 final IVoiceInteractionSession session;
5423
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005424 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 if (lastResumedActivityTask != null
5426 && lastResumedActivityTask.voiceSession != null) {
5427 session = lastResumedActivityTask.voiceSession;
5428 } else {
5429 session = mLastResumedActivity.voiceSession;
5430 }
5431
5432 if (session != null) {
5433 // We had been in a voice interaction session, but now focused has
5434 // move to something different. Just finish the session, we can't
5435 // return to it and retain the proper state and synchronization with
5436 // the voice interaction service.
5437 finishVoiceTask(session);
5438 }
5439 }
5440 }
5441
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005442 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5443 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005444 }
5445 updateResumedAppTrace(r);
5446 mLastResumedActivity = r;
5447
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005448 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449
5450 applyUpdateLockStateLocked(r);
5451 applyUpdateVrModeLocked(r);
5452
5453 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005454 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 r == null ? "NULL" : r.shortComponentName,
5456 reason);
5457 }
5458
5459 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5460 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005461 final ActivityTaskManagerInternal.SleepToken token =
5462 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 updateSleepIfNeededLocked();
5464 return token;
5465 }
5466 }
5467
5468 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005469 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 final boolean wasSleeping = mSleeping;
5471 boolean updateOomAdj = false;
5472
5473 if (!shouldSleep) {
5474 // If wasSleeping is true, we need to wake up activity manager state from when
5475 // we started sleeping. In either case, we need to apply the sleep tokens, which
5476 // will wake up stacks or put them to sleep as appropriate.
5477 if (wasSleeping) {
5478 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005479 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5480 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 startTimeTrackingFocusedActivityLocked();
5482 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005483 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005484 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5485 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005486 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005487 if (wasSleeping) {
5488 updateOomAdj = true;
5489 }
5490 } else if (!mSleeping && shouldSleep) {
5491 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005492 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5493 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 if (mCurAppTimeTracker != null) {
5495 mCurAppTimeTracker.stop();
5496 }
5497 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005498 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499 mStackSupervisor.goingToSleepLocked();
5500 updateResumedAppTrace(null /* resumed */);
5501 updateOomAdj = true;
5502 }
5503 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005504 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 }
5506 }
5507
5508 void updateOomAdj() {
5509 mH.post(mAmInternal::updateOomAdj);
5510 }
5511
Wale Ogunwale53783742018-09-16 10:21:51 -07005512 void updateCpuStats() {
5513 mH.post(mAmInternal::updateCpuStats);
5514 }
5515
Hui Yu03d12402018-12-06 18:00:37 -08005516 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5517 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005518 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5519 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005520 mH.sendMessage(m);
5521 }
5522
Hui Yu03d12402018-12-06 18:00:37 -08005523 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005524 ComponentName taskRoot = null;
5525 final TaskRecord task = activity.getTaskRecord();
5526 if (task != null) {
5527 final ActivityRecord rootActivity = task.getRootActivity();
5528 if (rootActivity != null) {
5529 taskRoot = rootActivity.mActivityComponent;
5530 }
5531 }
5532
Hui Yu03d12402018-12-06 18:00:37 -08005533 final Message m = PooledLambda.obtainMessage(
5534 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005535 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005536 mH.sendMessage(m);
5537 }
5538
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005539 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5540 String hostingType) {
5541 try {
5542 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5543 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5544 + activity.processName);
5545 }
5546 // Post message to start process to avoid possible deadlock of calling into AMS with the
5547 // ATMS lock held.
5548 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5549 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5550 isTop, hostingType, activity.intent.getComponent());
5551 mH.sendMessage(m);
5552 } finally {
5553 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5554 }
5555 }
5556
Wale Ogunwale53783742018-09-16 10:21:51 -07005557 void setBooting(boolean booting) {
5558 mAmInternal.setBooting(booting);
5559 }
5560
5561 boolean isBooting() {
5562 return mAmInternal.isBooting();
5563 }
5564
5565 void setBooted(boolean booted) {
5566 mAmInternal.setBooted(booted);
5567 }
5568
5569 boolean isBooted() {
5570 return mAmInternal.isBooted();
5571 }
5572
5573 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5574 mH.post(() -> {
5575 if (finishBooting) {
5576 mAmInternal.finishBooting();
5577 }
5578 if (enableScreen) {
5579 mInternal.enableScreenAfterBoot(isBooted());
5580 }
5581 });
5582 }
5583
5584 void setHeavyWeightProcess(ActivityRecord root) {
5585 mHeavyWeightProcess = root.app;
5586 final Message m = PooledLambda.obtainMessage(
5587 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005588 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005589 mH.sendMessage(m);
5590 }
5591
5592 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5593 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5594 return;
5595 }
5596
5597 mHeavyWeightProcess = null;
5598 final Message m = PooledLambda.obtainMessage(
5599 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5600 proc.mUserId);
5601 mH.sendMessage(m);
5602 }
5603
5604 private void cancelHeavyWeightProcessNotification(int userId) {
5605 final INotificationManager inm = NotificationManager.getService();
5606 if (inm == null) {
5607 return;
5608 }
5609 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005610 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005611 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5612 } catch (RuntimeException e) {
5613 Slog.w(TAG, "Error canceling notification for service", e);
5614 } catch (RemoteException e) {
5615 }
5616
5617 }
5618
5619 private void postHeavyWeightProcessNotification(
5620 WindowProcessController proc, Intent intent, int userId) {
5621 if (proc == null) {
5622 return;
5623 }
5624
5625 final INotificationManager inm = NotificationManager.getService();
5626 if (inm == null) {
5627 return;
5628 }
5629
5630 try {
5631 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5632 String text = mContext.getString(R.string.heavy_weight_notification,
5633 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5634 Notification notification =
5635 new Notification.Builder(context,
5636 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5637 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5638 .setWhen(0)
5639 .setOngoing(true)
5640 .setTicker(text)
5641 .setColor(mContext.getColor(
5642 com.android.internal.R.color.system_notification_accent_color))
5643 .setContentTitle(text)
5644 .setContentText(
5645 mContext.getText(R.string.heavy_weight_notification_detail))
5646 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5647 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5648 new UserHandle(userId)))
5649 .build();
5650 try {
5651 inm.enqueueNotificationWithTag("android", "android", null,
5652 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5653 } catch (RuntimeException e) {
5654 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5655 } catch (RemoteException e) {
5656 }
5657 } catch (PackageManager.NameNotFoundException e) {
5658 Slog.w(TAG, "Unable to create context for heavy notification", e);
5659 }
5660
5661 }
5662
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005663 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5664 IBinder token, String resultWho, int requestCode, Intent[] intents,
5665 String[] resolvedTypes, int flags, Bundle bOptions) {
5666
5667 ActivityRecord activity = null;
5668 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5669 activity = ActivityRecord.isInStackLocked(token);
5670 if (activity == null) {
5671 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5672 return null;
5673 }
5674 if (activity.finishing) {
5675 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5676 return null;
5677 }
5678 }
5679
5680 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5681 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5682 bOptions);
5683 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5684 if (noCreate) {
5685 return rec;
5686 }
5687 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5688 if (activity.pendingResults == null) {
5689 activity.pendingResults = new HashSet<>();
5690 }
5691 activity.pendingResults.add(rec.ref);
5692 }
5693 return rec;
5694 }
5695
Andrii Kulian52d255c2018-07-13 11:32:19 -07005696 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005697 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005698 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005699 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5700 mCurAppTimeTracker.start(resumedActivity.packageName);
5701 }
5702 }
5703
5704 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5705 if (mTracedResumedActivity != null) {
5706 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5707 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5708 }
5709 if (resumed != null) {
5710 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5711 constructResumedTraceName(resumed.packageName), 0);
5712 }
5713 mTracedResumedActivity = resumed;
5714 }
5715
5716 private String constructResumedTraceName(String packageName) {
5717 return "focused app: " + packageName;
5718 }
5719
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005720 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005721 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005722 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005723 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005724 // mainStack is null during startup.
5725 if (mainStack != null) {
5726 if (changes != 0 && starting == null) {
5727 // If the configuration changed, and the caller is not already
5728 // in the process of starting an activity, then find the top
5729 // activity to check if its configuration needs to change.
5730 starting = mainStack.topRunningActivityLocked();
5731 }
5732
5733 if (starting != null) {
5734 kept = starting.ensureActivityConfiguration(changes,
5735 false /* preserveWindow */);
5736 // And we need to make sure at this point that all other activities
5737 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005738 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005739 !PRESERVE_WINDOWS);
5740 }
5741 }
5742
5743 return kept;
5744 }
5745
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005746 void scheduleAppGcsLocked() {
5747 mH.post(() -> mAmInternal.scheduleAppGcs());
5748 }
5749
Wale Ogunwale53783742018-09-16 10:21:51 -07005750 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5751 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5752 }
5753
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005754 /**
5755 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5756 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5757 * on demand.
5758 */
5759 IPackageManager getPackageManager() {
5760 return AppGlobals.getPackageManager();
5761 }
5762
5763 PackageManagerInternal getPackageManagerInternalLocked() {
5764 if (mPmInternal == null) {
5765 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5766 }
5767 return mPmInternal;
5768 }
5769
Hai Zhangf4da9be2019-05-01 13:46:06 +08005770 PermissionPolicyInternal getPermissionPolicyInternal() {
5771 if (mPermissionPolicyInternal == null) {
5772 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5773 }
5774 return mPermissionPolicyInternal;
5775 }
5776
Wale Ogunwale008163e2018-07-23 23:11:08 -07005777 AppWarnings getAppWarningsLocked() {
5778 return mAppWarnings;
5779 }
5780
Wale Ogunwale214f3482018-10-04 11:00:47 -07005781 Intent getHomeIntent() {
5782 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5783 intent.setComponent(mTopComponent);
5784 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5785 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5786 intent.addCategory(Intent.CATEGORY_HOME);
5787 }
5788 return intent;
5789 }
5790
Chilun2ef71f72018-11-16 17:57:15 +08005791 /**
5792 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5793 * activities.
5794 *
5795 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5796 * component defined in config_secondaryHomeComponent.
5797 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5798 */
5799 Intent getSecondaryHomeIntent(String preferredPackage) {
5800 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005801 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5802 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5803 if (preferredPackage == null || useSystemProvidedLauncher) {
5804 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005805 final String secondaryHomeComponent = mContext.getResources().getString(
5806 com.android.internal.R.string.config_secondaryHomeComponent);
5807 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5808 } else {
5809 intent.setPackage(preferredPackage);
5810 }
5811 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5812 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5813 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5814 }
5815 return intent;
5816 }
5817
Wale Ogunwale214f3482018-10-04 11:00:47 -07005818 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5819 if (info == null) return null;
5820 ApplicationInfo newInfo = new ApplicationInfo(info);
5821 newInfo.initForUser(userId);
5822 return newInfo;
5823 }
5824
Wale Ogunwale9c103022018-10-18 07:44:54 -07005825 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005826 if (uid == SYSTEM_UID) {
5827 // The system gets to run in any process. If there are multiple processes with the same
5828 // uid, just pick the first (this should never happen).
5829 final SparseArray<WindowProcessController> procs =
5830 mProcessNames.getMap().get(processName);
5831 if (procs == null) return null;
5832 final int procCount = procs.size();
5833 for (int i = 0; i < procCount; i++) {
5834 final int procUid = procs.keyAt(i);
5835 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5836 // Don't use an app process or different user process for system component.
5837 continue;
5838 }
5839 return procs.valueAt(i);
5840 }
5841 }
5842
5843 return mProcessNames.get(processName, uid);
5844 }
5845
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005846 WindowProcessController getProcessController(IApplicationThread thread) {
5847 if (thread == null) {
5848 return null;
5849 }
5850
5851 final IBinder threadBinder = thread.asBinder();
5852 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5853 for (int i = pmap.size()-1; i >= 0; i--) {
5854 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5855 for (int j = procs.size() - 1; j >= 0; j--) {
5856 final WindowProcessController proc = procs.valueAt(j);
5857 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5858 return proc;
5859 }
5860 }
5861 }
5862
5863 return null;
5864 }
5865
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005866 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005867 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005868 if (proc == null) return null;
5869 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5870 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005871 }
5872 return null;
5873 }
5874
Riddle Hsua0536432019-02-16 00:38:59 +08005875 int getUidState(int uid) {
5876 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005877 }
5878
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005879 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005880 // A uid is considered to be foreground if it has a visible non-toast window.
5881 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005882 }
5883
Ricky Wai96f5c352019-04-10 18:40:17 +01005884 boolean isDeviceOwner(int uid) {
5885 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005886 }
5887
Ricky Wai96f5c352019-04-10 18:40:17 +01005888 void setDeviceOwnerUid(int uid) {
5889 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005890 }
5891
Wale Ogunwale9de19442018-10-18 19:05:03 -07005892 /**
5893 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5894 * the whitelist
5895 */
5896 String getPendingTempWhitelistTagForUidLocked(int uid) {
5897 return mPendingTempWhitelist.get(uid);
5898 }
5899
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005900 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5901 if (true || Build.IS_USER) {
5902 return;
5903 }
5904
5905 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5906 StrictMode.allowThreadDiskWrites();
5907 try {
5908 File tracesDir = new File("/data/anr");
5909 File tracesFile = null;
5910 try {
5911 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5912
5913 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005914 String timeString =
5915 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5916 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005917 sb.append(": ");
5918 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5919 sb.append(" since ");
5920 sb.append(msg);
5921 FileOutputStream fos = new FileOutputStream(tracesFile);
5922 fos.write(sb.toString().getBytes());
5923 if (app == null) {
5924 fos.write("\n*** No application process!".getBytes());
5925 }
5926 fos.close();
5927 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5928 } catch (IOException e) {
5929 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5930 return;
5931 }
5932
5933 if (app != null && app.getPid() > 0) {
5934 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5935 firstPids.add(app.getPid());
5936 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5937 }
5938
5939 File lastTracesFile = null;
5940 File curTracesFile = null;
5941 for (int i=9; i>=0; i--) {
5942 String name = String.format(Locale.US, "slow%02d.txt", i);
5943 curTracesFile = new File(tracesDir, name);
5944 if (curTracesFile.exists()) {
5945 if (lastTracesFile != null) {
5946 curTracesFile.renameTo(lastTracesFile);
5947 } else {
5948 curTracesFile.delete();
5949 }
5950 }
5951 lastTracesFile = curTracesFile;
5952 }
5953 tracesFile.renameTo(curTracesFile);
5954 } finally {
5955 StrictMode.setThreadPolicy(oldPolicy);
5956 }
5957 }
5958
Michal Karpinskida34cd42019-04-02 19:46:52 +01005959 boolean isAssociatedCompanionApp(int userId, int uid) {
5960 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5961 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005962 return false;
5963 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005964 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005965 }
5966
Issei Suzuki734bc942019-06-05 13:59:52 +02005967 void notifySingleTaskDisplayEmpty(int displayId) {
5968 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5969 }
5970
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005971 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005973
5974
Wale Ogunwale98875612018-10-12 07:53:02 -07005975 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5976 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005977
Riddle Hsud93a6c42018-11-29 21:50:06 +08005978 H(Looper looper) {
5979 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005980 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005981
5982 @Override
5983 public void handleMessage(Message msg) {
5984 switch (msg.what) {
5985 case REPORT_TIME_TRACKER_MSG: {
5986 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5987 tracker.deliverResult(mContext);
5988 } break;
5989 }
5990 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005991 }
5992
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005993 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005994 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005995
5996 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005997 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005998 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005999
6000 @Override
6001 public void handleMessage(Message msg) {
6002 switch (msg.what) {
6003 case DISMISS_DIALOG_UI_MSG: {
6004 final Dialog d = (Dialog) msg.obj;
6005 d.dismiss();
6006 break;
6007 }
6008 }
6009 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006010 }
6011
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006012 final class LocalService extends ActivityTaskManagerInternal {
6013 @Override
6014 public SleepToken acquireSleepToken(String tag, int displayId) {
6015 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006016 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006017 }
6018
6019 @Override
6020 public ComponentName getHomeActivityForUser(int userId) {
6021 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006022 final ActivityRecord homeActivity =
6023 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006024 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
6026 }
6027
6028 @Override
6029 public void onLocalVoiceInteractionStarted(IBinder activity,
6030 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6031 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006032 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006033 }
6034 }
6035
6036 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006037 public void notifyAppTransitionStarting(SparseIntArray reasons,
6038 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 synchronized (mGlobalLock) {
6040 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6041 reasons, timestamp);
6042 }
6043 }
6044
6045 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006046 public void notifySingleTaskDisplayDrawn(int displayId) {
6047 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6048 }
6049
6050 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006051 public void notifyAppTransitionFinished() {
6052 synchronized (mGlobalLock) {
6053 mStackSupervisor.notifyAppTransitionDone();
6054 }
6055 }
6056
6057 @Override
6058 public void notifyAppTransitionCancelled() {
6059 synchronized (mGlobalLock) {
6060 mStackSupervisor.notifyAppTransitionDone();
6061 }
6062 }
6063
6064 @Override
6065 public List<IBinder> getTopVisibleActivities() {
6066 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006067 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006068 }
6069 }
6070
6071 @Override
6072 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6073 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006074 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 }
6076 }
6077
6078 @Override
6079 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6080 Bundle bOptions) {
6081 Preconditions.checkNotNull(intents, "intents");
6082 final String[] resolvedTypes = new String[intents.length];
6083
6084 // UID of the package on user userId.
6085 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6086 // packageUid may not be initialized.
6087 int packageUid = 0;
6088 final long ident = Binder.clearCallingIdentity();
6089
6090 try {
6091 for (int i = 0; i < intents.length; i++) {
6092 resolvedTypes[i] =
6093 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6094 }
6095
6096 packageUid = AppGlobals.getPackageManager().getPackageUid(
6097 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6098 } catch (RemoteException e) {
6099 // Shouldn't happen.
6100 } finally {
6101 Binder.restoreCallingIdentity(ident);
6102 }
6103
Riddle Hsu591bf612019-02-14 17:55:31 +08006104 return getActivityStartController().startActivitiesInPackage(
6105 packageUid, packageName,
6106 intents, resolvedTypes, null /* resultTo */,
6107 SafeActivityOptions.fromBundle(bOptions), userId,
6108 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6109 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 }
6111
6112 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006113 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6114 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6115 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6116 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006117 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006118 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006119 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6120 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6121 userId, validateIncomingUser, originatingPendingIntent,
6122 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006123 }
6124 }
6125
6126 @Override
6127 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6128 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6129 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6130 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006131 PendingIntentRecord originatingPendingIntent,
6132 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006133 synchronized (mGlobalLock) {
6134 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6135 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6136 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006137 validateIncomingUser, originatingPendingIntent,
6138 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006139 }
6140 }
6141
6142 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6144 Intent intent, Bundle options, int userId) {
6145 return ActivityTaskManagerService.this.startActivityAsUser(
6146 caller, callerPacakge, intent,
6147 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6148 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6149 false /*validateIncomingUser*/);
6150 }
6151
6152 @Override
lumark588a3e82018-07-20 18:53:54 +08006153 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 synchronized (mGlobalLock) {
6155
6156 // We might change the visibilities here, so prepare an empty app transition which
6157 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006158 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006159 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006160 if (activityDisplay == null) {
6161 return;
6162 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006163 final DisplayContent dc = activityDisplay.mDisplayContent;
6164 final boolean wasTransitionSet =
6165 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006167 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006169 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170
6171 // If there was a transition set already we don't want to interfere with it as we
6172 // might be starting it too early.
6173 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006174 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176 }
6177 if (callback != null) {
6178 callback.run();
6179 }
6180 }
6181
6182 @Override
6183 public void notifyKeyguardTrustedChanged() {
6184 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006185 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006186 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006187 }
6188 }
6189 }
6190
6191 /**
6192 * Called after virtual display Id is updated by
6193 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6194 * {@param vrVr2dDisplayId}.
6195 */
6196 @Override
6197 public void setVr2dDisplayId(int vr2dDisplayId) {
6198 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6199 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006200 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
6202 }
6203
6204 @Override
6205 public void setFocusedActivity(IBinder token) {
6206 synchronized (mGlobalLock) {
6207 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6208 if (r == null) {
6209 throw new IllegalArgumentException(
6210 "setFocusedActivity: No activity record matching token=" + token);
6211 }
Louis Chang19443452018-10-09 12:10:21 +08006212 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006213 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215 }
6216 }
6217
6218 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006220 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
6222
6223 @Override
6224 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006225 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
6227
6228 @Override
6229 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006230 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231 }
6232
6233 @Override
6234 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6235 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6236 }
6237
6238 @Override
6239 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006240 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006242
6243 @Override
6244 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6245 synchronized (mGlobalLock) {
6246 mActiveVoiceInteractionServiceComponent = component;
6247 }
6248 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006249
6250 @Override
6251 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6252 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6253 return;
6254 }
6255 synchronized (mGlobalLock) {
6256 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6257 if (types == null) {
6258 if (uid < 0) {
6259 return;
6260 }
6261 types = new ArrayMap<>();
6262 mAllowAppSwitchUids.put(userId, types);
6263 }
6264 if (uid < 0) {
6265 types.remove(type);
6266 } else {
6267 types.put(type, uid);
6268 }
6269 }
6270 }
6271
6272 @Override
6273 public void onUserStopped(int userId) {
6274 synchronized (mGlobalLock) {
6275 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6276 mAllowAppSwitchUids.remove(userId);
6277 }
6278 }
6279
6280 @Override
6281 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6282 synchronized (mGlobalLock) {
6283 return ActivityTaskManagerService.this.isGetTasksAllowed(
6284 caller, callingPid, callingUid);
6285 }
6286 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006287
Riddle Hsua0536432019-02-16 00:38:59 +08006288 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006289 @Override
6290 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006291 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006292 mProcessNames.put(proc.mName, proc.mUid, proc);
6293 }
6294 }
6295
Riddle Hsua0536432019-02-16 00:38:59 +08006296 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006297 @Override
6298 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006299 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006300 mProcessNames.remove(name, uid);
6301 }
6302 }
6303
Riddle Hsua0536432019-02-16 00:38:59 +08006304 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006305 @Override
6306 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006308 if (proc == mHomeProcess) {
6309 mHomeProcess = null;
6310 }
6311 if (proc == mPreviousProcess) {
6312 mPreviousProcess = null;
6313 }
6314 }
6315 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006316
Riddle Hsua0536432019-02-16 00:38:59 +08006317 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006318 @Override
6319 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006320 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006321 return mTopProcessState;
6322 }
6323 }
6324
Riddle Hsua0536432019-02-16 00:38:59 +08006325 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006326 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006327 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006328 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006329 return proc == mHeavyWeightProcess;
6330 }
6331 }
6332
Riddle Hsua0536432019-02-16 00:38:59 +08006333 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006334 @Override
6335 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006336 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006337 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6338 }
6339 }
6340
6341 @Override
6342 public void finishHeavyWeightApp() {
6343 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006344 if (mHeavyWeightProcess != null) {
6345 mHeavyWeightProcess.finishActivities();
6346 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006347 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6348 mHeavyWeightProcess);
6349 }
6350 }
6351
Riddle Hsua0536432019-02-16 00:38:59 +08006352 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006353 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006356 return isSleepingLocked();
6357 }
6358 }
6359
6360 @Override
6361 public boolean isShuttingDown() {
6362 synchronized (mGlobalLock) {
6363 return mShuttingDown;
6364 }
6365 }
6366
6367 @Override
6368 public boolean shuttingDown(boolean booted, int timeout) {
6369 synchronized (mGlobalLock) {
6370 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006371 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006372 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006373 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006374 return mStackSupervisor.shutdownLocked(timeout);
6375 }
6376 }
6377
6378 @Override
6379 public void enableScreenAfterBoot(boolean booted) {
6380 synchronized (mGlobalLock) {
6381 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6382 SystemClock.uptimeMillis());
6383 mWindowManager.enableScreenAfterBoot();
6384 updateEventDispatchingLocked(booted);
6385 }
6386 }
6387
6388 @Override
6389 public boolean showStrictModeViolationDialog() {
6390 synchronized (mGlobalLock) {
6391 return mShowDialogs && !mSleeping && !mShuttingDown;
6392 }
6393 }
6394
6395 @Override
6396 public void showSystemReadyErrorDialogsIfNeeded() {
6397 synchronized (mGlobalLock) {
6398 try {
6399 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6400 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6401 + " data partition or your device will be unstable.");
6402 mUiHandler.post(() -> {
6403 if (mShowDialogs) {
6404 AlertDialog d = new BaseErrorDialog(mUiContext);
6405 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6406 d.setCancelable(false);
6407 d.setTitle(mUiContext.getText(R.string.android_system_label));
6408 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6409 d.setButton(DialogInterface.BUTTON_POSITIVE,
6410 mUiContext.getText(R.string.ok),
6411 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6412 d.show();
6413 }
6414 });
6415 }
6416 } catch (RemoteException e) {
6417 }
6418
6419 if (!Build.isBuildConsistent()) {
6420 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6421 mUiHandler.post(() -> {
6422 if (mShowDialogs) {
6423 AlertDialog d = new BaseErrorDialog(mUiContext);
6424 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6425 d.setCancelable(false);
6426 d.setTitle(mUiContext.getText(R.string.android_system_label));
6427 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6428 d.setButton(DialogInterface.BUTTON_POSITIVE,
6429 mUiContext.getText(R.string.ok),
6430 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6431 d.show();
6432 }
6433 });
6434 }
6435 }
6436 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006437
6438 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006439 public void onProcessMapped(int pid, WindowProcessController proc) {
6440 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006441 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006442 }
6443 }
6444
6445 @Override
6446 public void onProcessUnMapped(int pid) {
6447 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006448 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006449 }
6450 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006451
6452 @Override
6453 public void onPackageDataCleared(String name) {
6454 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006456 mAppWarnings.onPackageDataCleared(name);
6457 }
6458 }
6459
6460 @Override
6461 public void onPackageUninstalled(String name) {
6462 synchronized (mGlobalLock) {
6463 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006464 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006465 }
6466 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006467
6468 @Override
6469 public void onPackageAdded(String name, boolean replacing) {
6470 synchronized (mGlobalLock) {
6471 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6472 }
6473 }
6474
6475 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006476 public void onPackageReplaced(ApplicationInfo aInfo) {
6477 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006478 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006479 }
6480 }
6481
6482 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006483 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6484 synchronized (mGlobalLock) {
6485 return compatibilityInfoForPackageLocked(ai);
6486 }
6487 }
6488
Yunfan Chen75157d72018-07-27 14:47:21 +09006489 /**
6490 * Set the corresponding display information for the process global configuration. To be
6491 * called when we need to show IME on a different display.
6492 *
6493 * @param pid The process id associated with the IME window.
6494 * @param displayId The ID of the display showing the IME.
6495 */
6496 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006497 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006498 // Don't update process-level configuration for Multi-Client IME process since other
6499 // IMEs on other displays will also receive this configuration change due to IME
6500 // services use the same application config/context.
6501 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006502
Yunfan Chen75157d72018-07-27 14:47:21 +09006503 if (pid == MY_PID || pid < 0) {
6504 if (DEBUG_CONFIGURATION) {
6505 Slog.w(TAG,
6506 "Trying to update display configuration for system/invalid process.");
6507 }
6508 return;
6509 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006510 synchronized (mGlobalLock) {
6511 final ActivityDisplay activityDisplay =
6512 mRootActivityContainer.getActivityDisplay(displayId);
6513 if (activityDisplay == null) {
6514 // Call might come when display is not yet added or has been removed.
6515 if (DEBUG_CONFIGURATION) {
6516 Slog.w(TAG, "Trying to update display configuration for non-existing "
6517 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006518 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006519 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006520 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006522 if (process == null) {
6523 if (DEBUG_CONFIGURATION) {
6524 Slog.w(TAG, "Trying to update display configuration for invalid "
6525 + "process, pid=" + pid);
6526 }
6527 return;
6528 }
lumarkddc77fb2019-06-27 22:22:23 +08006529 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006530 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6531 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006532 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006533
6534 @Override
6535 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006536 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006537 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006538 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6539 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006540 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006541 }
6542 }
6543 }
6544
6545 @Override
6546 public void clearPendingResultForActivity(IBinder activityToken,
6547 WeakReference<PendingIntentRecord> pir) {
6548 synchronized (mGlobalLock) {
6549 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6550 if (r != null && r.pendingResults != null) {
6551 r.pendingResults.remove(pir);
6552 }
6553 }
6554 }
6555
6556 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006557 public ActivityTokens getTopActivityForTask(int taskId) {
6558 synchronized (mGlobalLock) {
6559 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6560 if (taskRecord == null) {
6561 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6562 + " Requested task not found");
6563 return null;
6564 }
6565 final ActivityRecord activity = taskRecord.getTopActivity();
6566 if (activity == null) {
6567 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6568 + " Requested activity not found");
6569 return null;
6570 }
6571 if (!activity.attachedToProcess()) {
6572 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6573 + activity);
6574 return null;
6575 }
6576 return new ActivityTokens(activity.appToken, activity.assistToken,
6577 activity.app.getThread());
6578 }
6579 }
6580
6581 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006582 public IIntentSender getIntentSender(int type, String packageName,
6583 int callingUid, int userId, IBinder token, String resultWho,
6584 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6585 Bundle bOptions) {
6586 synchronized (mGlobalLock) {
6587 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6588 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6589 }
6590 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006591
6592 @Override
6593 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6594 synchronized (mGlobalLock) {
6595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6596 if (r == null) {
6597 return null;
6598 }
6599 if (r.mServiceConnectionsHolder == null) {
6600 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6601 ActivityTaskManagerService.this, r);
6602 }
6603
6604 return r.mServiceConnectionsHolder;
6605 }
6606 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006607
6608 @Override
6609 public Intent getHomeIntent() {
6610 synchronized (mGlobalLock) {
6611 return ActivityTaskManagerService.this.getHomeIntent();
6612 }
6613 }
6614
6615 @Override
6616 public boolean startHomeActivity(int userId, String reason) {
6617 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006618 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006619 }
6620 }
6621
6622 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006623 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006624 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006625 synchronized (mGlobalLock) {
6626 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006627 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006628 }
Chilun8b1f1be2019-03-13 17:14:36 +08006629 }
6630
6631 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006632 public boolean startHomeOnAllDisplays(int userId, String reason) {
6633 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006634 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006635 }
6636 }
6637
Riddle Hsua0536432019-02-16 00:38:59 +08006638 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006639 @Override
6640 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006641 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006642 if (mFactoryTest == FACTORY_TEST_OFF) {
6643 return false;
6644 }
6645 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6646 && wpc.mName.equals(mTopComponent.getPackageName())) {
6647 return true;
6648 }
6649 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6650 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6651 }
6652 }
6653
6654 @Override
6655 public void updateTopComponentForFactoryTest() {
6656 synchronized (mGlobalLock) {
6657 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6658 return;
6659 }
6660 final ResolveInfo ri = mContext.getPackageManager()
6661 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6662 final CharSequence errorMsg;
6663 if (ri != null) {
6664 final ActivityInfo ai = ri.activityInfo;
6665 final ApplicationInfo app = ai.applicationInfo;
6666 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6667 mTopAction = Intent.ACTION_FACTORY_TEST;
6668 mTopData = null;
6669 mTopComponent = new ComponentName(app.packageName, ai.name);
6670 errorMsg = null;
6671 } else {
6672 errorMsg = mContext.getResources().getText(
6673 com.android.internal.R.string.factorytest_not_system);
6674 }
6675 } else {
6676 errorMsg = mContext.getResources().getText(
6677 com.android.internal.R.string.factorytest_no_action);
6678 }
6679 if (errorMsg == null) {
6680 return;
6681 }
6682
6683 mTopAction = null;
6684 mTopData = null;
6685 mTopComponent = null;
6686 mUiHandler.post(() -> {
6687 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6688 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006689 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006690 });
6691 }
6692 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006693
Riddle Hsua0536432019-02-16 00:38:59 +08006694 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 @Override
6696 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6697 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006698 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006700 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701
6702 wpc.clearRecentTasks();
6703 wpc.clearActivities();
6704
6705 if (wpc.isInstrumenting()) {
6706 finishInstrumentationCallback.run();
6707 }
6708
Jorim Jaggid0752812018-10-16 16:07:20 +02006709 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006710 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006711 try {
6712 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6713 // If there was nothing to resume, and we are not already restarting
6714 // this process, but there is a visible activity that is hosted by the
6715 // process...then make sure all visible activities are running, taking
6716 // care of restarting this process.
6717 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6718 !PRESERVE_WINDOWS);
6719 }
6720 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006721 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 }
6724 }
6725 }
6726
6727 @Override
6728 public void closeSystemDialogs(String reason) {
6729 enforceNotIsolatedCaller("closeSystemDialogs");
6730
6731 final int pid = Binder.getCallingPid();
6732 final int uid = Binder.getCallingUid();
6733 final long origId = Binder.clearCallingIdentity();
6734 try {
6735 synchronized (mGlobalLock) {
6736 // Only allow this from foreground processes, so that background
6737 // applications can't abuse it to prevent system UI from being shown.
6738 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006739 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 if (!proc.isPerceptible()) {
6741 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6742 + " from background process " + proc);
6743 return;
6744 }
6745 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 mWindowManager.closeSystemDialogs(reason);
6747
Wale Ogunwaled32da472018-11-16 07:19:28 -08006748 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006750 // Call into AM outside the synchronized block.
6751 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 } finally {
6753 Binder.restoreCallingIdentity(origId);
6754 }
6755 }
6756
6757 @Override
6758 public void cleanupDisabledPackageComponents(
6759 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6760 synchronized (mGlobalLock) {
6761 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006762 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 mStackSupervisor.scheduleIdleLocked();
6766 }
6767
6768 // Clean-up disabled tasks
6769 getRecentTasks().cleanupDisabledPackageTasksLocked(
6770 packageName, disabledClasses, userId);
6771 }
6772 }
6773
6774 @Override
6775 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6776 int userId) {
6777 synchronized (mGlobalLock) {
6778
6779 boolean didSomething =
6780 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 null, doit, evenPersistent, userId);
6783 return didSomething;
6784 }
6785 }
6786
6787 @Override
6788 public void resumeTopActivities(boolean scheduleIdle) {
6789 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006790 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 if (scheduleIdle) {
6792 mStackSupervisor.scheduleIdleLocked();
6793 }
6794 }
6795 }
6796
Riddle Hsua0536432019-02-16 00:38:59 +08006797 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 @Override
6799 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006800 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6802 }
6803 }
6804
Riddle Hsua0536432019-02-16 00:38:59 +08006805 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 @Override
6807 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006808 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
6811 }
6812
6813 @Override
6814 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6815 try {
6816 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6817 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6818 }
6819 } catch (RemoteException ex) {
6820 throw new SecurityException("Fail to check is caller a privileged app", ex);
6821 }
6822
6823 synchronized (mGlobalLock) {
6824 final long ident = Binder.clearCallingIdentity();
6825 try {
6826 if (mAmInternal.shouldConfirmCredentials(userId)) {
6827 if (mKeyguardController.isKeyguardLocked()) {
6828 // Showing launcher to avoid user entering credential twice.
6829 startHomeActivity(currentUserId, "notifyLockedProfile");
6830 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006831 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 }
6833 } finally {
6834 Binder.restoreCallingIdentity(ident);
6835 }
6836 }
6837 }
6838
6839 @Override
6840 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6841 mAmInternal.enforceCallingPermission(
6842 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6843
6844 synchronized (mGlobalLock) {
6845 final long ident = Binder.clearCallingIdentity();
6846 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006847 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6848 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6851 UserHandle.CURRENT);
6852 } finally {
6853 Binder.restoreCallingIdentity(ident);
6854 }
6855 }
6856 }
6857
6858 @Override
6859 public void writeActivitiesToProto(ProtoOutputStream proto) {
6860 synchronized (mGlobalLock) {
6861 // The output proto of "activity --proto activities"
6862 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006863 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006864 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6865 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
6867 }
6868
6869 @Override
6870 public void saveANRState(String reason) {
6871 synchronized (mGlobalLock) {
6872 final StringWriter sw = new StringWriter();
6873 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6874 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6875 if (reason != null) {
6876 pw.println(" Reason: " + reason);
6877 }
6878 pw.println();
6879 getActivityStartController().dump(pw, " ", null);
6880 pw.println();
6881 pw.println("-------------------------------------------------------------------------------");
6882 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6883 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6884 "" /* header */);
6885 pw.println();
6886 pw.close();
6887
6888 mLastANRState = sw.toString();
6889 }
6890 }
6891
6892 @Override
6893 public void clearSavedANRState() {
6894 synchronized (mGlobalLock) {
6895 mLastANRState = null;
6896 }
6897 }
6898
6899 @Override
6900 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6901 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6902 synchronized (mGlobalLock) {
6903 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6904 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6905 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6906 dumpLastANRLocked(pw);
6907 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6908 dumpLastANRTracesLocked(pw);
6909 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6910 dumpActivityStarterLocked(pw, dumpPackage);
6911 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6912 dumpActivityContainersLocked(pw);
6913 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6914 if (getRecentTasks() != null) {
6915 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6916 }
6917 }
6918 }
6919 }
6920
6921 @Override
6922 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6923 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6924 int wakefulness) {
6925 synchronized (mGlobalLock) {
6926 if (mHomeProcess != null && (dumpPackage == null
6927 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6928 if (needSep) {
6929 pw.println();
6930 needSep = false;
6931 }
6932 pw.println(" mHomeProcess: " + mHomeProcess);
6933 }
6934 if (mPreviousProcess != null && (dumpPackage == null
6935 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6936 if (needSep) {
6937 pw.println();
6938 needSep = false;
6939 }
6940 pw.println(" mPreviousProcess: " + mPreviousProcess);
6941 }
6942 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6943 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6944 StringBuilder sb = new StringBuilder(128);
6945 sb.append(" mPreviousProcessVisibleTime: ");
6946 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6947 pw.println(sb);
6948 }
6949 if (mHeavyWeightProcess != null && (dumpPackage == null
6950 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6951 if (needSep) {
6952 pw.println();
6953 needSep = false;
6954 }
6955 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6956 }
6957 if (dumpPackage == null) {
6958 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006959 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 }
6961 if (dumpAll) {
6962 if (dumpPackage == null) {
6963 pw.println(" mConfigWillChange: "
6964 + getTopDisplayFocusedStack().mConfigWillChange);
6965 }
6966 if (mCompatModePackages.getPackages().size() > 0) {
6967 boolean printed = false;
6968 for (Map.Entry<String, Integer> entry
6969 : mCompatModePackages.getPackages().entrySet()) {
6970 String pkg = entry.getKey();
6971 int mode = entry.getValue();
6972 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6973 continue;
6974 }
6975 if (!printed) {
6976 pw.println(" mScreenCompatPackages:");
6977 printed = true;
6978 }
6979 pw.println(" " + pkg + ": " + mode);
6980 }
6981 }
6982 }
6983
6984 if (dumpPackage == null) {
6985 pw.println(" mWakefulness="
6986 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006987 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006988 if (mRunningVoice != null) {
6989 pw.println(" mRunningVoice=" + mRunningVoice);
6990 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6991 }
6992 pw.println(" mSleeping=" + mSleeping);
6993 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6994 pw.println(" mVrController=" + mVrController);
6995 }
6996 if (mCurAppTimeTracker != null) {
6997 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6998 }
6999 if (mAllowAppSwitchUids.size() > 0) {
7000 boolean printed = false;
7001 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7002 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7003 for (int j = 0; j < types.size(); j++) {
7004 if (dumpPackage == null ||
7005 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7006 if (needSep) {
7007 pw.println();
7008 needSep = false;
7009 }
7010 if (!printed) {
7011 pw.println(" mAllowAppSwitchUids:");
7012 printed = true;
7013 }
7014 pw.print(" User ");
7015 pw.print(mAllowAppSwitchUids.keyAt(i));
7016 pw.print(": Type ");
7017 pw.print(types.keyAt(j));
7018 pw.print(" = ");
7019 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7020 pw.println();
7021 }
7022 }
7023 }
7024 }
7025 if (dumpPackage == null) {
7026 if (mController != null) {
7027 pw.println(" mController=" + mController
7028 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7029 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007030 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7031 pw.println(" mLaunchingActivityWakeLock="
7032 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034
7035 return needSep;
7036 }
7037 }
7038
7039 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007040 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7041 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007042 synchronized (mGlobalLock) {
7043 if (dumpPackage == null) {
7044 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7045 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007046 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7047 if (mRunningVoice != null) {
7048 final long vrToken = proto.start(
7049 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7050 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7051 mRunningVoice.toString());
7052 mVoiceWakeLock.writeToProto(
7053 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7054 proto.end(vrToken);
7055 }
7056 mVrController.writeToProto(proto,
7057 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007058 if (mController != null) {
7059 final long token = proto.start(CONTROLLER);
7060 proto.write(CONTROLLER, mController.toString());
7061 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7062 proto.end(token);
7063 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007064 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7065 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7066 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007067 }
7068
7069 if (mHomeProcess != null && (dumpPackage == null
7070 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007071 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 }
7073
7074 if (mPreviousProcess != null && (dumpPackage == null
7075 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007076 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7078 }
7079
7080 if (mHeavyWeightProcess != null && (dumpPackage == null
7081 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007082 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 }
7084
7085 for (Map.Entry<String, Integer> entry
7086 : mCompatModePackages.getPackages().entrySet()) {
7087 String pkg = entry.getKey();
7088 int mode = entry.getValue();
7089 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7090 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7091 proto.write(PACKAGE, pkg);
7092 proto.write(MODE, mode);
7093 proto.end(compatToken);
7094 }
7095 }
7096
7097 if (mCurAppTimeTracker != null) {
7098 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7099 }
7100
7101 }
7102 }
7103
7104 @Override
7105 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7106 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7107 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007108 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7109 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 }
7111
7112 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007113 public void dumpForOom(PrintWriter pw) {
7114 synchronized (mGlobalLock) {
7115 pw.println(" mHomeProcess: " + mHomeProcess);
7116 pw.println(" mPreviousProcess: " + mPreviousProcess);
7117 if (mHeavyWeightProcess != null) {
7118 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7119 }
7120 }
7121 }
7122
7123 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 public boolean canGcNow() {
7125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128 }
7129
Riddle Hsua0536432019-02-16 00:38:59 +08007130 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 @Override
7132 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007133 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007134 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 return top != null ? top.app : null;
7136 }
7137 }
7138
Riddle Hsua0536432019-02-16 00:38:59 +08007139 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 @Override
7141 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007142 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007143 if (mRootActivityContainer != null) {
7144 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146 }
7147 }
7148
7149 @Override
7150 public void scheduleDestroyAllActivities(String reason) {
7151 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007152 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007153 }
7154 }
7155
7156 @Override
7157 public void removeUser(int userId) {
7158 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007159 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 }
7161 }
7162
7163 @Override
7164 public boolean switchUser(int userId, UserState userState) {
7165 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007166 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 }
7168 }
7169
7170 @Override
7171 public void onHandleAppCrash(WindowProcessController wpc) {
7172 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007173 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 }
7175 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007176
7177 @Override
7178 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007180 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007181 }
7182 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007183
Riddle Hsua0536432019-02-16 00:38:59 +08007184 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007185 @Override
7186 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007187 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007188 }
7189
Riddle Hsua0536432019-02-16 00:38:59 +08007190 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007191 @Override
7192 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007193 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007194 }
7195
Riddle Hsua0536432019-02-16 00:38:59 +08007196 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007197 @Override
7198 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007199 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007200 }
7201
Riddle Hsua0536432019-02-16 00:38:59 +08007202 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007203 @Override
7204 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007205 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007206 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007207
7208 @Override
7209 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007210 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007211 mPendingTempWhitelist.put(uid, tag);
7212 }
7213 }
7214
7215 @Override
7216 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007217 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007218 mPendingTempWhitelist.remove(uid);
7219 }
7220 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007221
7222 @Override
7223 public boolean handleAppCrashInActivityController(String processName, int pid,
7224 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7225 Runnable killCrashingAppCallback) {
7226 synchronized (mGlobalLock) {
7227 if (mController == null) {
7228 return false;
7229 }
7230
7231 try {
7232 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7233 stackTrace)) {
7234 killCrashingAppCallback.run();
7235 return true;
7236 }
7237 } catch (RemoteException e) {
7238 mController = null;
7239 Watchdog.getInstance().setActivityController(null);
7240 }
7241 return false;
7242 }
7243 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007244
7245 @Override
7246 public void removeRecentTasksByPackageName(String packageName, int userId) {
7247 synchronized (mGlobalLock) {
7248 mRecentTasks.removeTasksByPackageName(packageName, userId);
7249 }
7250 }
7251
7252 @Override
7253 public void cleanupRecentTasksForUser(int userId) {
7254 synchronized (mGlobalLock) {
7255 mRecentTasks.cleanupLocked(userId);
7256 }
7257 }
7258
7259 @Override
7260 public void loadRecentTasksForUser(int userId) {
7261 synchronized (mGlobalLock) {
7262 mRecentTasks.loadUserRecentsLocked(userId);
7263 }
7264 }
7265
7266 @Override
7267 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7268 synchronized (mGlobalLock) {
7269 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7270 }
7271 }
7272
7273 @Override
7274 public void flushRecentTasks() {
7275 mRecentTasks.flush();
7276 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007277
7278 @Override
7279 public WindowProcessController getHomeProcess() {
7280 synchronized (mGlobalLock) {
7281 return mHomeProcess;
7282 }
7283 }
7284
7285 @Override
7286 public WindowProcessController getPreviousProcess() {
7287 synchronized (mGlobalLock) {
7288 return mPreviousProcess;
7289 }
7290 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007291
7292 @Override
7293 public void clearLockedTasks(String reason) {
7294 synchronized (mGlobalLock) {
7295 getLockTaskController().clearLockedTasks(reason);
7296 }
7297 }
7298
7299 @Override
7300 public void updateUserConfiguration() {
7301 synchronized (mGlobalLock) {
7302 final Configuration configuration = new Configuration(getGlobalConfiguration());
7303 final int currentUserId = mAmInternal.getCurrentUserId();
7304 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7305 configuration, currentUserId, Settings.System.canWrite(mContext));
7306 updateConfigurationLocked(configuration, null /* starting */,
7307 false /* initLocale */, false /* persistent */, currentUserId,
7308 false /* deferResume */);
7309 }
7310 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007311
7312 @Override
7313 public boolean canShowErrorDialogs() {
7314 synchronized (mGlobalLock) {
7315 return mShowDialogs && !mSleeping && !mShuttingDown
7316 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7317 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7318 mAmInternal.getCurrentUserId())
7319 && !(UserManager.isDeviceInDemoMode(mContext)
7320 && mAmInternal.getCurrentUser().isDemo());
7321 }
7322 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007323
7324 @Override
7325 public void setProfileApp(String profileApp) {
7326 synchronized (mGlobalLock) {
7327 mProfileApp = profileApp;
7328 }
7329 }
7330
7331 @Override
7332 public void setProfileProc(WindowProcessController wpc) {
7333 synchronized (mGlobalLock) {
7334 mProfileProc = wpc;
7335 }
7336 }
7337
7338 @Override
7339 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7340 synchronized (mGlobalLock) {
7341 mProfilerInfo = profilerInfo;
7342 }
7343 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007344
7345 @Override
7346 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7347 synchronized (mGlobalLock) {
7348 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7349 }
7350 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007351
7352 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007353 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7354 boolean reducedResolution) {
7355 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7356 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007357 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007358
7359 @Override
7360 public boolean isUidForeground(int uid) {
7361 synchronized (mGlobalLock) {
7362 return ActivityTaskManagerService.this.isUidForeground(uid);
7363 }
7364 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007365
7366 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007367 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007368 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007369 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007370 }
7371 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007372
7373 @Override
7374 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007375 // Translate package names into UIDs
7376 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007377 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007378 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7379 if (uid >= 0) {
7380 result.add(uid);
7381 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007382 }
7383 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007384 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007385 }
7386 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007387 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007388}