blob: a192599af2eb0e19a11b8f6c7d0c1f77578f300e [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 Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import 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;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800126import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700218import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.EventLog;
220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700230import android.view.WindowContainerTransaction;
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;
Evan Roskyddedfd42019-10-04 13:38:38 -0700293import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800357 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800358 @VisibleForTesting
359 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 PowerManagerInternal mPowerManagerInternal;
361 private UsageStatsManagerInternal mUsageStatsInternal;
362
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700363 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 IntentFirewall mIntentFirewall;
365
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700366 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800367 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700369 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
371 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
372 *
373 * @see WindowManagerThreadPriorityBooster
374 */
375 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800377 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700378 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700379 private UserManagerService mUserManager;
380 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700381 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800382 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700383 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** All processes currently running that might have a window organized by name. */
385 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100386 /** All processes we currently have running mapped by pid and uid */
387 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** This is the process holding what we currently consider to be the "home" activity. */
389 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700390 /** The currently running heavy-weight process, if any. */
391 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700392 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /**
394 * This is the process holding the activity the user last visited that is in a different process
395 * from the one they are currently in.
396 */
397 WindowProcessController mPreviousProcess;
398 /** The time at which the previous process was last visible. */
399 long mPreviousProcessVisibleTime;
400
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700401 /** List of intents that were used to start the most recent tasks. */
402 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700403 /** State of external calls telling us if the device is awake or asleep. */
404 private boolean mKeyguardShown = false;
405
406 // Wrapper around VoiceInteractionServiceManager
407 private AssistUtils mAssistUtils;
408
409 // VoiceInteraction session ID that changes for each new request except when
410 // being called for multi-window assist in a single session.
411 private int mViSessionId = 1000;
412
413 // How long to wait in getAssistContextExtras for the activity and foreground services
414 // to respond with the result.
415 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
416
417 // How long top wait when going through the modern assist (which doesn't need to block
418 // on getting this result before starting to launch its UI).
419 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
420
421 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
422 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
423
Alison Cichowlas3e340502018-08-07 17:15:01 -0400424 // Permission tokens are used to temporarily granted a trusted app the ability to call
425 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
426 // showing any appropriate error messages to the user.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
428 10 * MINUTE_IN_MILLIS;
429
430 // How long before the service actually expires a token. This is slightly longer than
431 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
432 // expiration exception.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
434 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
435
436 // How long the service will remember expired tokens, for the purpose of providing error
437 // messaging when a client uses an expired token.
438 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
439 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
440
441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700467 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
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;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700575 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
Riddle Hsua0022cd2019-09-09 21:12:41 +0800603 @Retention(RetentionPolicy.SOURCE)
604 @IntDef({
605 LAYOUT_REASON_CONFIG_CHANGED,
606 LAYOUT_REASON_VISIBILITY_CHANGED,
607 })
608 @interface LayoutReason {}
609 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
610 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
611
612 /** The reasons to perform surface placement. */
613 @LayoutReason
614 private int mLayoutReasons;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
617 // automatically. Important for devices without direct input devices.
618 private boolean mShowDialogs = true;
619
620 /** Set if we are shutting down the system, similar to sleeping. */
621 boolean mShuttingDown = false;
622
623 /**
624 * We want to hold a wake lock while running a voice interaction session, since
625 * this may happen with the screen off and we need to keep the CPU running to
626 * be able to continue to interact with the user.
627 */
628 PowerManager.WakeLock mVoiceWakeLock;
629
630 /**
631 * Set while we are running a voice interaction. This overrides sleeping while it is active.
632 */
633 IVoiceInteractionSession mRunningVoice;
634
635 /**
636 * The last resumed activity. This is identical to the current resumed activity most
637 * of the time but could be different when we're pausing one activity before we resume
638 * another activity.
639 */
640 ActivityRecord mLastResumedActivity;
641
642 /**
643 * The activity that is currently being traced as the active resumed activity.
644 *
645 * @see #updateResumedAppTrace
646 */
647 private @Nullable ActivityRecord mTracedResumedActivity;
648
649 /** If non-null, we are tracking the time the user spends in the currently focused app. */
650 AppTimeTracker mCurAppTimeTracker;
651
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700652 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700653
Wale Ogunwale53783742018-09-16 10:21:51 -0700654 /**
655 * Packages that the user has asked to have run in screen size
656 * compatibility mode instead of filling the screen.
657 */
658 CompatModePackages mCompatModePackages;
659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private FontScaleSettingObserver mFontScaleSettingObserver;
661
Ricky Wai96f5c352019-04-10 18:40:17 +0100662 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private final class FontScaleSettingObserver extends ContentObserver {
665 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
666 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
667
668 public FontScaleSettingObserver() {
669 super(mH);
670 final ContentResolver resolver = mContext.getContentResolver();
671 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
672 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
673 UserHandle.USER_ALL);
674 }
675
676 @Override
677 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
678 if (mFontScaleUri.equals(uri)) {
679 updateFontScaleIfNeeded(userId);
680 } else if (mHideErrorDialogsUri.equals(uri)) {
681 synchronized (mGlobalLock) {
682 updateShouldShowDialogsLocked(getGlobalConfiguration());
683 }
684 }
685 }
686 }
687
Riddle Hsua0536432019-02-16 00:38:59 +0800688 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
689 @Target(ElementType.METHOD)
690 @Retention(RetentionPolicy.SOURCE)
691 @interface HotPath {
692 int NONE = 0;
693 int OOM_ADJUSTMENT = 1;
694 int LRU_UPDATE = 2;
695 int PROCESS_CHANGE = 3;
696 int caller() default NONE;
697 }
698
Charles Chen8d98dd22018-12-26 17:36:54 +0800699 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
700 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700701 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700702 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700703 mSystemThread = ActivityThread.currentActivityThread();
704 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700705 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800706 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700707 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700708 }
709
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700710 public void onSystemReady() {
711 synchronized (mGlobalLock) {
712 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
713 PackageManager.FEATURE_CANT_SAVE_STATE);
714 mAssistUtils = new AssistUtils(mContext);
715 mVrController.onSystemReady();
716 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700717 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700719 }
720
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700721 public void onInitPowerManagement() {
722 synchronized (mGlobalLock) {
723 mStackSupervisor.initPowerManagement();
724 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
725 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
726 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
727 mVoiceWakeLock.setReferenceCounted(false);
728 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700729 }
730
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700732 mFontScaleSettingObserver = new FontScaleSettingObserver();
733 }
734
Wale Ogunwale59507092018-10-29 09:00:30 -0700735 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700736 final boolean freeformWindowManagement =
737 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
738 || Settings.Global.getInt(
739 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
740
741 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
742 final boolean supportsPictureInPicture = supportsMultiWindow &&
743 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
744 final boolean supportsSplitScreenMultiWindow =
745 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
746 final boolean supportsMultiDisplay = mContext.getPackageManager()
747 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700748 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
749 final boolean forceResizable = Settings.Global.getInt(
750 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700751 final boolean sizeCompatFreeform = Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753
754 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900755 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756
757 final Configuration configuration = new Configuration();
758 Settings.System.getConfiguration(resolver, configuration);
759 if (forceRtl) {
760 // This will take care of setting the correct layout direction flags
761 configuration.setLayoutDirection(configuration.locale);
762 }
763
764 synchronized (mGlobalLock) {
765 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700766 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767 final boolean multiWindowFormEnabled = freeformWindowManagement
768 || supportsSplitScreenMultiWindow
769 || supportsPictureInPicture
770 || supportsMultiDisplay;
771 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
772 mSupportsMultiWindow = true;
773 mSupportsFreeformWindowManagement = freeformWindowManagement;
774 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
775 mSupportsPictureInPicture = supportsPictureInPicture;
776 mSupportsMultiDisplay = supportsMultiDisplay;
777 } else {
778 mSupportsMultiWindow = false;
779 mSupportsFreeformWindowManagement = false;
780 mSupportsSplitScreenMultiWindow = false;
781 mSupportsPictureInPicture = false;
782 mSupportsMultiDisplay = false;
783 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700784 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700785 // This happens before any activities are started, so we can change global configuration
786 // in-place.
787 updateConfigurationLocked(configuration, null, true);
788 final Configuration globalConfig = getGlobalConfiguration();
789 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
790
791 // Load resources only after the current configuration has been set.
792 final Resources res = mContext.getResources();
793 mThumbnailWidth = res.getDimensionPixelSize(
794 com.android.internal.R.dimen.thumbnail_width);
795 mThumbnailHeight = res.getDimensionPixelSize(
796 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 }
798 }
799
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800800 public WindowManagerGlobalLock getGlobalLock() {
801 return mGlobalLock;
802 }
803
Yunfan Chen585f2932019-01-29 16:04:45 +0900804 /** For test purpose only. */
805 @VisibleForTesting
806 public ActivityTaskManagerInternal getAtmInternal() {
807 return mInternal;
808 }
809
Riddle Hsud93a6c42018-11-29 21:50:06 +0800810 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
811 Looper looper) {
812 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700814 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700815 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800816 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700817 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700818 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
820 mTempConfig.setToDefaults();
821 mTempConfig.setLocales(LocaleList.getDefault());
822 mConfigurationSeq = mTempConfig.seq = 1;
823 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800824 mRootActivityContainer = new RootActivityContainer(this);
825 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700826
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700828 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700829 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700831 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700832 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700833 mKeyguardController = mStackSupervisor.getKeyguardController();
834 }
835
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700836 public void onActivityManagerInternalAdded() {
837 synchronized (mGlobalLock) {
838 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
839 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
840 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700841 }
842
Yunfan Chen75157d72018-07-27 14:47:21 +0900843 int increaseConfigurationSeqLocked() {
844 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
845 return mConfigurationSeq;
846 }
847
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700848 protected ActivityStackSupervisor createStackSupervisor() {
849 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
850 supervisor.initialize();
851 return supervisor;
852 }
853
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800854 protected AppWarnings createAppWarnings(
855 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
856 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
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,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700896 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100897 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)
Louis Chang54fbb052019-10-16 17:10:17 +08001066 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 .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)
Louis Chang54fbb052019-10-16 17:10:17 +08001237 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .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)
Louis Chang54fbb052019-10-16 17:10:17 +08001264 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001265 .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)
Louis Chang54fbb052019-10-16 17:10:17 +08001394 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395 .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)
Louis Chang54fbb052019-10-16 17:10:17 +08001442 .setUserId(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)
Louis Chang54fbb052019-10-16 17:10:17 +08001458 .setUserId(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();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001616 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 try {
1618 boolean res;
1619 final boolean finishWithRootActivity =
1620 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1621 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1622 || (finishWithRootActivity && r == rootR)) {
1623 // If requested, remove the task that is associated to this activity only if it
1624 // was the root activity in the task. The result code and data is ignored
1625 // because we don't support returning them across task boundaries. Also, to
1626 // keep backwards compatibility we remove the task from recents when finishing
1627 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001628 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 finishWithRootActivity, "finish-activity");
1630 if (!res) {
1631 Slog.i(TAG, "Removing task failed to finish activity");
1632 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001633 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001634 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001636 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001637 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 if (!res) {
1639 Slog.i(TAG, "Failed to finish by app-request");
1640 }
1641 }
1642 return res;
1643 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001644 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public boolean finishActivityAffinity(IBinder token) {
1652 synchronized (mGlobalLock) {
1653 final long origId = Binder.clearCallingIdentity();
1654 try {
1655 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1656 if (r == null) {
1657 return false;
1658 }
1659
1660 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1661 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001662 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 return false;
1664 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001665 r.finishActivityAffinity();
1666 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 } finally {
1668 Binder.restoreCallingIdentity(origId);
1669 }
1670 }
1671 }
1672
1673 @Override
1674 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1675 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001676 try {
1677 WindowProcessController proc = null;
1678 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001679 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001680 ActivityStack stack = ActivityRecord.getStackLocked(token);
1681 if (stack == null) {
1682 return;
1683 }
1684 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1685 false /* fromTimeout */, false /* processPausingActivities */, config);
1686 if (r != null) {
1687 proc = r.app;
1688 }
1689 if (stopProfiling && proc != null) {
1690 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 }
1692 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001693 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001694 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 }
1698
1699 @Override
1700 public final void activityResumed(IBinder token) {
1701 final long origId = Binder.clearCallingIdentity();
1702 synchronized (mGlobalLock) {
1703 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 }
1705 Binder.restoreCallingIdentity(origId);
1706 }
1707
1708 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001709 public final void activityTopResumedStateLost() {
1710 final long origId = Binder.clearCallingIdentity();
1711 synchronized (mGlobalLock) {
1712 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1713 }
1714 Binder.restoreCallingIdentity(origId);
1715 }
1716
1717 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 public final void activityPaused(IBinder token) {
1719 final long origId = Binder.clearCallingIdentity();
1720 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001721 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 ActivityStack stack = ActivityRecord.getStackLocked(token);
1723 if (stack != null) {
1724 stack.activityPausedLocked(token, false);
1725 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001726 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 }
1728 Binder.restoreCallingIdentity(origId);
1729 }
1730
1731 @Override
1732 public final void activityStopped(IBinder token, Bundle icicle,
1733 PersistableBundle persistentState, CharSequence description) {
1734 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1735
1736 // Refuse possible leaked file descriptors
1737 if (icicle != null && icicle.hasFileDescriptors()) {
1738 throw new IllegalArgumentException("File descriptors passed in Bundle");
1739 }
1740
1741 final long origId = Binder.clearCallingIdentity();
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 String restartingName = null;
1744 int restartingUid = 0;
1745 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001747 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001748 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001750 if (r.attachedToProcess()
1751 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1752 // The activity was requested to restart from
1753 // {@link #restartActivityProcessIfVisible}.
1754 restartingName = r.app.mName;
1755 restartingUid = r.app.mUid;
1756 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 r.activityStoppedLocked(icicle, persistentState, description);
1758 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001759 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 }
1761
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001762 if (restartingName != null) {
1763 // In order to let the foreground activity can be restarted with its saved state from
1764 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1765 // until the activity reports stopped with the state. And the activity record will be
1766 // kept because the record state is restarting, then the activity will be restarted
1767 // immediately if it is still the top one.
1768 mStackSupervisor.removeRestartTimeouts(r);
1769 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1770 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001771 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772
1773 Binder.restoreCallingIdentity(origId);
1774 }
1775
1776 @Override
1777 public final void activityDestroyed(IBinder token) {
1778 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1779 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001780 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001781 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001782 try {
1783 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1784 if (activity != null) {
1785 activity.destroyed("activityDestroyed");
1786 }
1787 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001788 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001789 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 }
1792 }
1793
1794 @Override
1795 public final void activityRelaunched(IBinder token) {
1796 final long origId = Binder.clearCallingIdentity();
1797 synchronized (mGlobalLock) {
1798 mStackSupervisor.activityRelaunchedLocked(token);
1799 }
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 public final void activitySlept(IBinder token) {
1804 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1805
1806 final long origId = Binder.clearCallingIdentity();
1807
1808 synchronized (mGlobalLock) {
1809 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1810 if (r != null) {
1811 mStackSupervisor.activitySleptLocked(r);
1812 }
1813 }
1814
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
1818 @Override
1819 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1820 synchronized (mGlobalLock) {
1821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return;
1824 }
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 r.setRequestedOrientation(requestedOrientation);
1828 } finally {
1829 Binder.restoreCallingIdentity(origId);
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public int getRequestedOrientation(IBinder token) {
1836 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001837 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 return (r != null)
1839 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842
1843 @Override
1844 public void setImmersive(IBinder token, boolean immersive) {
1845 synchronized (mGlobalLock) {
1846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 throw new IllegalArgumentException();
1849 }
1850 r.immersive = immersive;
1851
1852 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001853 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858 }
1859
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 void applyUpdateLockStateLocked(ActivityRecord r) {
1861 // Modifications to the UpdateLock state are done on our handler, outside
1862 // the activity manager's locks. The new state is determined based on the
1863 // state *now* of the relevant activity record. The object is passed to
1864 // the handler solely for logging detail, not to be consulted/modified.
1865 final boolean nextState = r != null && r.immersive;
1866 mH.post(() -> {
1867 if (mUpdateLock.isHeld() != nextState) {
1868 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1869 "Applying new update lock state '" + nextState + "' for " + r);
1870 if (nextState) {
1871 mUpdateLock.acquire();
1872 } else {
1873 mUpdateLock.release();
1874 }
1875 }
1876 });
1877 }
1878
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 @Override
1880 public boolean isImmersive(IBinder token) {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 throw new IllegalArgumentException();
1885 }
1886 return r.immersive;
1887 }
1888 }
1889
1890 @Override
1891 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 return (r != null) ? r.immersive : false;
1896 }
1897 }
1898
1899 @Override
1900 public void overridePendingTransition(IBinder token, String packageName,
1901 int enterAnim, int exitAnim) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1904 if (self == null) {
1905 return;
1906 }
1907
1908 final long origId = Binder.clearCallingIdentity();
1909
1910 if (self.isState(
1911 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001912 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001913 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
1915
1916 Binder.restoreCallingIdentity(origId);
1917 }
1918 }
1919
1920 @Override
1921 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001924 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 if (r == null) {
1926 return ActivityManager.COMPAT_MODE_UNKNOWN;
1927 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 if (r == null) {
1940 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1941 return;
1942 }
1943 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public int getLaunchedFromUid(IBinder activityToken) {
1950 ActivityRecord srec;
1951 synchronized (mGlobalLock) {
1952 srec = ActivityRecord.forTokenLocked(activityToken);
1953 }
1954 if (srec == null) {
1955 return -1;
1956 }
1957 return srec.launchedFromUid;
1958 }
1959
1960 @Override
1961 public String getLaunchedFromPackage(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return null;
1968 }
1969 return srec.launchedFromPackage;
1970 }
1971
1972 @Override
1973 public boolean convertFromTranslucent(IBinder token) {
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001981 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 } finally {
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public boolean convertToTranslucent(IBinder token, Bundle options) {
1990 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1991 final long origId = Binder.clearCallingIdentity();
1992 try {
1993 synchronized (mGlobalLock) {
1994 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1995 if (r == null) {
1996 return false;
1997 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001998 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 int index = task.mActivities.lastIndexOf(r);
2000 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002001 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2003 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002004 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 } finally {
2007 Binder.restoreCallingIdentity(origId);
2008 }
2009 }
2010
2011 @Override
2012 public void notifyActivityDrawn(IBinder token) {
2013 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2014 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002015 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002017 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 }
2019 }
2020 }
2021
2022 @Override
2023 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2024 synchronized (mGlobalLock) {
2025 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2026 if (r == null) {
2027 return;
2028 }
2029 r.reportFullyDrawnLocked(restoredFromBundle);
2030 }
2031 }
2032
2033 @Override
2034 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2035 synchronized (mGlobalLock) {
2036 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2037 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2038 return stack.mDisplayId;
2039 }
2040 return DEFAULT_DISPLAY;
2041 }
2042 }
2043
2044 @Override
2045 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 long ident = Binder.clearCallingIdentity();
2048 try {
2049 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002050 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002052 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 }
2054 return null;
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(ident);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 if (stack == null) {
2070 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2071 return;
2072 }
2073 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
2084 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2087 final long callingId = Binder.clearCallingIdentity();
2088 try {
2089 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002090 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002091 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 if (task == null) {
2093 return;
2094 }
2095 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002096 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002097 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 }
2099 }
2100 } finally {
2101 Binder.restoreCallingIdentity(callingId);
2102 }
2103 }
2104
2105 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002106 public void restartActivityProcessIfVisible(IBinder activityToken) {
2107 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2108 final long callingId = Binder.clearCallingIdentity();
2109 try {
2110 synchronized (mGlobalLock) {
2111 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2112 if (r == null) {
2113 return;
2114 }
2115 r.restartProcessIfVisible();
2116 }
2117 } finally {
2118 Binder.restoreCallingIdentity(callingId);
2119 }
2120 }
2121
2122 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002125 synchronized (mGlobalLock) {
2126 final long ident = Binder.clearCallingIdentity();
2127 try {
2128 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2129 "remove-task");
2130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134 }
2135
2136 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002137 public void removeAllVisibleRecentTasks() {
2138 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2139 synchronized (mGlobalLock) {
2140 final long ident = Binder.clearCallingIdentity();
2141 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002142 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002143 } finally {
2144 Binder.restoreCallingIdentity(ident);
2145 }
2146 }
2147 }
2148
2149 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002150 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2151 synchronized (mGlobalLock) {
2152 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2153 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002154 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 }
2156 }
2157 return false;
2158 }
2159
2160 @Override
2161 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2162 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002163
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002164 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002165 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2166 if (r != null) {
2167 return r.getActivityStack().navigateUpToLocked(
2168 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002169 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002170 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002171 }
2172 }
2173
2174 /**
2175 * Attempts to move a task backwards in z-order (the order of activities within the task is
2176 * unchanged).
2177 *
2178 * There are several possible results of this call:
2179 * - if the task is locked, then we will show the lock toast
2180 * - if there is a task behind the provided task, then that task is made visible and resumed as
2181 * this task is moved to the back
2182 * - otherwise, if there are no other tasks in the stack:
2183 * - if this task is in the pinned stack, then we remove the stack completely, which will
2184 * have the effect of moving the task to the top or bottom of the fullscreen stack
2185 * (depending on whether it is visible)
2186 * - otherwise, we simply return home and hide this task
2187 *
2188 * @param token A reference to the activity we wish to move
2189 * @param nonRoot If false then this only works if the activity is the root
2190 * of a task; if true it will work for any activity in a task.
2191 * @return Returns true if the move completed, false if not.
2192 */
2193 @Override
2194 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002195 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 synchronized (mGlobalLock) {
2197 final long origId = Binder.clearCallingIdentity();
2198 try {
2199 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002200 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 if (task != null) {
2202 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2203 }
2204 } finally {
2205 Binder.restoreCallingIdentity(origId);
2206 }
2207 }
2208 return false;
2209 }
2210
2211 @Override
2212 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002213 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 long ident = Binder.clearCallingIdentity();
2215 Rect rect = new Rect();
2216 try {
2217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2220 if (task == null) {
2221 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2222 return rect;
2223 }
2224 if (task.getStack() != null) {
2225 // Return the bounds from window manager since it will be adjusted for various
2226 // things like the presense of a docked stack for tasks that aren't resizeable.
2227 task.getWindowContainerBounds(rect);
2228 } else {
2229 // Task isn't in window manager yet since it isn't associated with a stack.
2230 // Return the persist value from activity manager
2231 if (!task.matchParentBounds()) {
2232 rect.set(task.getBounds());
2233 } else if (task.mLastNonFullscreenBounds != null) {
2234 rect.set(task.mLastNonFullscreenBounds);
2235 }
2236 }
2237 }
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 return rect;
2242 }
2243
2244 @Override
2245 public ActivityManager.TaskDescription getTaskDescription(int id) {
2246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002249 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2251 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002252 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254 }
2255 return null;
2256 }
2257
2258 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2260 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2261 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2262 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2263 return;
2264 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 synchronized (mGlobalLock) {
2267 final long ident = Binder.clearCallingIdentity();
2268 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002269 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002270 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 if (task == null) {
2272 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2273 return;
2274 }
2275
2276 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2277 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2278
2279 if (!task.isActivityTypeStandardOrUndefined()) {
2280 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2281 + " non-standard task " + taskId + " to windowing mode="
2282 + windowingMode);
2283 }
2284
2285 final ActivityStack stack = task.getStack();
2286 if (toTop) {
2287 stack.moveToFront("setTaskWindowingMode", task);
2288 }
2289 stack.setWindowingMode(windowingMode);
2290 } finally {
2291 Binder.restoreCallingIdentity(ident);
2292 }
2293 }
2294 }
2295
2296 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.info.packageName : null;
2301 }
2302 }
2303
2304 @Override
2305 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 ActivityRecord r = getCallingRecordLocked(token);
2308 return r != null ? r.intent.getComponent() : null;
2309 }
2310 }
2311
2312 private ActivityRecord getCallingRecordLocked(IBinder token) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return null;
2316 }
2317 return r.resultTo;
2318 }
2319
2320 @Override
2321 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323
2324 synchronized (mGlobalLock) {
2325 final long origId = Binder.clearCallingIdentity();
2326 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002327 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 } finally {
2329 Binder.restoreCallingIdentity(origId);
2330 }
2331 }
2332 }
2333
Mark Renouf446251d2019-04-26 10:22:41 -04002334 @Override
2335 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2336 synchronized (mGlobalLock) {
2337 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2338 if (r == null) {
2339 return;
2340 }
2341 ActivityStack stack = r.getActivityStack();
2342 if (stack != null && stack.isSingleTaskInstance()) {
2343 // Single-task stacks are used for activities which are presented in floating
2344 // windows above full screen activities. Instead of directly finishing the
2345 // task, a task change listener is used to notify SystemUI so the action can be
2346 // handled specially.
2347 final TaskRecord task = r.getTaskRecord();
2348 mTaskChangeNotificationController
2349 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2350 } else {
2351 try {
2352 callback.requestFinish();
2353 } catch (RemoteException e) {
2354 Slog.e(TAG, "Failed to invoke request finish callback", e);
2355 }
2356 }
2357 }
2358 }
2359
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 /**
2361 * TODO: Add mController hook
2362 */
2363 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2365 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367
2368 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2369 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2371 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 }
2373 }
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2376 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002378
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 final int callingPid = Binder.getCallingPid();
2380 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002381 if (!isSameApp(callingUid, callingPackage)) {
2382 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2383 + Binder.getCallingPid() + " as package " + callingPackage;
2384 Slog.w(TAG, msg);
2385 throw new SecurityException(msg);
2386 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 SafeActivityOptions.abort(options);
2389 return;
2390 }
2391 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 WindowProcessController callerApp = null;
2393 if (appThread != null) {
2394 callerApp = getProcessController(appThread);
2395 }
2396 final ActivityStarter starter = getActivityStartController().obtainStarter(
2397 null /* intent */, "moveTaskToFront");
2398 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2399 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002400 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002401 return;
2402 }
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 if (task == null) {
2407 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002408 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 return;
2410 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002411 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002413 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 return;
2415 }
2416 ActivityOptions realOptions = options != null
2417 ? options.getOptions(mStackSupervisor)
2418 : null;
2419 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2420 false /* forceNonResizable */);
2421
2422 final ActivityRecord topActivity = task.getTopActivity();
2423 if (topActivity != null) {
2424
2425 // We are reshowing a task, use a starting window to hide the initial draw delay
2426 // so the transition can start earlier.
2427 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2428 true /* taskSwitch */, fromRecents);
2429 }
2430 } finally {
2431 Binder.restoreCallingIdentity(origId);
2432 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 }
2434
Ricky Waiaca8a772019-04-04 16:01:06 +01002435 /**
2436 * Return true if callingUid is system, or packageName belongs to that callingUid.
2437 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002438 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002439 try {
2440 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2441 if (packageName == null) {
2442 return false;
2443 }
2444 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2445 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2446 UserHandle.getUserId(callingUid));
2447 return UserHandle.isSameApp(callingUid, uid);
2448 }
2449 } catch (RemoteException e) {
2450 // Should not happen
2451 }
2452 return true;
2453 }
2454
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2456 int callingPid, int callingUid, String name) {
2457 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2458 return true;
2459 }
2460
2461 if (getRecentTasks().isCallerRecents(sourceUid)) {
2462 return true;
2463 }
2464
2465 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2466 if (perm == PackageManager.PERMISSION_GRANTED) {
2467 return true;
2468 }
2469 if (checkAllowAppSwitchUid(sourceUid)) {
2470 return true;
2471 }
2472
2473 // If the actual IPC caller is different from the logical source, then
2474 // also see if they are allowed to control app switches.
2475 if (callingUid != -1 && callingUid != sourceUid) {
2476 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(callingUid)) {
2481 return true;
2482 }
2483 }
2484
2485 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2486 return false;
2487 }
2488
2489 private boolean checkAllowAppSwitchUid(int uid) {
2490 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2491 if (types != null) {
2492 for (int i = types.size() - 1; i >= 0; i--) {
2493 if (types.valueAt(i).intValue() == uid) {
2494 return true;
2495 }
2496 }
2497 }
2498 return false;
2499 }
2500
2501 @Override
2502 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2503 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2504 "setActivityController()");
2505 synchronized (mGlobalLock) {
2506 mController = controller;
2507 mControllerIsAMonkey = imAMonkey;
2508 Watchdog.getInstance().setActivityController(controller);
2509 }
2510 }
2511
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002512 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 synchronized (mGlobalLock) {
2514 return mController != null && mControllerIsAMonkey;
2515 }
2516 }
2517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 @Override
2519 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2520 synchronized (mGlobalLock) {
2521 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2522 }
2523 }
2524
2525 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2527 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2528 }
2529
2530 @Override
2531 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2532 @WindowConfiguration.ActivityType int ignoreActivityType,
2533 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2534 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002535 final int callingPid = Binder.getCallingPid();
2536 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002537 final int[] profileIds = getUserManager().getProfileIds(
2538 UserHandle.getUserId(callingUid), true);
2539 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2540 for (int i = 0; i < profileIds.length; i++) {
2541 callingProfileIds.add(profileIds[i]);
2542 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2544
2545 synchronized (mGlobalLock) {
2546 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2547
Nicholas Sauer0259e532019-08-30 08:24:55 -07002548 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002549 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002550 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 }
2552
2553 return list;
2554 }
2555
2556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2558 synchronized (mGlobalLock) {
2559 final long origId = Binder.clearCallingIdentity();
2560 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2561 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002562 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002563 }
2564 Binder.restoreCallingIdentity(origId);
2565 }
2566 }
2567
2568 @Override
2569 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 ActivityStack stack = ActivityRecord.getStackLocked(token);
2572 if (stack != null) {
2573 return stack.willActivityBeVisibleLocked(token);
2574 }
2575 return false;
2576 }
2577 }
2578
2579 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 synchronized (mGlobalLock) {
2583 final long ident = Binder.clearCallingIdentity();
2584 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (task == null) {
2587 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2588 return;
2589 }
2590
2591 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2592 + " to stackId=" + stackId + " toTop=" + toTop);
2593
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 if (stack == null) {
2596 throw new IllegalStateException(
2597 "moveTaskToStack: No stack for stackId=" + stackId);
2598 }
2599 if (!stack.isActivityTypeStandardOrUndefined()) {
2600 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2601 + taskId + " to stack " + stackId);
2602 }
2603 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002604 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2606 }
2607 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2608 "moveTaskToStack");
2609 } finally {
2610 Binder.restoreCallingIdentity(ident);
2611 }
2612 }
2613 }
2614
2615 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002616 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2617 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002618
2619 final long ident = Binder.clearCallingIdentity();
2620 try {
2621 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002622 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2623 if (stack == null) {
2624 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2625 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002627 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2628 throw new IllegalArgumentException("Stack: " + stackId
2629 + " doesn't support animated resize.");
2630 }
2631 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2632 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
2638
wilsonshih5c4cf522019-01-25 09:03:47 +08002639 @Override
2640 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2641 int animationDuration) {
2642 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2643
2644 final long ident = Binder.clearCallingIdentity();
2645 try {
2646 synchronized (mGlobalLock) {
2647 if (xOffset == 0 && yOffset == 0) {
2648 return;
2649 }
2650 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2651 if (stack == null) {
2652 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2653 return;
2654 }
2655 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2656 throw new IllegalArgumentException("Stack: " + stackId
2657 + " doesn't support animated resize.");
2658 }
2659 final Rect destBounds = new Rect();
2660 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002661 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002662 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2663 return;
2664 }
2665 destBounds.offset(xOffset, yOffset);
2666 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2667 animationDuration, false /* fromFullscreen */);
2668 }
2669 } finally {
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002673 /**
2674 * Moves the specified task to the primary-split-screen stack.
2675 *
2676 * @param taskId Id of task to move.
2677 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2678 * exist already. See
2679 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2680 * and
2681 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2682 * @param toTop If the task and stack should be moved to the top.
2683 * @param animate Whether we should play an animation for the moving the task.
2684 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2685 * stack. Pass {@code null} to use default bounds.
2686 * @param showRecents If the recents activity should be shown on the other side of the task
2687 * going into split-screen mode.
2688 */
2689 @Override
2690 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2691 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002692 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 "setTaskWindowingModeSplitScreenPrimary()");
2694 synchronized (mGlobalLock) {
2695 final long ident = Binder.clearCallingIdentity();
2696 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002697 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002698 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 if (task == null) {
2700 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2701 return false;
2702 }
2703 if (DEBUG_STACK) Slog.d(TAG_STACK,
2704 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2705 + " to createMode=" + createMode + " toTop=" + toTop);
2706 if (!task.isActivityTypeStandardOrUndefined()) {
2707 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2708 + " non-standard task " + taskId + " to split-screen windowing mode");
2709 }
2710
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002711 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002712 final int windowingMode = task.getWindowingMode();
2713 final ActivityStack stack = task.getStack();
2714 if (toTop) {
2715 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2716 }
2717 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002718 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2719 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 return windowingMode != task.getWindowingMode();
2721 } finally {
2722 Binder.restoreCallingIdentity(ident);
2723 }
2724 }
2725 }
2726
2727 /**
2728 * Removes stacks in the input windowing modes from the system if they are of activity type
2729 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2730 */
2731 @Override
2732 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 "removeStacksInWindowingModes()");
2735
2736 synchronized (mGlobalLock) {
2737 final long ident = Binder.clearCallingIdentity();
2738 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002739 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 } finally {
2741 Binder.restoreCallingIdentity(ident);
2742 }
2743 }
2744 }
2745
2746 @Override
2747 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002748 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002749 "removeStacksWithActivityTypes()");
2750
2751 synchronized (mGlobalLock) {
2752 final long ident = Binder.clearCallingIdentity();
2753 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002754 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002755 } finally {
2756 Binder.restoreCallingIdentity(ident);
2757 }
2758 }
2759 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760
2761 @Override
2762 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2763 int userId) {
2764 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002765 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2766 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 final boolean detailed = checkGetTasksPermission(
2769 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2770 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 == PackageManager.PERMISSION_GRANTED;
2772
2773 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002774 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 callingUid);
2776 }
2777 }
2778
2779 @Override
2780 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 long ident = Binder.clearCallingIdentity();
2783 try {
2784 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002785 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 }
2787 } finally {
2788 Binder.restoreCallingIdentity(ident);
2789 }
2790 }
2791
2792 @Override
2793 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002794 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 long ident = Binder.clearCallingIdentity();
2796 try {
2797 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002798 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800 } finally {
2801 Binder.restoreCallingIdentity(ident);
2802 }
2803 }
2804
2805 @Override
2806 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 final long callingUid = Binder.getCallingUid();
2809 final long origId = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mGlobalLock) {
2812 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002813 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2815 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2816 }
2817 } finally {
2818 Binder.restoreCallingIdentity(origId);
2819 }
2820 }
2821
2822 @Override
2823 public void startLockTaskModeByToken(IBinder token) {
2824 synchronized (mGlobalLock) {
2825 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2826 if (r == null) {
2827 return;
2828 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002829 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 }
2831 }
2832
2833 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002834 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002835 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 // This makes inner call to look as if it was initiated by system.
2837 long ident = Binder.clearCallingIdentity();
2838 try {
2839 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002840 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002841 MATCH_TASK_IN_STACKS_ONLY);
2842 if (task == null) {
2843 return;
2844 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845
2846 // When starting lock task mode the stack must be in front and focused
2847 task.getStack().moveToFront("startSystemLockTaskMode");
2848 startLockTaskModeLocked(task, true /* isSystemCaller */);
2849 }
2850 } finally {
2851 Binder.restoreCallingIdentity(ident);
2852 }
2853 }
2854
2855 @Override
2856 public void stopLockTaskModeByToken(IBinder token) {
2857 synchronized (mGlobalLock) {
2858 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2859 if (r == null) {
2860 return;
2861 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002862 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 }
2864 }
2865
2866 /**
2867 * This API should be called by SystemUI only when user perform certain action to dismiss
2868 * lock task mode. We should only dismiss pinned lock task mode in this case.
2869 */
2870 @Override
2871 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002872 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2874 }
2875
2876 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2877 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2878 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2879 return;
2880 }
2881
Wale Ogunwaled32da472018-11-16 07:19:28 -08002882 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 if (stack == null || task != stack.topTask()) {
2884 throw new IllegalArgumentException("Invalid task, not in foreground");
2885 }
2886
2887 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2888 // system or a specific app.
2889 // * System-initiated requests will only start the pinned mode (screen pinning)
2890 // * App-initiated requests
2891 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2892 // - will start the pinned mode, otherwise
2893 final int callingUid = Binder.getCallingUid();
2894 long ident = Binder.clearCallingIdentity();
2895 try {
2896 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002897 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002899 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 } finally {
2901 Binder.restoreCallingIdentity(ident);
2902 }
2903 }
2904
2905 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2906 final int callingUid = Binder.getCallingUid();
2907 long ident = Binder.clearCallingIdentity();
2908 try {
2909 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002910 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 }
2912 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2913 // task and jumping straight into a call in the case of emergency call back.
2914 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2915 if (tm != null) {
2916 tm.showInCallScreen(false);
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002924 public void updateLockTaskPackages(int userId, String[] packages) {
2925 final int callingUid = Binder.getCallingUid();
2926 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2927 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2928 "updateLockTaskPackages()");
2929 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002930 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002931 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2932 + Arrays.toString(packages));
2933 getLockTaskController().updateLockTaskPackages(userId, packages);
2934 }
2935 }
2936
2937 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 public boolean isInLockTaskMode() {
2939 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2940 }
2941
2942 @Override
2943 public int getLockTaskModeState() {
2944 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002945 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 }
2948
2949 @Override
2950 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2951 synchronized (mGlobalLock) {
2952 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2953 if (r != null) {
2954 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002955 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002957 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 }
2959 }
2960 }
2961
2962 @Override
2963 public Bundle getActivityOptions(IBinder token) {
2964 final long origId = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
2967 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2968 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002969 final ActivityOptions activityOptions = r.takeOptionsLocked(
2970 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 return activityOptions == null ? null : activityOptions.toBundle();
2972 }
2973 return null;
2974 }
2975 } finally {
2976 Binder.restoreCallingIdentity(origId);
2977 }
2978 }
2979
2980 @Override
2981 public List<IBinder> getAppTasks(String callingPackage) {
2982 int callingUid = Binder.getCallingUid();
2983 long ident = Binder.clearCallingIdentity();
2984 try {
2985 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002986 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 }
2988 } finally {
2989 Binder.restoreCallingIdentity(ident);
2990 }
2991 }
2992
2993 @Override
2994 public void finishVoiceTask(IVoiceInteractionSession session) {
2995 synchronized (mGlobalLock) {
2996 final long origId = Binder.clearCallingIdentity();
2997 try {
2998 // TODO: VI Consider treating local voice interactions and voice tasks
2999 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003000 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 } finally {
3002 Binder.restoreCallingIdentity(origId);
3003 }
3004 }
3005
3006 }
3007
3008 @Override
3009 public boolean isTopOfTask(IBinder token) {
3010 synchronized (mGlobalLock) {
3011 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003012 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 }
3014 }
3015
3016 @Override
3017 public void notifyLaunchTaskBehindComplete(IBinder token) {
3018 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3019 }
3020
3021 @Override
3022 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003023 mH.post(() -> {
3024 synchronized (mGlobalLock) {
3025 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003026 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003027 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003028 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003029 } catch (RemoteException e) {
3030 }
3031 }
3032 }
3033
3034 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036
3037 /** Called from an app when assist data is ready. */
3038 @Override
3039 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3040 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 synchronized (pae) {
3043 pae.result = extras;
3044 pae.structure = structure;
3045 pae.content = content;
3046 if (referrer != null) {
3047 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3048 }
3049 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003050 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003051 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003052 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 structure.setHomeActivity(pae.isHome);
3054 }
3055 pae.haveResult = true;
3056 pae.notifyAll();
3057 if (pae.intent == null && pae.receiver == null) {
3058 // Caller is just waiting for the result.
3059 return;
3060 }
3061 }
3062 // We are now ready to launch the assist activity.
3063 IAssistDataReceiver sendReceiver = null;
3064 Bundle sendBundle = null;
3065 synchronized (mGlobalLock) {
3066 buildAssistBundleLocked(pae, extras);
3067 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003068 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 if (!exists) {
3070 // Timed out.
3071 return;
3072 }
3073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 // Caller wants result sent back to them.
3076 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003077 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003078 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003079 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3080 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3082 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3083 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3084 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3085 }
3086 }
3087 if (sendReceiver != null) {
3088 try {
3089 sendReceiver.onHandleAssistData(sendBundle);
3090 } catch (RemoteException e) {
3091 }
3092 return;
3093 }
3094
3095 final long ident = Binder.clearCallingIdentity();
3096 try {
3097 if (TextUtils.equals(pae.intent.getAction(),
3098 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003099 // Start voice interaction through VoiceInteractionManagerService.
3100 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3101 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 } else {
3103 pae.intent.replaceExtras(pae.extras);
3104 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3105 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3106 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003107 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003108
3109 try {
3110 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3111 } catch (ActivityNotFoundException e) {
3112 Slog.w(TAG, "No activity to handle assist action.", e);
3113 }
3114 }
3115 } finally {
3116 Binder.restoreCallingIdentity(ident);
3117 }
3118 }
3119
3120 @Override
3121 public int addAppTask(IBinder activityToken, Intent intent,
3122 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3123 final int callingUid = Binder.getCallingUid();
3124 final long callingIdent = Binder.clearCallingIdentity();
3125
3126 try {
3127 synchronized (mGlobalLock) {
3128 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3129 if (r == null) {
3130 throw new IllegalArgumentException("Activity does not exist; token="
3131 + activityToken);
3132 }
3133 ComponentName comp = intent.getComponent();
3134 if (comp == null) {
3135 throw new IllegalArgumentException("Intent " + intent
3136 + " must specify explicit component");
3137 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003138 if (thumbnail.getWidth() != mThumbnailWidth
3139 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 throw new IllegalArgumentException("Bad thumbnail size: got "
3141 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 }
3144 if (intent.getSelector() != null) {
3145 intent.setSelector(null);
3146 }
3147 if (intent.getSourceBounds() != null) {
3148 intent.setSourceBounds(null);
3149 }
3150 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3151 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3152 // The caller has added this as an auto-remove task... that makes no
3153 // sense, so turn off auto-remove.
3154 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3155 }
3156 }
3157 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3158 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3159 if (ainfo.applicationInfo.uid != callingUid) {
3160 throw new SecurityException(
3161 "Can't add task for another application: target uid="
3162 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3163 }
3164
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003165 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003167 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003169 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 // The app has too many tasks already and we can't add any more
3171 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3172 return INVALID_TASK_ID;
3173 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003174 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175
3176 // TODO: Send the thumbnail to WM to store it.
3177
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003178 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 } finally {
3181 Binder.restoreCallingIdentity(callingIdent);
3182 }
3183 }
3184
3185 @Override
3186 public Point getAppTaskThumbnailSize() {
3187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 }
3190 }
3191
3192 @Override
3193 public void setTaskResizeable(int taskId, int resizeableMode) {
3194 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003195 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3197 if (task == null) {
3198 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3199 return;
3200 }
3201 task.setResizeMode(resizeableMode);
3202 }
3203 }
3204
3205 @Override
3206 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003207 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 long ident = Binder.clearCallingIdentity();
3209 try {
3210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003211 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003212 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 if (task == null) {
3214 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3215 return;
3216 }
3217 // Place the task in the right stack if it isn't there already based on
3218 // the requested bounds.
3219 // The stack transition logic is:
3220 // - a null bounds on a freeform task moves that task to fullscreen
3221 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3222 // that task to freeform
3223 // - otherwise the task is not moved
3224 ActivityStack stack = task.getStack();
3225 if (!task.getWindowConfiguration().canResizeTask()) {
3226 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3227 }
3228 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3229 stack = stack.getDisplay().getOrCreateStack(
3230 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3231 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3232 stack = stack.getDisplay().getOrCreateStack(
3233 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3234 }
3235
3236 // Reparent the task to the right stack if necessary
3237 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3238 if (stack != task.getStack()) {
3239 // Defer resume until the task is resized below
3240 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3241 DEFER_RESUME, "resizeTask");
3242 preserveWindow = false;
3243 }
3244
3245 // After reparenting (which only resizes the task to the stack bounds), resize the
3246 // task to the actual bounds provided
3247 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3248 }
3249 } finally {
3250 Binder.restoreCallingIdentity(ident);
3251 }
3252 }
3253
Evan Roskyddedfd42019-10-04 13:38:38 -07003254 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3255 WindowContainerTransaction.Change change) {
3256 if (!(container instanceof TaskRecord)) {
3257 throw new RuntimeException("Invalid token in task transaction");
3258 }
3259 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3260 // masks here.
3261 int configMask = change.getConfigSetMask();
3262 int windowMask = change.getWindowSetMask();
3263 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3264 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3265 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3266 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3267 c.setTo(change.getConfiguration(), configMask, windowMask);
3268 container.onRequestedOverrideConfigurationChanged(c);
3269 }
3270
3271 @Override
3272 public void applyContainerTransaction(WindowContainerTransaction t) {
3273 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3274 long ident = Binder.clearCallingIdentity();
3275 try {
3276 if (t == null) {
3277 return;
3278 }
3279 synchronized (mGlobalLock) {
3280 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3281 t.getChanges().entrySet().iterator();
3282 while (entries.hasNext()) {
3283 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3284 entries.next();
3285 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3286 entry.getKey()).getContainer();
3287 sanitizeAndApplyConfigChange(cc, entry.getValue());
3288 }
3289 }
3290 } finally {
3291 Binder.restoreCallingIdentity(ident);
3292 }
3293 }
3294
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 @Override
3296 public boolean releaseActivityInstance(IBinder token) {
3297 synchronized (mGlobalLock) {
3298 final long origId = Binder.clearCallingIdentity();
3299 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003300 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3301 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 return false;
3303 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003304 r.destroyImmediately(true /* removeFromApp */, "app-req");
3305 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 } finally {
3307 Binder.restoreCallingIdentity(origId);
3308 }
3309 }
3310 }
3311
3312 @Override
3313 public void releaseSomeActivities(IApplicationThread appInt) {
3314 synchronized (mGlobalLock) {
3315 final long origId = Binder.clearCallingIdentity();
3316 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003317 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003318 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 } finally {
3320 Binder.restoreCallingIdentity(origId);
3321 }
3322 }
3323 }
3324
3325 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003326 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003327 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 != PackageManager.PERMISSION_GRANTED) {
3329 throw new SecurityException("Requires permission "
3330 + android.Manifest.permission.DEVICE_POWER);
3331 }
3332
3333 synchronized (mGlobalLock) {
3334 long ident = Binder.clearCallingIdentity();
3335 if (mKeyguardShown != keyguardShowing) {
3336 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003337 final Message msg = PooledLambda.obtainMessage(
3338 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3339 keyguardShowing);
3340 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 }
3342 try {
wilsonshih177261f2019-02-22 12:02:18 +08003343 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 } finally {
3345 Binder.restoreCallingIdentity(ident);
3346 }
3347 }
3348
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 mH.post(() -> {
3350 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3351 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3352 }
3353 });
3354 }
3355
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003356 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003357 mH.post(() -> {
3358 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3359 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3360 }
3361 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 }
3363
3364 @Override
3365 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3367 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 final File passedIconFile = new File(filePath);
3370 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3371 passedIconFile.getName());
3372 if (!legitIconFile.getPath().equals(filePath)
3373 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3374 throw new IllegalArgumentException("Bad file path: " + filePath
3375 + " passed for userId " + userId);
3376 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003377 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 }
3379
3380 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 synchronized (mGlobalLock) {
3384 final long ident = Binder.clearCallingIdentity();
3385 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003386 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 if (stack == null) {
3388 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3389 return;
3390 }
3391 if (!stack.isActivityTypeStandardOrUndefined()) {
3392 throw new IllegalArgumentException(
3393 "Removing non-standard stack is not allowed.");
3394 }
3395 mStackSupervisor.removeStack(stack);
3396 } finally {
3397 Binder.restoreCallingIdentity(ident);
3398 }
3399 }
3400 }
3401
3402 @Override
3403 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405
3406 synchronized (mGlobalLock) {
3407 final long ident = Binder.clearCallingIdentity();
3408 try {
3409 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3410 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003411 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
3415 }
3416 }
3417
3418 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003419 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 synchronized (mGlobalLock) {
3421 long ident = Binder.clearCallingIdentity();
3422 try {
3423 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3424 if (r == null) {
3425 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003426 "toggleFreeformWindowingMode: No activity record matching token="
3427 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 }
3429
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003430 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003431 if (stack == null) {
3432 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3433 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 }
3435
Yunfan Chend967af82019-01-17 18:30:18 +09003436 if (!stack.inFreeformWindowingMode()
3437 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3438 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3439 + "toggle between fullscreen and freeform.");
3440 }
3441
3442 if (stack.inFreeformWindowingMode()) {
3443 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003444 } else if (!mSizeCompatFreeform) {
3445 throw new IllegalStateException("Size-compat windows are currently not"
3446 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003447 } else if (stack.getParent().inFreeformWindowingMode()) {
3448 // If the window is on a freeform display, set it to undefined. It will be
3449 // resolved to freeform and it can adjust windowing mode when the display mode
3450 // changes in runtime.
3451 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003452 } else {
3453 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3454 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 } finally {
3456 Binder.restoreCallingIdentity(ident);
3457 }
3458 }
3459 }
3460
3461 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3462 @Override
3463 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003464 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003466 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 }
3468
3469 /** Unregister a task stack listener so that it stops receiving callbacks. */
3470 @Override
3471 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003474 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 }
3476
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003477 @Override
3478 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3479 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3480 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3481 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3482 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3483 }
3484
3485 @Override
3486 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3487 IBinder activityToken, int flags) {
3488 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3489 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3490 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3491 }
3492
3493 @Override
3494 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3495 Bundle args) {
3496 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3497 true /* focused */, true /* newSessionId */, userHandle, args,
3498 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3499 }
3500
3501 @Override
3502 public Bundle getAssistContextExtras(int requestType) {
3503 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3504 null, null, true /* focused */, true /* newSessionId */,
3505 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3506 if (pae == null) {
3507 return null;
3508 }
3509 synchronized (pae) {
3510 while (!pae.haveResult) {
3511 try {
3512 pae.wait();
3513 } catch (InterruptedException e) {
3514 }
3515 }
3516 }
3517 synchronized (mGlobalLock) {
3518 buildAssistBundleLocked(pae, pae.result);
3519 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003520 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 }
3522 return pae.extras;
3523 }
3524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003525 /**
3526 * Binder IPC calls go through the public entry point.
3527 * This can be called with or without the global lock held.
3528 */
3529 private static int checkCallingPermission(String permission) {
3530 return checkPermission(
3531 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3532 }
3533
3534 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003535 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003536 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3537 mAmInternal.enforceCallingPermission(permission, func);
3538 }
3539 }
3540
3541 @VisibleForTesting
3542 int checkGetTasksPermission(String permission, int pid, int uid) {
3543 return checkPermission(permission, pid, uid);
3544 }
3545
3546 static int checkPermission(String permission, int pid, int uid) {
3547 if (permission == null) {
3548 return PackageManager.PERMISSION_DENIED;
3549 }
3550 return checkComponentPermission(permission, pid, uid, -1, true);
3551 }
3552
Wale Ogunwale214f3482018-10-04 11:00:47 -07003553 public static int checkComponentPermission(String permission, int pid, int uid,
3554 int owningUid, boolean exported) {
3555 return ActivityManagerService.checkComponentPermission(
3556 permission, pid, uid, owningUid, exported);
3557 }
3558
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3560 if (getRecentTasks().isCallerRecents(callingUid)) {
3561 // Always allow the recents component to get tasks
3562 return true;
3563 }
3564
3565 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3566 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3567 if (!allowed) {
3568 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3569 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3570 // Temporary compatibility: some existing apps on the system image may
3571 // still be requesting the old permission and not switched to the new
3572 // one; if so, we'll still allow them full access. This means we need
3573 // to see if they are holding the old permission and are a system app.
3574 try {
3575 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3576 allowed = true;
3577 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3578 + " is using old GET_TASKS but privileged; allowing");
3579 }
3580 } catch (RemoteException e) {
3581 }
3582 }
3583 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3584 + " does not hold REAL_GET_TASKS; limiting output");
3585 }
3586 return allowed;
3587 }
3588
Nicholas Sauer0259e532019-08-30 08:24:55 -07003589 boolean isCrossUserAllowed(int pid, int uid) {
3590 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3591 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3592 }
3593
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3595 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3596 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3597 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003598 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 "enqueueAssistContext()");
3600
3601 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003602 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 if (activity == null) {
3604 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3605 return null;
3606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3609 return null;
3610 }
3611 if (focused) {
3612 if (activityToken != null) {
3613 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3614 if (activity != caller) {
3615 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3616 + " is not current top " + activity);
3617 return null;
3618 }
3619 }
3620 } else {
3621 activity = ActivityRecord.forTokenLocked(activityToken);
3622 if (activity == null) {
3623 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3624 + " couldn't be found");
3625 return null;
3626 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003627 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3629 return null;
3630 }
3631 }
3632
3633 PendingAssistExtras pae;
3634 Bundle extras = new Bundle();
3635 if (args != null) {
3636 extras.putAll(args);
3637 }
3638 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003639 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640
3641 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3642 userHandle);
3643 pae.isHome = activity.isActivityTypeHome();
3644
3645 // Increment the sessionId if necessary
3646 if (newSessionId) {
3647 mViSessionId++;
3648 }
3649 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003650 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3651 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003652 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 } catch (RemoteException e) {
3655 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3656 return null;
3657 }
3658 return pae;
3659 }
3660 }
3661
3662 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3663 if (result != null) {
3664 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3665 }
3666 if (pae.hint != null) {
3667 pae.extras.putBoolean(pae.hint, true);
3668 }
3669 }
3670
3671 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3672 IAssistDataReceiver receiver;
3673 synchronized (mGlobalLock) {
3674 mPendingAssistExtras.remove(pae);
3675 receiver = pae.receiver;
3676 }
3677 if (receiver != null) {
3678 // Caller wants result sent back to them.
3679 Bundle sendBundle = new Bundle();
3680 // At least return the receiver extras
3681 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3682 try {
3683 pae.receiver.onHandleAssistData(sendBundle);
3684 } catch (RemoteException e) {
3685 }
3686 }
3687 }
3688
3689 public class PendingAssistExtras extends Binder implements Runnable {
3690 public final ActivityRecord activity;
3691 public boolean isHome;
3692 public final Bundle extras;
3693 public final Intent intent;
3694 public final String hint;
3695 public final IAssistDataReceiver receiver;
3696 public final int userHandle;
3697 public boolean haveResult = false;
3698 public Bundle result = null;
3699 public AssistStructure structure = null;
3700 public AssistContent content = null;
3701 public Bundle receiverExtras;
3702
3703 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3704 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3705 int _userHandle) {
3706 activity = _activity;
3707 extras = _extras;
3708 intent = _intent;
3709 hint = _hint;
3710 receiver = _receiver;
3711 receiverExtras = _receiverExtras;
3712 userHandle = _userHandle;
3713 }
3714
3715 @Override
3716 public void run() {
3717 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3718 synchronized (this) {
3719 haveResult = true;
3720 notifyAll();
3721 }
3722 pendingAssistExtrasTimedOut(this);
3723 }
3724 }
3725
3726 @Override
3727 public boolean isAssistDataAllowedOnCurrentActivity() {
3728 int userId;
3729 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003730 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3732 return false;
3733 }
3734
3735 final ActivityRecord activity = focusedStack.getTopActivity();
3736 if (activity == null) {
3737 return false;
3738 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003739 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 }
3741 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3742 }
3743
3744 @Override
3745 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3746 long ident = Binder.clearCallingIdentity();
3747 try {
3748 synchronized (mGlobalLock) {
3749 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003750 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 if (top != caller) {
3752 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3753 + " is not current top " + top);
3754 return false;
3755 }
3756 if (!top.nowVisible) {
3757 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3758 + " is not visible");
3759 return false;
3760 }
3761 }
3762 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3763 token);
3764 } finally {
3765 Binder.restoreCallingIdentity(ident);
3766 }
3767 }
3768
3769 @Override
3770 public boolean isRootVoiceInteraction(IBinder token) {
3771 synchronized (mGlobalLock) {
3772 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3773 if (r == null) {
3774 return false;
3775 }
3776 return r.rootVoiceInteraction;
3777 }
3778 }
3779
Wale Ogunwalef6733932018-06-27 05:14:34 -07003780 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3781 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3782 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3783 if (activityToCallback == null) return;
3784 activityToCallback.setVoiceSessionLocked(voiceSession);
3785
3786 // Inform the activity
3787 try {
3788 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3789 voiceInteractor);
3790 long token = Binder.clearCallingIdentity();
3791 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003792 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003793 } finally {
3794 Binder.restoreCallingIdentity(token);
3795 }
3796 // TODO: VI Should we cache the activity so that it's easier to find later
3797 // rather than scan through all the stacks and activities?
3798 } catch (RemoteException re) {
3799 activityToCallback.clearVoiceSessionLocked();
3800 // TODO: VI Should this terminate the voice session?
3801 }
3802 }
3803
3804 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3805 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3806 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3807 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3808 boolean wasRunningVoice = mRunningVoice != null;
3809 mRunningVoice = session;
3810 if (!wasRunningVoice) {
3811 mVoiceWakeLock.acquire();
3812 updateSleepIfNeededLocked();
3813 }
3814 }
3815 }
3816
3817 void finishRunningVoiceLocked() {
3818 if (mRunningVoice != null) {
3819 mRunningVoice = null;
3820 mVoiceWakeLock.release();
3821 updateSleepIfNeededLocked();
3822 }
3823 }
3824
3825 @Override
3826 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3827 synchronized (mGlobalLock) {
3828 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3829 if (keepAwake) {
3830 mVoiceWakeLock.acquire();
3831 } else {
3832 mVoiceWakeLock.release();
3833 }
3834 }
3835 }
3836 }
3837
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 @Override
3839 public ComponentName getActivityClassForToken(IBinder token) {
3840 synchronized (mGlobalLock) {
3841 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3842 if (r == null) {
3843 return null;
3844 }
3845 return r.intent.getComponent();
3846 }
3847 }
3848
3849 @Override
3850 public String getPackageForToken(IBinder token) {
3851 synchronized (mGlobalLock) {
3852 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3853 if (r == null) {
3854 return null;
3855 }
3856 return r.packageName;
3857 }
3858 }
3859
3860 @Override
3861 public void showLockTaskEscapeMessage(IBinder token) {
3862 synchronized (mGlobalLock) {
3863 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3864 if (r == null) {
3865 return;
3866 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003867 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 }
3869 }
3870
3871 @Override
3872 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003873 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 final long token = Binder.clearCallingIdentity();
3875 try {
3876 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003877 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(token);
3881 }
3882 }
3883
3884 /**
3885 * Try to place task to provided position. The final position might be different depending on
3886 * current user and stacks state. The task will be moved to target stack if it's currently in
3887 * different stack.
3888 */
3889 @Override
3890 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003891 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003892 synchronized (mGlobalLock) {
3893 long ident = Binder.clearCallingIdentity();
3894 try {
3895 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3896 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003897 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 if (task == null) {
3899 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3900 + taskId);
3901 }
3902
Wale Ogunwaled32da472018-11-16 07:19:28 -08003903 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003904
3905 if (stack == null) {
3906 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3907 + stackId);
3908 }
3909 if (!stack.isActivityTypeStandardOrUndefined()) {
3910 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3911 + " the position of task " + taskId + " in/to non-standard stack");
3912 }
3913
3914 // TODO: Have the callers of this API call a separate reparent method if that is
3915 // what they intended to do vs. having this method also do reparenting.
3916 if (task.getStack() == stack) {
3917 // Change position in current stack.
3918 stack.positionChildAt(task, position);
3919 } else {
3920 // Reparent to new stack.
3921 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3922 !DEFER_RESUME, "positionTaskInStack");
3923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(ident);
3926 }
3927 }
3928 }
3929
3930 @Override
3931 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3932 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3933 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003934 + Arrays.toString(horizontalSizeConfiguration) + " "
3935 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 synchronized (mGlobalLock) {
3937 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3938 if (record == null) {
3939 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3940 + "found for: " + token);
3941 }
3942 record.setSizeConfigurations(horizontalSizeConfiguration,
3943 verticalSizeConfigurations, smallestSizeConfigurations);
3944 }
3945 }
3946
3947 /**
3948 * Dismisses split-screen multi-window mode.
3949 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3950 */
3951 @Override
3952 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003953 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3955 final long ident = Binder.clearCallingIdentity();
3956 try {
3957 synchronized (mGlobalLock) {
3958 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003959 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 if (stack == null) {
3961 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3962 return;
3963 }
3964
3965 if (toTop) {
3966 // Caller wants the current split-screen primary stack to be the top stack after
3967 // it goes fullscreen, so move it to the front.
3968 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003969 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003971 // stack after it goes fullscreen, so we move the focus to the top-most
3972 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3974 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3975 if (otherStack != null) {
3976 otherStack.moveToFront("dismissSplitScreenMode_other");
3977 }
3978 }
3979
Evan Rosky10475742018-09-05 19:02:48 -07003980 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 }
3982 } finally {
3983 Binder.restoreCallingIdentity(ident);
3984 }
3985 }
3986
3987 /**
3988 * Dismisses Pip
3989 * @param animate True if the dismissal should be animated.
3990 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3991 * default animation duration should be used.
3992 */
3993 @Override
3994 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 final long ident = Binder.clearCallingIdentity();
3997 try {
3998 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003999 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004000 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 if (stack == null) {
4002 Slog.w(TAG, "dismissPip: pinned stack not found.");
4003 return;
4004 }
4005 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4006 throw new IllegalArgumentException("Stack: " + stack
4007 + " doesn't support animated resize.");
4008 }
4009 if (animate) {
4010 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4011 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4012 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004013 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 }
4015 }
4016 } finally {
4017 Binder.restoreCallingIdentity(ident);
4018 }
4019 }
4020
4021 @Override
4022 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004023 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 synchronized (mGlobalLock) {
4025 mSuppressResizeConfigChanges = suppress;
4026 }
4027 }
4028
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 @Override
4030 // TODO: API should just be about changing windowing modes...
4031 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 "moveTasksToFullscreenStack()");
4034 synchronized (mGlobalLock) {
4035 final long origId = Binder.clearCallingIdentity();
4036 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004037 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 if (stack != null){
4039 if (!stack.isActivityTypeStandardOrUndefined()) {
4040 throw new IllegalArgumentException(
4041 "You can't move tasks from non-standard stacks.");
4042 }
4043 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(origId);
4047 }
4048 }
4049 }
4050
4051 /**
4052 * Moves the top activity in the input stackId to the pinned stack.
4053 *
4054 * @param stackId Id of stack to move the top activity to pinned stack.
4055 * @param bounds Bounds to use for pinned stack.
4056 *
4057 * @return True if the top activity of the input stack was successfully moved to the pinned
4058 * stack.
4059 */
4060 @Override
4061 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004062 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 "moveTopActivityToPinnedStack()");
4064 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004065 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4067 + "Device doesn't support picture-in-picture mode");
4068 }
4069
4070 long ident = Binder.clearCallingIdentity();
4071 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004072 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 } finally {
4074 Binder.restoreCallingIdentity(ident);
4075 }
4076 }
4077 }
4078
4079 @Override
4080 public boolean isInMultiWindowMode(IBinder token) {
4081 final long origId = Binder.clearCallingIdentity();
4082 try {
4083 synchronized (mGlobalLock) {
4084 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4085 if (r == null) {
4086 return false;
4087 }
4088 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4089 return r.inMultiWindowMode();
4090 }
4091 } finally {
4092 Binder.restoreCallingIdentity(origId);
4093 }
4094 }
4095
4096 @Override
4097 public boolean isInPictureInPictureMode(IBinder token) {
4098 final long origId = Binder.clearCallingIdentity();
4099 try {
4100 synchronized (mGlobalLock) {
4101 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4102 }
4103 } finally {
4104 Binder.restoreCallingIdentity(origId);
4105 }
4106 }
4107
4108 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004109 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4110 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 return false;
4112 }
4113
4114 // If we are animating to fullscreen then we have already dispatched the PIP mode
4115 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004116 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4117 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 }
4119
4120 @Override
4121 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4122 final long origId = Binder.clearCallingIdentity();
4123 try {
4124 synchronized (mGlobalLock) {
4125 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4126 "enterPictureInPictureMode", token, params);
4127
4128 // If the activity is already in picture in picture mode, then just return early
4129 if (isInPictureInPictureMode(r)) {
4130 return true;
4131 }
4132
4133 // Activity supports picture-in-picture, now check that we can enter PiP at this
4134 // point, if it is
4135 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4136 false /* beforeStopping */)) {
4137 return false;
4138 }
4139
4140 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 synchronized (mGlobalLock) {
4142 // Only update the saved args from the args that are set
4143 r.pictureInPictureArgs.copyOnlySet(params);
4144 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4145 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4146 // Adjust the source bounds by the insets for the transition down
4147 final Rect sourceBounds = new Rect(
4148 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004149 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004150 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004151 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004152 stack.setPictureInPictureAspectRatio(aspectRatio);
4153 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004154 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4155 r.info.applicationInfo.uid, r.shortComponentName,
4156 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004157 logPictureInPictureArgs(params);
4158 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 };
4160
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004161 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 // If the keyguard is showing or occluded, then try and dismiss it before
4163 // entering picture-in-picture (this will prompt the user to authenticate if the
4164 // device is currently locked).
4165 dismissKeyguard(token, new KeyguardDismissCallback() {
4166 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004167 public void onDismissSucceeded() {
4168 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 }
4170 }, null /* message */);
4171 } else {
4172 // Enter picture in picture immediately otherwise
4173 enterPipRunnable.run();
4174 }
4175 return true;
4176 }
4177 } finally {
4178 Binder.restoreCallingIdentity(origId);
4179 }
4180 }
4181
4182 @Override
4183 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4184 final long origId = Binder.clearCallingIdentity();
4185 try {
4186 synchronized (mGlobalLock) {
4187 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4188 "setPictureInPictureParams", token, params);
4189
4190 // Only update the saved args from the args that are set
4191 r.pictureInPictureArgs.copyOnlySet(params);
4192 if (r.inPinnedWindowingMode()) {
4193 // If the activity is already in picture-in-picture, update the pinned stack now
4194 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4195 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004196 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 if (!stack.isAnimatingBoundsToFullscreen()) {
4198 stack.setPictureInPictureAspectRatio(
4199 r.pictureInPictureArgs.getAspectRatio());
4200 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4201 }
4202 }
4203 logPictureInPictureArgs(params);
4204 }
4205 } finally {
4206 Binder.restoreCallingIdentity(origId);
4207 }
4208 }
4209
4210 @Override
4211 public int getMaxNumPictureInPictureActions(IBinder token) {
4212 // Currently, this is a static constant, but later, we may change this to be dependent on
4213 // the context of the activity
4214 return 3;
4215 }
4216
4217 private void logPictureInPictureArgs(PictureInPictureParams params) {
4218 if (params.hasSetActions()) {
4219 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4220 params.getActions().size());
4221 }
4222 if (params.hasSetAspectRatio()) {
4223 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4224 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4225 MetricsLogger.action(lm);
4226 }
4227 }
4228
4229 /**
4230 * Checks the state of the system and the activity associated with the given {@param token} to
4231 * verify that picture-in-picture is supported for that activity.
4232 *
4233 * @return the activity record for the given {@param token} if all the checks pass.
4234 */
4235 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4236 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004237 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 throw new IllegalStateException(caller
4239 + ": Device doesn't support picture-in-picture mode.");
4240 }
4241
4242 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4243 if (r == null) {
4244 throw new IllegalStateException(caller
4245 + ": Can't find activity for token=" + token);
4246 }
4247
4248 if (!r.supportsPictureInPicture()) {
4249 throw new IllegalStateException(caller
4250 + ": Current activity does not support picture-in-picture.");
4251 }
4252
4253 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004254 && !mWindowManager.isValidPictureInPictureAspectRatio(
4255 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 final float minAspectRatio = mContext.getResources().getFloat(
4257 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4258 final float maxAspectRatio = mContext.getResources().getFloat(
4259 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4260 throw new IllegalArgumentException(String.format(caller
4261 + ": Aspect ratio is too extreme (must be between %f and %f).",
4262 minAspectRatio, maxAspectRatio));
4263 }
4264
4265 // Truncate the number of actions if necessary
4266 params.truncateActions(getMaxNumPictureInPictureActions(token));
4267
4268 return r;
4269 }
4270
4271 @Override
4272 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 synchronized (mGlobalLock) {
4275 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4276 if (r == null) {
4277 throw new IllegalArgumentException("Activity does not exist; token="
4278 + activityToken);
4279 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004280 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 }
4282 }
4283
4284 @Override
4285 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4286 Rect tempDockedTaskInsetBounds,
4287 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 long ident = Binder.clearCallingIdentity();
4290 try {
4291 synchronized (mGlobalLock) {
4292 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4293 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4294 PRESERVE_WINDOWS);
4295 }
4296 } finally {
4297 Binder.restoreCallingIdentity(ident);
4298 }
4299 }
4300
4301 @Override
4302 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004303 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 final long ident = Binder.clearCallingIdentity();
4305 try {
4306 synchronized (mGlobalLock) {
4307 mStackSupervisor.setSplitScreenResizing(resizing);
4308 }
4309 } finally {
4310 Binder.restoreCallingIdentity(ident);
4311 }
4312 }
4313
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004314 /**
4315 * Check that we have the features required for VR-related API calls, and throw an exception if
4316 * not.
4317 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004318 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004319 if (!mContext.getPackageManager().hasSystemFeature(
4320 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4321 throw new UnsupportedOperationException("VR mode not supported on this device!");
4322 }
4323 }
4324
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 @Override
4326 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328
4329 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4330
4331 ActivityRecord r;
4332 synchronized (mGlobalLock) {
4333 r = ActivityRecord.isInStackLocked(token);
4334 }
4335
4336 if (r == null) {
4337 throw new IllegalArgumentException();
4338 }
4339
4340 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004341 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 VrManagerInternal.NO_ERROR) {
4343 return err;
4344 }
4345
4346 // Clear the binder calling uid since this path may call moveToTask().
4347 final long callingId = Binder.clearCallingIdentity();
4348 try {
4349 synchronized (mGlobalLock) {
4350 r.requestedVrComponent = (enabled) ? packageName : null;
4351
4352 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004353 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004354 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 }
4356 return 0;
4357 }
4358 } finally {
4359 Binder.restoreCallingIdentity(callingId);
4360 }
4361 }
4362
4363 @Override
4364 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4365 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4366 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004367 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4369 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4370 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004371 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 || activity.voiceSession != null) {
4373 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4374 return;
4375 }
4376 if (activity.pendingVoiceInteractionStart) {
4377 Slog.w(TAG, "Pending start of voice interaction already.");
4378 return;
4379 }
4380 activity.pendingVoiceInteractionStart = true;
4381 }
4382 LocalServices.getService(VoiceInteractionManagerInternal.class)
4383 .startLocalVoiceInteraction(callingActivity, options);
4384 }
4385
4386 @Override
4387 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4388 LocalServices.getService(VoiceInteractionManagerInternal.class)
4389 .stopLocalVoiceInteraction(callingActivity);
4390 }
4391
4392 @Override
4393 public boolean supportsLocalVoiceInteraction() {
4394 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4395 .supportsLocalVoiceInteraction();
4396 }
4397
4398 /** Notifies all listeners when the pinned stack animation starts. */
4399 @Override
4400 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004401 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 }
4403
4404 /** Notifies all listeners when the pinned stack animation ends. */
4405 @Override
4406 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004407 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 }
4409
4410 @Override
4411 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 final long ident = Binder.clearCallingIdentity();
4414 try {
4415 synchronized (mGlobalLock) {
4416 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4417 }
4418 } finally {
4419 Binder.restoreCallingIdentity(ident);
4420 }
4421 }
4422
4423 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426
4427 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004428 if (mWindowManager == null) {
4429 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4430 return false;
4431 }
4432
4433 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004435 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 }
4437
Riddle Hsua0022cd2019-09-09 21:12:41 +08004438 mH.sendMessage(PooledLambda.obtainMessage(
4439 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4440 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441
4442 final long origId = Binder.clearCallingIdentity();
4443 try {
4444 if (values != null) {
4445 Settings.System.clearConfiguration(values);
4446 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 UserHandle.USER_NULL, false /* deferResume */,
4449 mTmpUpdateConfigurationResult);
4450 return mTmpUpdateConfigurationResult.changes != 0;
4451 } finally {
4452 Binder.restoreCallingIdentity(origId);
4453 }
4454 }
4455 }
4456
4457 @Override
4458 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4459 CharSequence message) {
4460 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4463 }
4464 final long callingId = Binder.clearCallingIdentity();
4465 try {
4466 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004467 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 }
4469 } finally {
4470 Binder.restoreCallingIdentity(callingId);
4471 }
4472 }
4473
4474 @Override
4475 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 "cancelTaskWindowTransition()");
4478 final long ident = Binder.clearCallingIdentity();
4479 try {
4480 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004481 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 MATCH_TASK_IN_STACKS_ONLY);
4483 if (task == null) {
4484 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4485 return;
4486 }
4487 task.cancelWindowTransition();
4488 }
4489 } finally {
4490 Binder.restoreCallingIdentity(ident);
4491 }
4492 }
4493
4494 @Override
4495 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 final long ident = Binder.clearCallingIdentity();
4498 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004499 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 } finally {
4501 Binder.restoreCallingIdentity(ident);
4502 }
4503 }
4504
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004505 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4506 boolean restoreFromDisk) {
4507 final TaskRecord task;
4508 synchronized (mGlobalLock) {
4509 task = mRootActivityContainer.anyTaskForId(taskId,
4510 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4511 if (task == null) {
4512 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4513 return null;
4514 }
4515 }
4516 // Don't call this while holding the lock as this operation might hit the disk.
4517 return task.getSnapshot(reducedResolution, restoreFromDisk);
4518 }
4519
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 @Override
4521 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4526 + token);
4527 return;
4528 }
4529 final long origId = Binder.clearCallingIdentity();
4530 try {
4531 r.setDisablePreviewScreenshots(disable);
4532 } finally {
4533 Binder.restoreCallingIdentity(origId);
4534 }
4535 }
4536 }
4537
4538 /** Return the user id of the last resumed activity. */
4539 @Override
4540 public @UserIdInt
4541 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004542 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4544 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004545 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004546 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004548 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 }
4550 }
4551
4552 @Override
4553 public void updateLockTaskFeatures(int userId, int flags) {
4554 final int callingUid = Binder.getCallingUid();
4555 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 "updateLockTaskFeatures()");
4558 }
4559 synchronized (mGlobalLock) {
4560 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4561 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004562 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 }
4564 }
4565
4566 @Override
4567 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4568 synchronized (mGlobalLock) {
4569 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4570 if (r == null) {
4571 return;
4572 }
4573 final long origId = Binder.clearCallingIdentity();
4574 try {
4575 r.setShowWhenLocked(showWhenLocked);
4576 } finally {
4577 Binder.restoreCallingIdentity(origId);
4578 }
4579 }
4580 }
4581
4582 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004583 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4584 synchronized (mGlobalLock) {
4585 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4586 if (r == null) {
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
4598 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004599 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4600 synchronized (mGlobalLock) {
4601 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4602 if (r == null) {
4603 return;
4604 }
4605 final long origId = Binder.clearCallingIdentity();
4606 try {
4607 r.setTurnScreenOn(turnScreenOn);
4608 } finally {
4609 Binder.restoreCallingIdentity(origId);
4610 }
4611 }
4612 }
4613
4614 @Override
4615 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004616 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004618 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004619 synchronized (mGlobalLock) {
4620 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4621 if (r == null) {
4622 return;
4623 }
4624 final long origId = Binder.clearCallingIdentity();
4625 try {
4626 r.registerRemoteAnimations(definition);
4627 } finally {
4628 Binder.restoreCallingIdentity(origId);
4629 }
4630 }
4631 }
4632
4633 @Override
4634 public void registerRemoteAnimationForNextActivityStart(String packageName,
4635 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004636 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004638 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 synchronized (mGlobalLock) {
4640 final long origId = Binder.clearCallingIdentity();
4641 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004642 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 packageName, adapter);
4644 } finally {
4645 Binder.restoreCallingIdentity(origId);
4646 }
4647 }
4648 }
4649
Evan Rosky966759f2019-01-15 10:33:58 -08004650 @Override
4651 public void registerRemoteAnimationsForDisplay(int displayId,
4652 RemoteAnimationDefinition definition) {
4653 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4654 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004655 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004656 synchronized (mGlobalLock) {
4657 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4658 if (display == null) {
4659 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4660 return;
4661 }
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
4664 display.mDisplayContent.registerRemoteAnimations(definition);
4665 } finally {
4666 Binder.restoreCallingIdentity(origId);
4667 }
4668 }
4669 }
4670
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4672 @Override
4673 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4674 synchronized (mGlobalLock) {
4675 final long origId = Binder.clearCallingIdentity();
4676 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004677 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004678 } finally {
4679 Binder.restoreCallingIdentity(origId);
4680 }
4681 }
4682 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004683
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004684 @Override
4685 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004686 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004687 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004688 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004689 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004690 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004691 }
4692 }
4693
4694 @Override
4695 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004697 != PERMISSION_GRANTED) {
4698 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4699 + Binder.getCallingPid()
4700 + ", uid=" + Binder.getCallingUid()
4701 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4702 Slog.w(TAG, msg);
4703 throw new SecurityException(msg);
4704 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004705 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004707 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004708 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004709 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 }
4711 }
4712
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004713 @Override
4714 public void stopAppSwitches() {
4715 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4716 synchronized (mGlobalLock) {
4717 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004718 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004719 mDidAppSwitch = false;
4720 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4721 }
4722 }
4723
4724 @Override
4725 public void resumeAppSwitches() {
4726 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4727 synchronized (mGlobalLock) {
4728 // Note that we don't execute any pending app switches... we will
4729 // let those wait until either the timeout, or the next start
4730 // activity request.
4731 mAppSwitchesAllowedTime = 0;
4732 }
4733 }
4734
Ricky Wai906af482019-06-03 17:25:28 +01004735 long getLastStopAppSwitchesTime() {
4736 return mLastStopAppSwitchesTime;
4737 }
4738
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004739 void onStartActivitySetDidAppSwitch() {
4740 if (mDidAppSwitch) {
4741 // This is the second allowed switch since we stopped switches, so now just generally
4742 // allow switches. Use case:
4743 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4744 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4745 // anyone to switch again).
4746 mAppSwitchesAllowedTime = 0;
4747 } else {
4748 mDidAppSwitch = true;
4749 }
4750 }
4751
4752 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004753 boolean shouldDisableNonVrUiLocked() {
4754 return mVrController.shouldDisableNonVrUiLocked();
4755 }
4756
Wale Ogunwale53783742018-09-16 10:21:51 -07004757 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004758 // 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 +00004759 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004760 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004761 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4762 + " to main display for VR");
4763 mRootActivityContainer.moveStackToDisplay(
4764 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004765 }
4766 mH.post(() -> {
4767 if (!mVrController.onVrModeChanged(r)) {
4768 return;
4769 }
4770 synchronized (mGlobalLock) {
4771 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4772 mWindowManager.disableNonVrUi(disableNonVrUi);
4773 if (disableNonVrUi) {
4774 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4775 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004776 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004777 }
4778 }
4779 });
4780 }
4781
Wale Ogunwale53783742018-09-16 10:21:51 -07004782 @Override
4783 public int getPackageScreenCompatMode(String packageName) {
4784 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4785 synchronized (mGlobalLock) {
4786 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4787 }
4788 }
4789
4790 @Override
4791 public void setPackageScreenCompatMode(String packageName, int mode) {
4792 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4793 "setPackageScreenCompatMode");
4794 synchronized (mGlobalLock) {
4795 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4796 }
4797 }
4798
4799 @Override
4800 public boolean getPackageAskScreenCompat(String packageName) {
4801 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4802 synchronized (mGlobalLock) {
4803 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4804 }
4805 }
4806
4807 @Override
4808 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4809 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4810 "setPackageAskScreenCompat");
4811 synchronized (mGlobalLock) {
4812 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4813 }
4814 }
4815
Wale Ogunwale64258362018-10-16 15:13:37 -07004816 public static String relaunchReasonToString(int relaunchReason) {
4817 switch (relaunchReason) {
4818 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4819 return "window_resize";
4820 case RELAUNCH_REASON_FREE_RESIZE:
4821 return "free_resize";
4822 default:
4823 return null;
4824 }
4825 }
4826
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004827 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004828 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004829 }
4830
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004831 /** Pokes the task persister. */
4832 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4833 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4834 }
4835
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004836 boolean isKeyguardLocked() {
4837 return mKeyguardController.isKeyguardLocked();
4838 }
4839
Garfield Tan01548632018-11-27 10:15:48 -08004840 /**
4841 * Clears launch params for the given package.
4842 * @param packageNames the names of the packages of which the launch params are to be cleared
4843 */
4844 @Override
4845 public void clearLaunchParamsForPackages(List<String> packageNames) {
4846 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4847 "clearLaunchParamsForPackages");
4848 synchronized (mGlobalLock) {
4849 for (int i = 0; i < packageNames.size(); ++i) {
4850 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4851 }
4852 }
4853 }
4854
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004855 /**
4856 * Makes the display with the given id a single task instance display. I.e the display can only
4857 * contain one task.
4858 */
4859 @Override
4860 public void setDisplayToSingleTaskInstance(int displayId) {
4861 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4862 "setDisplayToSingleTaskInstance");
4863 final long origId = Binder.clearCallingIdentity();
4864 try {
4865 final ActivityDisplay display =
4866 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4867 if (display != null) {
4868 display.setDisplayToSingleTaskInstance();
4869 }
4870 } finally {
4871 Binder.restoreCallingIdentity(origId);
4872 }
4873 }
4874
Wale Ogunwale31913b52018-10-13 08:29:31 -07004875 void dumpLastANRLocked(PrintWriter pw) {
4876 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4877 if (mLastANRState == null) {
4878 pw.println(" <no ANR has occurred since boot>");
4879 } else {
4880 pw.println(mLastANRState);
4881 }
4882 }
4883
4884 void dumpLastANRTracesLocked(PrintWriter pw) {
4885 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4886
4887 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4888 if (ArrayUtils.isEmpty(files)) {
4889 pw.println(" <no ANR has occurred since boot>");
4890 return;
4891 }
4892 // Find the latest file.
4893 File latest = null;
4894 for (File f : files) {
4895 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4896 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004897 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004898 }
4899 pw.print("File: ");
4900 pw.print(latest.getName());
4901 pw.println();
4902 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4903 String line;
4904 while ((line = in.readLine()) != null) {
4905 pw.println(line);
4906 }
4907 } catch (IOException e) {
4908 pw.print("Unable to read: ");
4909 pw.print(e);
4910 pw.println();
4911 }
4912 }
4913
4914 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4915 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4916 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4917 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4918 }
4919
4920 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4921 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4922 pw.println(header);
4923
Wale Ogunwaled32da472018-11-16 07:19:28 -08004924 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004925 dumpPackage);
4926 boolean needSep = printedAnything;
4927
4928 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004929 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 " ResumedActivity: ");
4931 if (printed) {
4932 printedAnything = true;
4933 needSep = false;
4934 }
4935
4936 if (dumpPackage == null) {
4937 if (needSep) {
4938 pw.println();
4939 }
4940 printedAnything = true;
4941 mStackSupervisor.dump(pw, " ");
4942 }
4943
4944 if (!printedAnything) {
4945 pw.println(" (nothing)");
4946 }
4947 }
4948
4949 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004950 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004951 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004952 pw.println(" ");
4953 }
4954
4955 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4956 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4957 getActivityStartController().dump(pw, "", dumpPackage);
4958 }
4959
4960 /**
4961 * There are three things that cmd can be:
4962 * - a flattened component name that matches an existing activity
4963 * - the cmd arg isn't the flattened component name of an existing activity:
4964 * dump all activity whose component contains the cmd as a substring
4965 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004966 * <p>
4967 * The caller should not hold lock when calling this method because it will wait for the
4968 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004969 *
4970 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4971 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4972 */
4973 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4974 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4975 ArrayList<ActivityRecord> activities;
4976
4977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004978 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004979 dumpFocusedStackOnly);
4980 }
4981
4982 if (activities.size() <= 0) {
4983 return false;
4984 }
4985
4986 String[] newArgs = new String[args.length - opti];
4987 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4988
4989 TaskRecord lastTask = null;
4990 boolean needSep = false;
4991 for (int i = activities.size() - 1; i >= 0; i--) {
4992 ActivityRecord r = activities.get(i);
4993 if (needSep) {
4994 pw.println();
4995 }
4996 needSep = true;
4997 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004998 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 if (lastTask != task) {
5000 lastTask = task;
5001 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005002 pw.print(" id="); pw.print(lastTask.mTaskId);
5003 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 if (dumpAll) {
5005 lastTask.dump(pw, " ");
5006 }
5007 }
5008 }
5009 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5010 }
5011 return true;
5012 }
5013
5014 /**
5015 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5016 * there is a thread associated with the activity.
5017 */
5018 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5019 final ActivityRecord r, String[] args, boolean dumpAll) {
5020 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005021 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 synchronized (mGlobalLock) {
5023 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5024 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5025 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005026 if (r.hasProcess()) {
5027 pw.println(r.app.getPid());
5028 appThread = r.app.getThread();
5029 } else {
5030 pw.println("(not running)");
5031 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005032 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005033 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005034 }
5035 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005036 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005037 // flush anything that is already in the PrintWriter since the thread is going
5038 // to write to the file descriptor directly
5039 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005040 try (TransferPipe tp = new TransferPipe()) {
5041 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5042 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005043 } catch (IOException e) {
5044 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5045 } catch (RemoteException e) {
5046 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5047 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005048 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005049 }
5050
sanryhuang498e77e2018-12-06 14:57:01 +08005051 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5052 boolean testPssMode) {
5053 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5054 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5055 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005056 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005057 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5058 st.toString());
5059 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005060 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5061 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5062 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005063 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5064 testPssMode);
5065 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005066 }
5067
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 int getCurrentUserId() {
5069 return mAmInternal.getCurrentUserId();
5070 }
5071
5072 private void enforceNotIsolatedCaller(String caller) {
5073 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5074 throw new SecurityException("Isolated process not allowed to call " + caller);
5075 }
5076 }
5077
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 public Configuration getConfiguration() {
5079 Configuration ci;
5080 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005081 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005082 ci.userSetLocale = false;
5083 }
5084 return ci;
5085 }
5086
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005087 /**
5088 * Current global configuration information. Contains general settings for the entire system,
5089 * also corresponds to the merged configuration of the default display.
5090 */
5091 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005092 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 }
5094
5095 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5096 boolean initLocale) {
5097 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5098 }
5099
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale, boolean deferResume) {
5102 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5103 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5104 UserHandle.USER_NULL, deferResume);
5105 }
5106
Wale Ogunwale59507092018-10-29 09:00:30 -07005107 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005108 final long origId = Binder.clearCallingIdentity();
5109 try {
5110 synchronized (mGlobalLock) {
5111 updateConfigurationLocked(values, null, false, true, userId,
5112 false /* deferResume */);
5113 }
5114 } finally {
5115 Binder.restoreCallingIdentity(origId);
5116 }
5117 }
5118
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5120 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5121 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5122 deferResume, null /* result */);
5123 }
5124
5125 /**
5126 * Do either or both things: (1) change the current configuration, and (2)
5127 * make sure the given activity is running with the (now) current
5128 * configuration. Returns true if the activity has been left running, or
5129 * false if <var>starting</var> is being destroyed to match the new
5130 * configuration.
5131 *
5132 * @param userId is only used when persistent parameter is set to true to persist configuration
5133 * for that particular user
5134 */
5135 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5136 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5137 ActivityTaskManagerService.UpdateConfigurationResult result) {
5138 int changes = 0;
5139 boolean kept = true;
5140
Riddle Hsua0022cd2019-09-09 21:12:41 +08005141 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142 try {
5143 if (values != null) {
5144 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5145 deferResume);
5146 }
5147
5148 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5149 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005150 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005151 }
5152
5153 if (result != null) {
5154 result.changes = changes;
5155 result.activityRelaunched = !kept;
5156 }
5157 return kept;
5158 }
5159
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005161 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005163
5164 final ActivityDisplay defaultDisplay =
5165 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5166
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005167 mTempConfig.setTo(getGlobalConfiguration());
5168 final int changes = mTempConfig.updateFrom(values);
5169 if (changes == 0) {
5170 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5171 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5172 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5173 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005174 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175 return 0;
5176 }
5177
5178 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5179 "Updating global configuration to: " + values);
5180
5181 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5182 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5183 values.colorMode,
5184 values.densityDpi,
5185 values.fontScale,
5186 values.hardKeyboardHidden,
5187 values.keyboard,
5188 values.keyboardHidden,
5189 values.mcc,
5190 values.mnc,
5191 values.navigation,
5192 values.navigationHidden,
5193 values.orientation,
5194 values.screenHeightDp,
5195 values.screenLayout,
5196 values.screenWidthDp,
5197 values.smallestScreenWidthDp,
5198 values.touchscreen,
5199 values.uiMode);
5200
5201
5202 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5203 final LocaleList locales = values.getLocales();
5204 int bestLocaleIndex = 0;
5205 if (locales.size() > 1) {
5206 if (mSupportedSystemLocales == null) {
5207 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5208 }
5209 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5210 }
5211 SystemProperties.set("persist.sys.locale",
5212 locales.get(bestLocaleIndex).toLanguageTag());
5213 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005214
5215 final Message m = PooledLambda.obtainMessage(
5216 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5217 locales.get(bestLocaleIndex));
5218 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
5220
Yunfan Chen75157d72018-07-27 14:47:21 +09005221 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222
5223 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005224 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5227 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005228 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229
5230 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005231 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232
5233 AttributeCache ac = AttributeCache.instance();
5234 if (ac != null) {
5235 ac.updateConfiguration(mTempConfig);
5236 }
5237
5238 // Make sure all resources in our process are updated right now, so that anyone who is going
5239 // to retrieve resource values after we return will be sure to get the new ones. This is
5240 // especially important during boot, where the first config change needs to guarantee all
5241 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005242 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243
5244 // We need another copy of global config because we're scheduling some calls instead of
5245 // running them in place. We need to be sure that object we send will be handled unchanged.
5246 final Configuration configCopy = new Configuration(mTempConfig);
5247 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005248 final Message msg = PooledLambda.obtainMessage(
5249 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5250 this, userId, configCopy);
5251 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 }
5253
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005254 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5255 for (int i = pidMap.size() - 1; i >= 0; i--) {
5256 final int pid = pidMap.keyAt(i);
5257 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005258 if (DEBUG_CONFIGURATION) {
5259 Slog.v(TAG_CONFIGURATION, "Update process config of "
5260 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005262 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005263 }
5264
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005265 final Message msg = PooledLambda.obtainMessage(
5266 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5267 mAmInternal, changes, initLocale);
5268 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 // Override configuration of the default display duplicates global config, so we need to
5271 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005272 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5273 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 return changes;
5276 }
5277
Riddle Hsua0022cd2019-09-09 21:12:41 +08005278 /** @see WindowSurfacePlacer#deferLayout */
5279 void deferWindowLayout() {
5280 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5281 // Reset the reasons at the first entrance because we only care about the changes in the
5282 // deferred scope.
5283 mLayoutReasons = 0;
5284 }
5285
5286 mWindowManager.mWindowPlacerLocked.deferLayout();
5287 }
5288
5289 /** @see WindowSurfacePlacer#continueLayout */
5290 void continueWindowLayout() {
5291 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5292 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5293 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5294 }
5295 }
5296
5297 /**
5298 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5299 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5300 * defer count is gone.
5301 */
5302 void addWindowLayoutReasons(@LayoutReason int reasons) {
5303 mLayoutReasons |= reasons;
5304 }
5305
Wale Ogunwalef6733932018-06-27 05:14:34 -07005306 private void updateEventDispatchingLocked(boolean booted) {
5307 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5308 }
5309
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005310 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5311 final ContentResolver resolver = mContext.getContentResolver();
5312 Settings.System.putConfigurationForUser(resolver, config, userId);
5313 }
5314
5315 private void sendLocaleToMountDaemonMsg(Locale l) {
5316 try {
5317 IBinder service = ServiceManager.getService("mount");
5318 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5319 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5320 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5321 } catch (RemoteException e) {
5322 Log.e(TAG, "Error storing locale for decryption UI", e);
5323 }
5324 }
5325
Alison Cichowlas3e340502018-08-07 17:15:01 -04005326 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5327 mStartActivitySources.remove(permissionToken);
5328 mExpiredStartAsCallerTokens.add(permissionToken);
5329 }
5330
5331 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5332 mExpiredStartAsCallerTokens.remove(permissionToken);
5333 }
5334
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005335 boolean isActivityStartsLoggingEnabled() {
5336 return mAmInternal.isActivityStartsLoggingEnabled();
5337 }
5338
Michal Karpinski8596ded2018-11-14 14:43:48 +00005339 boolean isBackgroundActivityStartsEnabled() {
5340 return mAmInternal.isBackgroundActivityStartsEnabled();
5341 }
5342
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 void enableScreenAfterBoot(boolean booted) {
5344 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5345 SystemClock.uptimeMillis());
5346 mWindowManager.enableScreenAfterBoot();
5347
5348 synchronized (mGlobalLock) {
5349 updateEventDispatchingLocked(booted);
5350 }
5351 }
5352
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005353 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5354 if (r == null || !r.hasProcess()) {
5355 return KEY_DISPATCHING_TIMEOUT_MS;
5356 }
5357 return getInputDispatchingTimeoutLocked(r.app);
5358 }
5359
5360 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005361 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005362 }
5363
Wale Ogunwalef6733932018-06-27 05:14:34 -07005364 /**
5365 * Decide based on the configuration whether we should show the ANR,
5366 * crash, etc dialogs. The idea is that if there is no affordance to
5367 * press the on-screen buttons, or the user experience would be more
5368 * greatly impacted than the crash itself, we shouldn't show the dialog.
5369 *
5370 * A thought: SystemUI might also want to get told about this, the Power
5371 * dialog / global actions also might want different behaviors.
5372 */
5373 private void updateShouldShowDialogsLocked(Configuration config) {
5374 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5375 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5376 && config.navigation == Configuration.NAVIGATION_NONAV);
5377 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5378 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5379 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5380 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5381 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5382 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5383 HIDE_ERROR_DIALOGS, 0) != 0;
5384 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5385 }
5386
5387 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5388 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5389 FONT_SCALE, 1.0f, userId);
5390
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005391 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 if (getGlobalConfiguration().fontScale == scaleFactor) {
5393 return;
5394 }
5395
5396 final Configuration configuration
5397 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5398 configuration.fontScale = scaleFactor;
5399 updatePersistentConfiguration(configuration, userId);
5400 }
5401 }
5402
5403 // Actually is sleeping or shutting down or whatever else in the future
5404 // is an inactive state.
5405 boolean isSleepingOrShuttingDownLocked() {
5406 return isSleepingLocked() || mShuttingDown;
5407 }
5408
5409 boolean isSleepingLocked() {
5410 return mSleeping;
5411 }
5412
Riddle Hsu16567132018-08-16 21:37:47 +08005413 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005415 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 if (task.isActivityTypeStandard()) {
5417 if (mCurAppTimeTracker != r.appTimeTracker) {
5418 // We are switching app tracking. Complete the current one.
5419 if (mCurAppTimeTracker != null) {
5420 mCurAppTimeTracker.stop();
5421 mH.obtainMessage(
5422 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005423 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005424 mCurAppTimeTracker = null;
5425 }
5426 if (r.appTimeTracker != null) {
5427 mCurAppTimeTracker = r.appTimeTracker;
5428 startTimeTrackingFocusedActivityLocked();
5429 }
5430 } else {
5431 startTimeTrackingFocusedActivityLocked();
5432 }
5433 } else {
5434 r.appTimeTracker = null;
5435 }
5436 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5437 // TODO: Probably not, because we don't want to resume voice on switching
5438 // back to this activity
5439 if (task.voiceInteractor != null) {
5440 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5441 } else {
5442 finishRunningVoiceLocked();
5443
5444 if (mLastResumedActivity != null) {
5445 final IVoiceInteractionSession session;
5446
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005447 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 if (lastResumedActivityTask != null
5449 && lastResumedActivityTask.voiceSession != null) {
5450 session = lastResumedActivityTask.voiceSession;
5451 } else {
5452 session = mLastResumedActivity.voiceSession;
5453 }
5454
5455 if (session != null) {
5456 // We had been in a voice interaction session, but now focused has
5457 // move to something different. Just finish the session, we can't
5458 // return to it and retain the proper state and synchronization with
5459 // the voice interaction service.
5460 finishVoiceTask(session);
5461 }
5462 }
5463 }
5464
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005465 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5466 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005467 }
5468 updateResumedAppTrace(r);
5469 mLastResumedActivity = r;
5470
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005471 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472
5473 applyUpdateLockStateLocked(r);
5474 applyUpdateVrModeLocked(r);
5475
5476 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005477 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 r == null ? "NULL" : r.shortComponentName,
5479 reason);
5480 }
5481
5482 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5483 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005484 final ActivityTaskManagerInternal.SleepToken token =
5485 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 updateSleepIfNeededLocked();
5487 return token;
5488 }
5489 }
5490
5491 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005492 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 final boolean wasSleeping = mSleeping;
5494 boolean updateOomAdj = false;
5495
5496 if (!shouldSleep) {
5497 // If wasSleeping is true, we need to wake up activity manager state from when
5498 // we started sleeping. In either case, we need to apply the sleep tokens, which
5499 // will wake up stacks or put them to sleep as appropriate.
5500 if (wasSleeping) {
5501 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005502 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5503 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005504 startTimeTrackingFocusedActivityLocked();
5505 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005506 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5508 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005509 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005510 if (wasSleeping) {
5511 updateOomAdj = true;
5512 }
5513 } else if (!mSleeping && shouldSleep) {
5514 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005515 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5516 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (mCurAppTimeTracker != null) {
5518 mCurAppTimeTracker.stop();
5519 }
5520 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005521 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 mStackSupervisor.goingToSleepLocked();
5523 updateResumedAppTrace(null /* resumed */);
5524 updateOomAdj = true;
5525 }
5526 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005527 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 }
5529 }
5530
5531 void updateOomAdj() {
5532 mH.post(mAmInternal::updateOomAdj);
5533 }
5534
Wale Ogunwale53783742018-09-16 10:21:51 -07005535 void updateCpuStats() {
5536 mH.post(mAmInternal::updateCpuStats);
5537 }
5538
Hui Yu03d12402018-12-06 18:00:37 -08005539 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5540 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5542 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005543 mH.sendMessage(m);
5544 }
5545
Hui Yu03d12402018-12-06 18:00:37 -08005546 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005547 ComponentName taskRoot = null;
5548 final TaskRecord task = activity.getTaskRecord();
5549 if (task != null) {
5550 final ActivityRecord rootActivity = task.getRootActivity();
5551 if (rootActivity != null) {
5552 taskRoot = rootActivity.mActivityComponent;
5553 }
5554 }
5555
Hui Yu03d12402018-12-06 18:00:37 -08005556 final Message m = PooledLambda.obtainMessage(
5557 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005558 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005559 mH.sendMessage(m);
5560 }
5561
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005562 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5563 String hostingType) {
5564 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005565 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5566 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005567 + activity.processName);
5568 }
5569 // Post message to start process to avoid possible deadlock of calling into AMS with the
5570 // ATMS lock held.
5571 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5572 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5573 isTop, hostingType, activity.intent.getComponent());
5574 mH.sendMessage(m);
5575 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005576 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005577 }
5578 }
5579
Wale Ogunwale53783742018-09-16 10:21:51 -07005580 void setBooting(boolean booting) {
5581 mAmInternal.setBooting(booting);
5582 }
5583
5584 boolean isBooting() {
5585 return mAmInternal.isBooting();
5586 }
5587
5588 void setBooted(boolean booted) {
5589 mAmInternal.setBooted(booted);
5590 }
5591
5592 boolean isBooted() {
5593 return mAmInternal.isBooted();
5594 }
5595
5596 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5597 mH.post(() -> {
5598 if (finishBooting) {
5599 mAmInternal.finishBooting();
5600 }
5601 if (enableScreen) {
5602 mInternal.enableScreenAfterBoot(isBooted());
5603 }
5604 });
5605 }
5606
5607 void setHeavyWeightProcess(ActivityRecord root) {
5608 mHeavyWeightProcess = root.app;
5609 final Message m = PooledLambda.obtainMessage(
5610 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005611 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005612 mH.sendMessage(m);
5613 }
5614
5615 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5616 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5617 return;
5618 }
5619
5620 mHeavyWeightProcess = null;
5621 final Message m = PooledLambda.obtainMessage(
5622 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5623 proc.mUserId);
5624 mH.sendMessage(m);
5625 }
5626
5627 private void cancelHeavyWeightProcessNotification(int userId) {
5628 final INotificationManager inm = NotificationManager.getService();
5629 if (inm == null) {
5630 return;
5631 }
5632 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005633 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005634 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5635 } catch (RuntimeException e) {
5636 Slog.w(TAG, "Error canceling notification for service", e);
5637 } catch (RemoteException e) {
5638 }
5639
5640 }
5641
5642 private void postHeavyWeightProcessNotification(
5643 WindowProcessController proc, Intent intent, int userId) {
5644 if (proc == null) {
5645 return;
5646 }
5647
5648 final INotificationManager inm = NotificationManager.getService();
5649 if (inm == null) {
5650 return;
5651 }
5652
5653 try {
5654 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5655 String text = mContext.getString(R.string.heavy_weight_notification,
5656 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5657 Notification notification =
5658 new Notification.Builder(context,
5659 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5660 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5661 .setWhen(0)
5662 .setOngoing(true)
5663 .setTicker(text)
5664 .setColor(mContext.getColor(
5665 com.android.internal.R.color.system_notification_accent_color))
5666 .setContentTitle(text)
5667 .setContentText(
5668 mContext.getText(R.string.heavy_weight_notification_detail))
5669 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5670 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5671 new UserHandle(userId)))
5672 .build();
5673 try {
5674 inm.enqueueNotificationWithTag("android", "android", null,
5675 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5676 } catch (RuntimeException e) {
5677 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5678 } catch (RemoteException e) {
5679 }
5680 } catch (PackageManager.NameNotFoundException e) {
5681 Slog.w(TAG, "Unable to create context for heavy notification", e);
5682 }
5683
5684 }
5685
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005686 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5687 IBinder token, String resultWho, int requestCode, Intent[] intents,
5688 String[] resolvedTypes, int flags, Bundle bOptions) {
5689
5690 ActivityRecord activity = null;
5691 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5692 activity = ActivityRecord.isInStackLocked(token);
5693 if (activity == null) {
5694 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5695 return null;
5696 }
5697 if (activity.finishing) {
5698 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5699 return null;
5700 }
5701 }
5702
5703 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5704 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5705 bOptions);
5706 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5707 if (noCreate) {
5708 return rec;
5709 }
5710 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5711 if (activity.pendingResults == null) {
5712 activity.pendingResults = new HashSet<>();
5713 }
5714 activity.pendingResults.add(rec.ref);
5715 }
5716 return rec;
5717 }
5718
Andrii Kulian52d255c2018-07-13 11:32:19 -07005719 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005720 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005721 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005722 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5723 mCurAppTimeTracker.start(resumedActivity.packageName);
5724 }
5725 }
5726
5727 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5728 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005729 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005730 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5731 }
5732 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005733 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005734 constructResumedTraceName(resumed.packageName), 0);
5735 }
5736 mTracedResumedActivity = resumed;
5737 }
5738
5739 private String constructResumedTraceName(String packageName) {
5740 return "focused app: " + packageName;
5741 }
5742
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005743 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005744 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005745 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005746 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005747 // mainStack is null during startup.
5748 if (mainStack != null) {
5749 if (changes != 0 && starting == null) {
5750 // If the configuration changed, and the caller is not already
5751 // in the process of starting an activity, then find the top
5752 // activity to check if its configuration needs to change.
5753 starting = mainStack.topRunningActivityLocked();
5754 }
5755
5756 if (starting != null) {
5757 kept = starting.ensureActivityConfiguration(changes,
5758 false /* preserveWindow */);
5759 // And we need to make sure at this point that all other activities
5760 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005761 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005762 !PRESERVE_WINDOWS);
5763 }
5764 }
5765
5766 return kept;
5767 }
5768
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005769 void scheduleAppGcsLocked() {
5770 mH.post(() -> mAmInternal.scheduleAppGcs());
5771 }
5772
Wale Ogunwale53783742018-09-16 10:21:51 -07005773 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5774 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5775 }
5776
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005777 /**
5778 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5779 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5780 * on demand.
5781 */
5782 IPackageManager getPackageManager() {
5783 return AppGlobals.getPackageManager();
5784 }
5785
5786 PackageManagerInternal getPackageManagerInternalLocked() {
5787 if (mPmInternal == null) {
5788 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5789 }
5790 return mPmInternal;
5791 }
5792
Hai Zhangf4da9be2019-05-01 13:46:06 +08005793 PermissionPolicyInternal getPermissionPolicyInternal() {
5794 if (mPermissionPolicyInternal == null) {
5795 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5796 }
5797 return mPermissionPolicyInternal;
5798 }
5799
Wale Ogunwale008163e2018-07-23 23:11:08 -07005800 AppWarnings getAppWarningsLocked() {
5801 return mAppWarnings;
5802 }
5803
Wale Ogunwale214f3482018-10-04 11:00:47 -07005804 Intent getHomeIntent() {
5805 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5806 intent.setComponent(mTopComponent);
5807 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5808 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5809 intent.addCategory(Intent.CATEGORY_HOME);
5810 }
5811 return intent;
5812 }
5813
Chilun2ef71f72018-11-16 17:57:15 +08005814 /**
5815 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5816 * activities.
5817 *
5818 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5819 * component defined in config_secondaryHomeComponent.
5820 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5821 */
5822 Intent getSecondaryHomeIntent(String preferredPackage) {
5823 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005824 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5825 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5826 if (preferredPackage == null || useSystemProvidedLauncher) {
5827 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005828 final String secondaryHomeComponent = mContext.getResources().getString(
5829 com.android.internal.R.string.config_secondaryHomeComponent);
5830 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5831 } else {
5832 intent.setPackage(preferredPackage);
5833 }
5834 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5835 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5836 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5837 }
5838 return intent;
5839 }
5840
Wale Ogunwale214f3482018-10-04 11:00:47 -07005841 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5842 if (info == null) return null;
5843 ApplicationInfo newInfo = new ApplicationInfo(info);
5844 newInfo.initForUser(userId);
5845 return newInfo;
5846 }
5847
Wale Ogunwale9c103022018-10-18 07:44:54 -07005848 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005849 if (uid == SYSTEM_UID) {
5850 // The system gets to run in any process. If there are multiple processes with the same
5851 // uid, just pick the first (this should never happen).
5852 final SparseArray<WindowProcessController> procs =
5853 mProcessNames.getMap().get(processName);
5854 if (procs == null) return null;
5855 final int procCount = procs.size();
5856 for (int i = 0; i < procCount; i++) {
5857 final int procUid = procs.keyAt(i);
5858 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5859 // Don't use an app process or different user process for system component.
5860 continue;
5861 }
5862 return procs.valueAt(i);
5863 }
5864 }
5865
5866 return mProcessNames.get(processName, uid);
5867 }
5868
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005869 WindowProcessController getProcessController(IApplicationThread thread) {
5870 if (thread == null) {
5871 return null;
5872 }
5873
5874 final IBinder threadBinder = thread.asBinder();
5875 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5876 for (int i = pmap.size()-1; i >= 0; i--) {
5877 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5878 for (int j = procs.size() - 1; j >= 0; j--) {
5879 final WindowProcessController proc = procs.valueAt(j);
5880 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5881 return proc;
5882 }
5883 }
5884 }
5885
5886 return null;
5887 }
5888
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005889 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005890 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005891 if (proc == null) return null;
5892 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5893 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005894 }
5895 return null;
5896 }
5897
Riddle Hsua0536432019-02-16 00:38:59 +08005898 int getUidState(int uid) {
5899 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005900 }
5901
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005902 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005903 // A uid is considered to be foreground if it has a visible non-toast window.
5904 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005905 }
5906
Ricky Wai96f5c352019-04-10 18:40:17 +01005907 boolean isDeviceOwner(int uid) {
5908 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005909 }
5910
Ricky Wai96f5c352019-04-10 18:40:17 +01005911 void setDeviceOwnerUid(int uid) {
5912 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005913 }
5914
Wale Ogunwale9de19442018-10-18 19:05:03 -07005915 /**
5916 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5917 * the whitelist
5918 */
5919 String getPendingTempWhitelistTagForUidLocked(int uid) {
5920 return mPendingTempWhitelist.get(uid);
5921 }
5922
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005923 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5924 if (true || Build.IS_USER) {
5925 return;
5926 }
5927
5928 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5929 StrictMode.allowThreadDiskWrites();
5930 try {
5931 File tracesDir = new File("/data/anr");
5932 File tracesFile = null;
5933 try {
5934 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5935
5936 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005937 String timeString =
5938 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5939 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005940 sb.append(": ");
5941 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5942 sb.append(" since ");
5943 sb.append(msg);
5944 FileOutputStream fos = new FileOutputStream(tracesFile);
5945 fos.write(sb.toString().getBytes());
5946 if (app == null) {
5947 fos.write("\n*** No application process!".getBytes());
5948 }
5949 fos.close();
5950 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5951 } catch (IOException e) {
5952 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5953 return;
5954 }
5955
5956 if (app != null && app.getPid() > 0) {
5957 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5958 firstPids.add(app.getPid());
5959 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5960 }
5961
5962 File lastTracesFile = null;
5963 File curTracesFile = null;
5964 for (int i=9; i>=0; i--) {
5965 String name = String.format(Locale.US, "slow%02d.txt", i);
5966 curTracesFile = new File(tracesDir, name);
5967 if (curTracesFile.exists()) {
5968 if (lastTracesFile != null) {
5969 curTracesFile.renameTo(lastTracesFile);
5970 } else {
5971 curTracesFile.delete();
5972 }
5973 }
5974 lastTracesFile = curTracesFile;
5975 }
5976 tracesFile.renameTo(curTracesFile);
5977 } finally {
5978 StrictMode.setThreadPolicy(oldPolicy);
5979 }
5980 }
5981
Michal Karpinskida34cd42019-04-02 19:46:52 +01005982 boolean isAssociatedCompanionApp(int userId, int uid) {
5983 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5984 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005985 return false;
5986 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005987 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005988 }
5989
Issei Suzuki734bc942019-06-05 13:59:52 +02005990 void notifySingleTaskDisplayEmpty(int displayId) {
5991 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5992 }
5993
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005994 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005995 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005996
5997
Wale Ogunwale98875612018-10-12 07:53:02 -07005998 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5999 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006000
Riddle Hsud93a6c42018-11-29 21:50:06 +08006001 H(Looper looper) {
6002 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006003 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006004
6005 @Override
6006 public void handleMessage(Message msg) {
6007 switch (msg.what) {
6008 case REPORT_TIME_TRACKER_MSG: {
6009 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6010 tracker.deliverResult(mContext);
6011 } break;
6012 }
6013 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006014 }
6015
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006016 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006017 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006018
6019 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006020 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006021 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022
6023 @Override
6024 public void handleMessage(Message msg) {
6025 switch (msg.what) {
6026 case DISMISS_DIALOG_UI_MSG: {
6027 final Dialog d = (Dialog) msg.obj;
6028 d.dismiss();
6029 break;
6030 }
6031 }
6032 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006033 }
6034
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006035 final class LocalService extends ActivityTaskManagerInternal {
6036 @Override
6037 public SleepToken acquireSleepToken(String tag, int displayId) {
6038 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006039 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006040 }
6041
6042 @Override
6043 public ComponentName getHomeActivityForUser(int userId) {
6044 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006045 final ActivityRecord homeActivity =
6046 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006047 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006048 }
6049 }
6050
6051 @Override
6052 public void onLocalVoiceInteractionStarted(IBinder activity,
6053 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6054 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006055 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057 }
6058
6059 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006060 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006061 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006062 synchronized (mGlobalLock) {
6063 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006064 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 }
6066 }
6067
6068 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006069 public void notifySingleTaskDisplayDrawn(int displayId) {
6070 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6071 }
6072
6073 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006074 public void notifyAppTransitionFinished() {
6075 synchronized (mGlobalLock) {
6076 mStackSupervisor.notifyAppTransitionDone();
6077 }
6078 }
6079
6080 @Override
6081 public void notifyAppTransitionCancelled() {
6082 synchronized (mGlobalLock) {
6083 mStackSupervisor.notifyAppTransitionDone();
6084 }
6085 }
6086
6087 @Override
6088 public List<IBinder> getTopVisibleActivities() {
6089 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006090 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092 }
6093
6094 @Override
6095 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6096 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006097 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 }
6099 }
6100
6101 @Override
6102 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6103 Bundle bOptions) {
6104 Preconditions.checkNotNull(intents, "intents");
6105 final String[] resolvedTypes = new String[intents.length];
6106
6107 // UID of the package on user userId.
6108 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6109 // packageUid may not be initialized.
6110 int packageUid = 0;
6111 final long ident = Binder.clearCallingIdentity();
6112
6113 try {
6114 for (int i = 0; i < intents.length; i++) {
6115 resolvedTypes[i] =
6116 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6117 }
6118
6119 packageUid = AppGlobals.getPackageManager().getPackageUid(
6120 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6121 } catch (RemoteException e) {
6122 // Shouldn't happen.
6123 } finally {
6124 Binder.restoreCallingIdentity(ident);
6125 }
6126
Riddle Hsu591bf612019-02-14 17:55:31 +08006127 return getActivityStartController().startActivitiesInPackage(
6128 packageUid, packageName,
6129 intents, resolvedTypes, null /* resultTo */,
6130 SafeActivityOptions.fromBundle(bOptions), userId,
6131 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6132 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 }
6134
6135 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006136 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6137 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6138 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6139 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006140 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006141 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006142 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6143 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6144 userId, validateIncomingUser, originatingPendingIntent,
6145 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006146 }
6147 }
6148
6149 @Override
6150 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6151 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6152 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6153 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006154 PendingIntentRecord originatingPendingIntent,
6155 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006156 synchronized (mGlobalLock) {
6157 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6158 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6159 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006160 validateIncomingUser, originatingPendingIntent,
6161 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006162 }
6163 }
6164
6165 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6167 Intent intent, Bundle options, int userId) {
6168 return ActivityTaskManagerService.this.startActivityAsUser(
6169 caller, callerPacakge, intent,
6170 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6171 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6172 false /*validateIncomingUser*/);
6173 }
6174
6175 @Override
lumark588a3e82018-07-20 18:53:54 +08006176 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006177 synchronized (mGlobalLock) {
6178
6179 // We might change the visibilities here, so prepare an empty app transition which
6180 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006181 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006182 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006183 if (activityDisplay == null) {
6184 return;
6185 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006186 final DisplayContent dc = activityDisplay.mDisplayContent;
6187 final boolean wasTransitionSet =
6188 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006190 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006192 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193
6194 // If there was a transition set already we don't want to interfere with it as we
6195 // might be starting it too early.
6196 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006197 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 }
6199 }
6200 if (callback != null) {
6201 callback.run();
6202 }
6203 }
6204
6205 @Override
6206 public void notifyKeyguardTrustedChanged() {
6207 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006208 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006209 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006210 }
6211 }
6212 }
6213
6214 /**
6215 * Called after virtual display Id is updated by
6216 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6217 * {@param vrVr2dDisplayId}.
6218 */
6219 @Override
6220 public void setVr2dDisplayId(int vr2dDisplayId) {
6221 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006223 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006224 }
6225 }
6226
6227 @Override
6228 public void setFocusedActivity(IBinder token) {
6229 synchronized (mGlobalLock) {
6230 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6231 if (r == null) {
6232 throw new IllegalArgumentException(
6233 "setFocusedActivity: No activity record matching token=" + token);
6234 }
Louis Chang19443452018-10-09 12:10:21 +08006235 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006236 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006237 }
6238 }
6239 }
6240
6241 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006243 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006244 }
6245
6246 @Override
6247 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006248 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250
6251 @Override
6252 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006253 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255
6256 @Override
6257 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6258 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6259 }
6260
6261 @Override
6262 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006263 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006264 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006265
6266 @Override
6267 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6268 synchronized (mGlobalLock) {
6269 mActiveVoiceInteractionServiceComponent = component;
6270 }
6271 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006272
6273 @Override
6274 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6275 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6276 return;
6277 }
6278 synchronized (mGlobalLock) {
6279 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6280 if (types == null) {
6281 if (uid < 0) {
6282 return;
6283 }
6284 types = new ArrayMap<>();
6285 mAllowAppSwitchUids.put(userId, types);
6286 }
6287 if (uid < 0) {
6288 types.remove(type);
6289 } else {
6290 types.put(type, uid);
6291 }
6292 }
6293 }
6294
6295 @Override
6296 public void onUserStopped(int userId) {
6297 synchronized (mGlobalLock) {
6298 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6299 mAllowAppSwitchUids.remove(userId);
6300 }
6301 }
6302
6303 @Override
6304 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6305 synchronized (mGlobalLock) {
6306 return ActivityTaskManagerService.this.isGetTasksAllowed(
6307 caller, callingPid, callingUid);
6308 }
6309 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006310
Riddle Hsua0536432019-02-16 00:38:59 +08006311 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006312 @Override
6313 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006314 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006315 mProcessNames.put(proc.mName, proc.mUid, proc);
6316 }
6317 }
6318
Riddle Hsua0536432019-02-16 00:38:59 +08006319 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006320 @Override
6321 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006322 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006323 mProcessNames.remove(name, uid);
6324 }
6325 }
6326
Riddle Hsua0536432019-02-16 00:38:59 +08006327 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006328 @Override
6329 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006330 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006331 if (proc == mHomeProcess) {
6332 mHomeProcess = null;
6333 }
6334 if (proc == mPreviousProcess) {
6335 mPreviousProcess = null;
6336 }
6337 }
6338 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006339
Riddle Hsua0536432019-02-16 00:38:59 +08006340 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006341 @Override
6342 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006343 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006344 return mTopProcessState;
6345 }
6346 }
6347
Riddle Hsua0536432019-02-16 00:38:59 +08006348 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006349 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006350 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006351 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006352 return proc == mHeavyWeightProcess;
6353 }
6354 }
6355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006357 @Override
6358 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006360 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6361 }
6362 }
6363
6364 @Override
6365 public void finishHeavyWeightApp() {
6366 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006367 if (mHeavyWeightProcess != null) {
6368 mHeavyWeightProcess.finishActivities();
6369 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006370 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6371 mHeavyWeightProcess);
6372 }
6373 }
6374
Riddle Hsua0536432019-02-16 00:38:59 +08006375 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006376 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006377 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006378 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006379 return isSleepingLocked();
6380 }
6381 }
6382
6383 @Override
6384 public boolean isShuttingDown() {
6385 synchronized (mGlobalLock) {
6386 return mShuttingDown;
6387 }
6388 }
6389
6390 @Override
6391 public boolean shuttingDown(boolean booted, int timeout) {
6392 synchronized (mGlobalLock) {
6393 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006394 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006396 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006397 return mStackSupervisor.shutdownLocked(timeout);
6398 }
6399 }
6400
6401 @Override
6402 public void enableScreenAfterBoot(boolean booted) {
6403 synchronized (mGlobalLock) {
6404 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6405 SystemClock.uptimeMillis());
6406 mWindowManager.enableScreenAfterBoot();
6407 updateEventDispatchingLocked(booted);
6408 }
6409 }
6410
6411 @Override
6412 public boolean showStrictModeViolationDialog() {
6413 synchronized (mGlobalLock) {
6414 return mShowDialogs && !mSleeping && !mShuttingDown;
6415 }
6416 }
6417
6418 @Override
6419 public void showSystemReadyErrorDialogsIfNeeded() {
6420 synchronized (mGlobalLock) {
6421 try {
6422 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6423 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6424 + " data partition or your device will be unstable.");
6425 mUiHandler.post(() -> {
6426 if (mShowDialogs) {
6427 AlertDialog d = new BaseErrorDialog(mUiContext);
6428 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6429 d.setCancelable(false);
6430 d.setTitle(mUiContext.getText(R.string.android_system_label));
6431 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6432 d.setButton(DialogInterface.BUTTON_POSITIVE,
6433 mUiContext.getText(R.string.ok),
6434 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6435 d.show();
6436 }
6437 });
6438 }
6439 } catch (RemoteException e) {
6440 }
6441
6442 if (!Build.isBuildConsistent()) {
6443 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6444 mUiHandler.post(() -> {
6445 if (mShowDialogs) {
6446 AlertDialog d = new BaseErrorDialog(mUiContext);
6447 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6448 d.setCancelable(false);
6449 d.setTitle(mUiContext.getText(R.string.android_system_label));
6450 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6451 d.setButton(DialogInterface.BUTTON_POSITIVE,
6452 mUiContext.getText(R.string.ok),
6453 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6454 d.show();
6455 }
6456 });
6457 }
6458 }
6459 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006460
6461 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006462 public void onProcessMapped(int pid, WindowProcessController proc) {
6463 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006464 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006465 }
6466 }
6467
6468 @Override
6469 public void onProcessUnMapped(int pid) {
6470 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006471 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006472 }
6473 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006474
6475 @Override
6476 public void onPackageDataCleared(String name) {
6477 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006478 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006479 mAppWarnings.onPackageDataCleared(name);
6480 }
6481 }
6482
6483 @Override
6484 public void onPackageUninstalled(String name) {
6485 synchronized (mGlobalLock) {
6486 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006487 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006488 }
6489 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006490
6491 @Override
6492 public void onPackageAdded(String name, boolean replacing) {
6493 synchronized (mGlobalLock) {
6494 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6495 }
6496 }
6497
6498 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006499 public void onPackageReplaced(ApplicationInfo aInfo) {
6500 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006501 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006502 }
6503 }
6504
6505 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006506 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6507 synchronized (mGlobalLock) {
6508 return compatibilityInfoForPackageLocked(ai);
6509 }
6510 }
6511
Yunfan Chen75157d72018-07-27 14:47:21 +09006512 /**
6513 * Set the corresponding display information for the process global configuration. To be
6514 * called when we need to show IME on a different display.
6515 *
6516 * @param pid The process id associated with the IME window.
6517 * @param displayId The ID of the display showing the IME.
6518 */
6519 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006520 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006521 // Don't update process-level configuration for Multi-Client IME process since other
6522 // IMEs on other displays will also receive this configuration change due to IME
6523 // services use the same application config/context.
6524 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006525
Yunfan Chen75157d72018-07-27 14:47:21 +09006526 if (pid == MY_PID || pid < 0) {
6527 if (DEBUG_CONFIGURATION) {
6528 Slog.w(TAG,
6529 "Trying to update display configuration for system/invalid process.");
6530 }
6531 return;
6532 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006533 synchronized (mGlobalLock) {
6534 final ActivityDisplay activityDisplay =
6535 mRootActivityContainer.getActivityDisplay(displayId);
6536 if (activityDisplay == null) {
6537 // Call might come when display is not yet added or has been removed.
6538 if (DEBUG_CONFIGURATION) {
6539 Slog.w(TAG, "Trying to update display configuration for non-existing "
6540 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006541 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006542 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006543 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006544 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006545 if (process == null) {
6546 if (DEBUG_CONFIGURATION) {
6547 Slog.w(TAG, "Trying to update display configuration for invalid "
6548 + "process, pid=" + pid);
6549 }
6550 return;
6551 }
lumarkddc77fb2019-06-27 22:22:23 +08006552 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006553 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6554 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006555 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006556
6557 @Override
6558 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006559 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006560 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006561 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6562 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006563 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006564 }
6565 }
6566 }
6567
6568 @Override
6569 public void clearPendingResultForActivity(IBinder activityToken,
6570 WeakReference<PendingIntentRecord> pir) {
6571 synchronized (mGlobalLock) {
6572 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6573 if (r != null && r.pendingResults != null) {
6574 r.pendingResults.remove(pir);
6575 }
6576 }
6577 }
6578
6579 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006580 public ActivityTokens getTopActivityForTask(int taskId) {
6581 synchronized (mGlobalLock) {
6582 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6583 if (taskRecord == null) {
6584 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6585 + " Requested task not found");
6586 return null;
6587 }
6588 final ActivityRecord activity = taskRecord.getTopActivity();
6589 if (activity == null) {
6590 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6591 + " Requested activity not found");
6592 return null;
6593 }
6594 if (!activity.attachedToProcess()) {
6595 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6596 + activity);
6597 return null;
6598 }
6599 return new ActivityTokens(activity.appToken, activity.assistToken,
6600 activity.app.getThread());
6601 }
6602 }
6603
6604 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006605 public IIntentSender getIntentSender(int type, String packageName,
6606 int callingUid, int userId, IBinder token, String resultWho,
6607 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6608 Bundle bOptions) {
6609 synchronized (mGlobalLock) {
6610 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6611 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6612 }
6613 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006614
6615 @Override
6616 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6617 synchronized (mGlobalLock) {
6618 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6619 if (r == null) {
6620 return null;
6621 }
6622 if (r.mServiceConnectionsHolder == null) {
6623 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6624 ActivityTaskManagerService.this, r);
6625 }
6626
6627 return r.mServiceConnectionsHolder;
6628 }
6629 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006630
6631 @Override
6632 public Intent getHomeIntent() {
6633 synchronized (mGlobalLock) {
6634 return ActivityTaskManagerService.this.getHomeIntent();
6635 }
6636 }
6637
6638 @Override
6639 public boolean startHomeActivity(int userId, String reason) {
6640 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006641 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006642 }
6643 }
6644
6645 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006646 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006647 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006648 synchronized (mGlobalLock) {
6649 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006650 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006651 }
Chilun8b1f1be2019-03-13 17:14:36 +08006652 }
6653
6654 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006655 public boolean startHomeOnAllDisplays(int userId, String reason) {
6656 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006657 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006658 }
6659 }
6660
Riddle Hsua0536432019-02-16 00:38:59 +08006661 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006662 @Override
6663 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006664 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006665 if (mFactoryTest == FACTORY_TEST_OFF) {
6666 return false;
6667 }
6668 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6669 && wpc.mName.equals(mTopComponent.getPackageName())) {
6670 return true;
6671 }
6672 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6673 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6674 }
6675 }
6676
6677 @Override
6678 public void updateTopComponentForFactoryTest() {
6679 synchronized (mGlobalLock) {
6680 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6681 return;
6682 }
6683 final ResolveInfo ri = mContext.getPackageManager()
6684 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6685 final CharSequence errorMsg;
6686 if (ri != null) {
6687 final ActivityInfo ai = ri.activityInfo;
6688 final ApplicationInfo app = ai.applicationInfo;
6689 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6690 mTopAction = Intent.ACTION_FACTORY_TEST;
6691 mTopData = null;
6692 mTopComponent = new ComponentName(app.packageName, ai.name);
6693 errorMsg = null;
6694 } else {
6695 errorMsg = mContext.getResources().getText(
6696 com.android.internal.R.string.factorytest_not_system);
6697 }
6698 } else {
6699 errorMsg = mContext.getResources().getText(
6700 com.android.internal.R.string.factorytest_no_action);
6701 }
6702 if (errorMsg == null) {
6703 return;
6704 }
6705
6706 mTopAction = null;
6707 mTopData = null;
6708 mTopComponent = null;
6709 mUiHandler.post(() -> {
6710 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6711 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006712 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006713 });
6714 }
6715 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716
Riddle Hsua0536432019-02-16 00:38:59 +08006717 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 @Override
6719 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6720 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006721 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006723 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006724
6725 wpc.clearRecentTasks();
6726 wpc.clearActivities();
6727
6728 if (wpc.isInstrumenting()) {
6729 finishInstrumentationCallback.run();
6730 }
6731
Jorim Jaggid0752812018-10-16 16:07:20 +02006732 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006733 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006734 try {
6735 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6736 // If there was nothing to resume, and we are not already restarting
6737 // this process, but there is a visible activity that is hosted by the
6738 // process...then make sure all visible activities are running, taking
6739 // care of restarting this process.
6740 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6741 !PRESERVE_WINDOWS);
6742 }
6743 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006744 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006745 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 }
6747 }
6748 }
6749
6750 @Override
6751 public void closeSystemDialogs(String reason) {
6752 enforceNotIsolatedCaller("closeSystemDialogs");
6753
6754 final int pid = Binder.getCallingPid();
6755 final int uid = Binder.getCallingUid();
6756 final long origId = Binder.clearCallingIdentity();
6757 try {
6758 synchronized (mGlobalLock) {
6759 // Only allow this from foreground processes, so that background
6760 // applications can't abuse it to prevent system UI from being shown.
6761 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006762 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 if (!proc.isPerceptible()) {
6764 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6765 + " from background process " + proc);
6766 return;
6767 }
6768 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006769 mWindowManager.closeSystemDialogs(reason);
6770
Wale Ogunwaled32da472018-11-16 07:19:28 -08006771 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006773 // Call into AM outside the synchronized block.
6774 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 } finally {
6776 Binder.restoreCallingIdentity(origId);
6777 }
6778 }
6779
6780 @Override
6781 public void cleanupDisabledPackageComponents(
6782 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6783 synchronized (mGlobalLock) {
6784 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006785 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006787 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006788 mStackSupervisor.scheduleIdleLocked();
6789 }
6790
6791 // Clean-up disabled tasks
6792 getRecentTasks().cleanupDisabledPackageTasksLocked(
6793 packageName, disabledClasses, userId);
6794 }
6795 }
6796
6797 @Override
6798 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6799 int userId) {
6800 synchronized (mGlobalLock) {
6801
6802 boolean didSomething =
6803 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006804 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006805 null, doit, evenPersistent, userId);
6806 return didSomething;
6807 }
6808 }
6809
6810 @Override
6811 public void resumeTopActivities(boolean scheduleIdle) {
6812 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006813 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 if (scheduleIdle) {
6815 mStackSupervisor.scheduleIdleLocked();
6816 }
6817 }
6818 }
6819
Riddle Hsua0536432019-02-16 00:38:59 +08006820 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 @Override
6822 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006823 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6825 }
6826 }
6827
Riddle Hsua0536432019-02-16 00:38:59 +08006828 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 @Override
6830 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006831 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006832 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6833 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6834 }
6835 try {
6836 return mRootActivityContainer.attachApplication(wpc);
6837 } finally {
6838 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6839 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 }
6841 }
6842
6843 @Override
6844 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6845 try {
6846 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6847 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6848 }
6849 } catch (RemoteException ex) {
6850 throw new SecurityException("Fail to check is caller a privileged app", ex);
6851 }
6852
6853 synchronized (mGlobalLock) {
6854 final long ident = Binder.clearCallingIdentity();
6855 try {
6856 if (mAmInternal.shouldConfirmCredentials(userId)) {
6857 if (mKeyguardController.isKeyguardLocked()) {
6858 // Showing launcher to avoid user entering credential twice.
6859 startHomeActivity(currentUserId, "notifyLockedProfile");
6860 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006861 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
6863 } finally {
6864 Binder.restoreCallingIdentity(ident);
6865 }
6866 }
6867 }
6868
6869 @Override
6870 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6871 mAmInternal.enforceCallingPermission(
6872 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6873
6874 synchronized (mGlobalLock) {
6875 final long ident = Binder.clearCallingIdentity();
6876 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006877 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6878 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6881 UserHandle.CURRENT);
6882 } finally {
6883 Binder.restoreCallingIdentity(ident);
6884 }
6885 }
6886 }
6887
6888 @Override
6889 public void writeActivitiesToProto(ProtoOutputStream proto) {
6890 synchronized (mGlobalLock) {
6891 // The output proto of "activity --proto activities"
6892 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006893 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006894 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6895 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 }
6897 }
6898
6899 @Override
6900 public void saveANRState(String reason) {
6901 synchronized (mGlobalLock) {
6902 final StringWriter sw = new StringWriter();
6903 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6904 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6905 if (reason != null) {
6906 pw.println(" Reason: " + reason);
6907 }
6908 pw.println();
6909 getActivityStartController().dump(pw, " ", null);
6910 pw.println();
6911 pw.println("-------------------------------------------------------------------------------");
6912 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6913 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6914 "" /* header */);
6915 pw.println();
6916 pw.close();
6917
6918 mLastANRState = sw.toString();
6919 }
6920 }
6921
6922 @Override
6923 public void clearSavedANRState() {
6924 synchronized (mGlobalLock) {
6925 mLastANRState = null;
6926 }
6927 }
6928
6929 @Override
6930 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6931 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6932 synchronized (mGlobalLock) {
6933 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6934 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6935 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6936 dumpLastANRLocked(pw);
6937 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6938 dumpLastANRTracesLocked(pw);
6939 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6940 dumpActivityStarterLocked(pw, dumpPackage);
6941 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6942 dumpActivityContainersLocked(pw);
6943 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6944 if (getRecentTasks() != null) {
6945 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6946 }
6947 }
6948 }
6949 }
6950
6951 @Override
6952 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6953 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6954 int wakefulness) {
6955 synchronized (mGlobalLock) {
6956 if (mHomeProcess != null && (dumpPackage == null
6957 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6958 if (needSep) {
6959 pw.println();
6960 needSep = false;
6961 }
6962 pw.println(" mHomeProcess: " + mHomeProcess);
6963 }
6964 if (mPreviousProcess != null && (dumpPackage == null
6965 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6966 if (needSep) {
6967 pw.println();
6968 needSep = false;
6969 }
6970 pw.println(" mPreviousProcess: " + mPreviousProcess);
6971 }
6972 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6973 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6974 StringBuilder sb = new StringBuilder(128);
6975 sb.append(" mPreviousProcessVisibleTime: ");
6976 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6977 pw.println(sb);
6978 }
6979 if (mHeavyWeightProcess != null && (dumpPackage == null
6980 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6981 if (needSep) {
6982 pw.println();
6983 needSep = false;
6984 }
6985 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6986 }
6987 if (dumpPackage == null) {
6988 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006989 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006990 }
6991 if (dumpAll) {
6992 if (dumpPackage == null) {
6993 pw.println(" mConfigWillChange: "
6994 + getTopDisplayFocusedStack().mConfigWillChange);
6995 }
6996 if (mCompatModePackages.getPackages().size() > 0) {
6997 boolean printed = false;
6998 for (Map.Entry<String, Integer> entry
6999 : mCompatModePackages.getPackages().entrySet()) {
7000 String pkg = entry.getKey();
7001 int mode = entry.getValue();
7002 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7003 continue;
7004 }
7005 if (!printed) {
7006 pw.println(" mScreenCompatPackages:");
7007 printed = true;
7008 }
7009 pw.println(" " + pkg + ": " + mode);
7010 }
7011 }
7012 }
7013
7014 if (dumpPackage == null) {
7015 pw.println(" mWakefulness="
7016 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007017 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007018 if (mRunningVoice != null) {
7019 pw.println(" mRunningVoice=" + mRunningVoice);
7020 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7021 }
7022 pw.println(" mSleeping=" + mSleeping);
7023 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7024 pw.println(" mVrController=" + mVrController);
7025 }
7026 if (mCurAppTimeTracker != null) {
7027 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7028 }
7029 if (mAllowAppSwitchUids.size() > 0) {
7030 boolean printed = false;
7031 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7032 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7033 for (int j = 0; j < types.size(); j++) {
7034 if (dumpPackage == null ||
7035 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7036 if (needSep) {
7037 pw.println();
7038 needSep = false;
7039 }
7040 if (!printed) {
7041 pw.println(" mAllowAppSwitchUids:");
7042 printed = true;
7043 }
7044 pw.print(" User ");
7045 pw.print(mAllowAppSwitchUids.keyAt(i));
7046 pw.print(": Type ");
7047 pw.print(types.keyAt(j));
7048 pw.print(" = ");
7049 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7050 pw.println();
7051 }
7052 }
7053 }
7054 }
7055 if (dumpPackage == null) {
7056 if (mController != null) {
7057 pw.println(" mController=" + mController
7058 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7059 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007060 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7061 pw.println(" mLaunchingActivityWakeLock="
7062 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 }
7064
7065 return needSep;
7066 }
7067 }
7068
7069 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007070 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7071 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 synchronized (mGlobalLock) {
7073 if (dumpPackage == null) {
7074 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7075 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007076 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7077 if (mRunningVoice != null) {
7078 final long vrToken = proto.start(
7079 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7080 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7081 mRunningVoice.toString());
7082 mVoiceWakeLock.writeToProto(
7083 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7084 proto.end(vrToken);
7085 }
7086 mVrController.writeToProto(proto,
7087 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 if (mController != null) {
7089 final long token = proto.start(CONTROLLER);
7090 proto.write(CONTROLLER, mController.toString());
7091 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7092 proto.end(token);
7093 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007094 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7095 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7096 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007097 }
7098
7099 if (mHomeProcess != null && (dumpPackage == null
7100 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007101 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 }
7103
7104 if (mPreviousProcess != null && (dumpPackage == null
7105 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007106 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7108 }
7109
7110 if (mHeavyWeightProcess != null && (dumpPackage == null
7111 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007112 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114
7115 for (Map.Entry<String, Integer> entry
7116 : mCompatModePackages.getPackages().entrySet()) {
7117 String pkg = entry.getKey();
7118 int mode = entry.getValue();
7119 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7120 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7121 proto.write(PACKAGE, pkg);
7122 proto.write(MODE, mode);
7123 proto.end(compatToken);
7124 }
7125 }
7126
7127 if (mCurAppTimeTracker != null) {
7128 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7129 }
7130
7131 }
7132 }
7133
7134 @Override
7135 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7136 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7137 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007138 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7139 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141
7142 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007143 public void dumpForOom(PrintWriter pw) {
7144 synchronized (mGlobalLock) {
7145 pw.println(" mHomeProcess: " + mHomeProcess);
7146 pw.println(" mPreviousProcess: " + mPreviousProcess);
7147 if (mHeavyWeightProcess != null) {
7148 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7149 }
7150 }
7151 }
7152
7153 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 public boolean canGcNow() {
7155 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007156 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 }
7158 }
7159
Riddle Hsua0536432019-02-16 00:38:59 +08007160 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 @Override
7162 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007163 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007164 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 return top != null ? top.app : null;
7166 }
7167 }
7168
Riddle Hsua0536432019-02-16 00:38:59 +08007169 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 @Override
7171 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007172 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007173 if (mRootActivityContainer != null) {
7174 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 }
7176 }
7177 }
7178
7179 @Override
7180 public void scheduleDestroyAllActivities(String reason) {
7181 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007182 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184 }
7185
7186 @Override
7187 public void removeUser(int userId) {
7188 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007189 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 }
7191 }
7192
7193 @Override
7194 public boolean switchUser(int userId, UserState userState) {
7195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007196 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 }
7198 }
7199
7200 @Override
7201 public void onHandleAppCrash(WindowProcessController wpc) {
7202 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007203 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 }
7205 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007206
7207 @Override
7208 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7209 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007210 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007211 }
7212 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007213
Riddle Hsua0536432019-02-16 00:38:59 +08007214 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007215 @Override
7216 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007217 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007218 }
7219
Riddle Hsua0536432019-02-16 00:38:59 +08007220 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007221 @Override
7222 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007223 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007224 }
7225
Riddle Hsua0536432019-02-16 00:38:59 +08007226 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007227 @Override
7228 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007229 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007230 }
7231
Riddle Hsua0536432019-02-16 00:38:59 +08007232 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007233 @Override
7234 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007235 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007236 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007237
7238 @Override
7239 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007240 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007241 mPendingTempWhitelist.put(uid, tag);
7242 }
7243 }
7244
7245 @Override
7246 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007247 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007248 mPendingTempWhitelist.remove(uid);
7249 }
7250 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007251
7252 @Override
7253 public boolean handleAppCrashInActivityController(String processName, int pid,
7254 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7255 Runnable killCrashingAppCallback) {
7256 synchronized (mGlobalLock) {
7257 if (mController == null) {
7258 return false;
7259 }
7260
7261 try {
7262 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7263 stackTrace)) {
7264 killCrashingAppCallback.run();
7265 return true;
7266 }
7267 } catch (RemoteException e) {
7268 mController = null;
7269 Watchdog.getInstance().setActivityController(null);
7270 }
7271 return false;
7272 }
7273 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007274
7275 @Override
7276 public void removeRecentTasksByPackageName(String packageName, int userId) {
7277 synchronized (mGlobalLock) {
7278 mRecentTasks.removeTasksByPackageName(packageName, userId);
7279 }
7280 }
7281
7282 @Override
7283 public void cleanupRecentTasksForUser(int userId) {
7284 synchronized (mGlobalLock) {
7285 mRecentTasks.cleanupLocked(userId);
7286 }
7287 }
7288
7289 @Override
7290 public void loadRecentTasksForUser(int userId) {
7291 synchronized (mGlobalLock) {
7292 mRecentTasks.loadUserRecentsLocked(userId);
7293 }
7294 }
7295
7296 @Override
7297 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7298 synchronized (mGlobalLock) {
7299 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7300 }
7301 }
7302
7303 @Override
7304 public void flushRecentTasks() {
7305 mRecentTasks.flush();
7306 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007307
7308 @Override
7309 public WindowProcessController getHomeProcess() {
7310 synchronized (mGlobalLock) {
7311 return mHomeProcess;
7312 }
7313 }
7314
7315 @Override
7316 public WindowProcessController getPreviousProcess() {
7317 synchronized (mGlobalLock) {
7318 return mPreviousProcess;
7319 }
7320 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007321
7322 @Override
7323 public void clearLockedTasks(String reason) {
7324 synchronized (mGlobalLock) {
7325 getLockTaskController().clearLockedTasks(reason);
7326 }
7327 }
7328
7329 @Override
7330 public void updateUserConfiguration() {
7331 synchronized (mGlobalLock) {
7332 final Configuration configuration = new Configuration(getGlobalConfiguration());
7333 final int currentUserId = mAmInternal.getCurrentUserId();
7334 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7335 configuration, currentUserId, Settings.System.canWrite(mContext));
7336 updateConfigurationLocked(configuration, null /* starting */,
7337 false /* initLocale */, false /* persistent */, currentUserId,
7338 false /* deferResume */);
7339 }
7340 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007341
7342 @Override
7343 public boolean canShowErrorDialogs() {
7344 synchronized (mGlobalLock) {
7345 return mShowDialogs && !mSleeping && !mShuttingDown
7346 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7347 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7348 mAmInternal.getCurrentUserId())
7349 && !(UserManager.isDeviceInDemoMode(mContext)
7350 && mAmInternal.getCurrentUser().isDemo());
7351 }
7352 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007353
7354 @Override
7355 public void setProfileApp(String profileApp) {
7356 synchronized (mGlobalLock) {
7357 mProfileApp = profileApp;
7358 }
7359 }
7360
7361 @Override
7362 public void setProfileProc(WindowProcessController wpc) {
7363 synchronized (mGlobalLock) {
7364 mProfileProc = wpc;
7365 }
7366 }
7367
7368 @Override
7369 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7370 synchronized (mGlobalLock) {
7371 mProfilerInfo = profilerInfo;
7372 }
7373 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007374
7375 @Override
7376 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7377 synchronized (mGlobalLock) {
7378 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7379 }
7380 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007381
7382 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007383 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7384 boolean reducedResolution) {
7385 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7386 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007387 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007388
7389 @Override
7390 public boolean isUidForeground(int uid) {
7391 synchronized (mGlobalLock) {
7392 return ActivityTaskManagerService.this.isUidForeground(uid);
7393 }
7394 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007395
7396 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007397 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007398 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007399 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007400 }
7401 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007402
7403 @Override
7404 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007405 // Translate package names into UIDs
7406 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007407 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007408 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7409 if (uid >= 0) {
7410 result.add(uid);
7411 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007412 }
7413 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007414 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007415 }
7416 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007417 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007418}