blob: bcd5d369ee0c1acd0b93b503f4cb936453640e65 [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;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100198import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700199import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700201import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.SystemClock;
203import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.UserManager;
208import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700209import android.os.storage.IStorageManager;
210import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.provider.Settings;
212import android.service.voice.IVoiceInteractionSession;
213import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900214import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.telecom.TelecomManager;
216import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100217import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700219import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.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;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700292import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700305 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700306 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800376 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
379 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700574 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Ricky Wai96f5c352019-04-10 18:40:17 +0100661 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private final class FontScaleSettingObserver extends ContentObserver {
664 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
665 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
666
667 public FontScaleSettingObserver() {
668 super(mH);
669 final ContentResolver resolver = mContext.getContentResolver();
670 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
671 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
672 UserHandle.USER_ALL);
673 }
674
675 @Override
676 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
677 if (mFontScaleUri.equals(uri)) {
678 updateFontScaleIfNeeded(userId);
679 } else if (mHideErrorDialogsUri.equals(uri)) {
680 synchronized (mGlobalLock) {
681 updateShouldShowDialogsLocked(getGlobalConfiguration());
682 }
683 }
684 }
685 }
686
Riddle Hsua0536432019-02-16 00:38:59 +0800687 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
688 @Target(ElementType.METHOD)
689 @Retention(RetentionPolicy.SOURCE)
690 @interface HotPath {
691 int NONE = 0;
692 int OOM_ADJUSTMENT = 1;
693 int LRU_UPDATE = 2;
694 int PROCESS_CHANGE = 3;
695 int caller() default NONE;
696 }
697
Charles Chen8d98dd22018-12-26 17:36:54 +0800698 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
699 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700700 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700701 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700702 mSystemThread = ActivityThread.currentActivityThread();
703 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700704 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800705 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700706 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700707 }
708
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700709 public void onSystemReady() {
710 synchronized (mGlobalLock) {
711 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
712 PackageManager.FEATURE_CANT_SAVE_STATE);
713 mAssistUtils = new AssistUtils(mContext);
714 mVrController.onSystemReady();
715 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700716 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700718 }
719
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700720 public void onInitPowerManagement() {
721 synchronized (mGlobalLock) {
722 mStackSupervisor.initPowerManagement();
723 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
724 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
725 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
726 mVoiceWakeLock.setReferenceCounted(false);
727 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700731 mFontScaleSettingObserver = new FontScaleSettingObserver();
732 }
733
Wale Ogunwale59507092018-10-29 09:00:30 -0700734 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean freeformWindowManagement =
736 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
737 || Settings.Global.getInt(
738 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
739
740 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
741 final boolean supportsPictureInPicture = supportsMultiWindow &&
742 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
743 final boolean supportsSplitScreenMultiWindow =
744 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
745 final boolean supportsMultiDisplay = mContext.getPackageManager()
746 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
748 final boolean forceResizable = Settings.Global.getInt(
749 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700750 final boolean sizeCompatFreeform = Settings.Global.getInt(
751 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752
753 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900754 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755
756 final Configuration configuration = new Configuration();
757 Settings.System.getConfiguration(resolver, configuration);
758 if (forceRtl) {
759 // This will take care of setting the correct layout direction flags
760 configuration.setLayoutDirection(configuration.locale);
761 }
762
763 synchronized (mGlobalLock) {
764 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700765 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 final boolean multiWindowFormEnabled = freeformWindowManagement
767 || supportsSplitScreenMultiWindow
768 || supportsPictureInPicture
769 || supportsMultiDisplay;
770 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
771 mSupportsMultiWindow = true;
772 mSupportsFreeformWindowManagement = freeformWindowManagement;
773 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
774 mSupportsPictureInPicture = supportsPictureInPicture;
775 mSupportsMultiDisplay = supportsMultiDisplay;
776 } else {
777 mSupportsMultiWindow = false;
778 mSupportsFreeformWindowManagement = false;
779 mSupportsSplitScreenMultiWindow = false;
780 mSupportsPictureInPicture = false;
781 mSupportsMultiDisplay = false;
782 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700783 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700784 // This happens before any activities are started, so we can change global configuration
785 // in-place.
786 updateConfigurationLocked(configuration, null, true);
787 final Configuration globalConfig = getGlobalConfiguration();
788 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
789
790 // Load resources only after the current configuration has been set.
791 final Resources res = mContext.getResources();
792 mThumbnailWidth = res.getDimensionPixelSize(
793 com.android.internal.R.dimen.thumbnail_width);
794 mThumbnailHeight = res.getDimensionPixelSize(
795 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 }
797 }
798
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800799 public WindowManagerGlobalLock getGlobalLock() {
800 return mGlobalLock;
801 }
802
Yunfan Chen585f2932019-01-29 16:04:45 +0900803 /** For test purpose only. */
804 @VisibleForTesting
805 public ActivityTaskManagerInternal getAtmInternal() {
806 return mInternal;
807 }
808
Riddle Hsud93a6c42018-11-29 21:50:06 +0800809 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
810 Looper looper) {
811 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700812 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700814 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800815 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700816 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700817 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818
819 mTempConfig.setToDefaults();
820 mTempConfig.setLocales(LocaleList.getDefault());
821 mConfigurationSeq = mTempConfig.seq = 1;
822 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800823 mRootActivityContainer = new RootActivityContainer(this);
824 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700825
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700827 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700828 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700830 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mKeyguardController = mStackSupervisor.getKeyguardController();
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void onActivityManagerInternalAdded() {
836 synchronized (mGlobalLock) {
837 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
838 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
839 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700840 }
841
Yunfan Chen75157d72018-07-27 14:47:21 +0900842 int increaseConfigurationSeqLocked() {
843 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
844 return mConfigurationSeq;
845 }
846
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700847 protected ActivityStackSupervisor createStackSupervisor() {
848 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
849 supervisor.initialize();
850 return supervisor;
851 }
852
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800853 protected AppWarnings createAppWarnings(
854 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
855 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
856 }
857
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 public void setWindowManager(WindowManagerService wm) {
859 synchronized (mGlobalLock) {
860 mWindowManager = wm;
861 mLockTaskController.setWindowManager(wm);
862 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800863 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700864 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700865 }
866
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700867 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
868 synchronized (mGlobalLock) {
869 mUsageStatsInternal = usageStatsManager;
870 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700871 }
872
Wale Ogunwalef6733932018-06-27 05:14:34 -0700873 UserManagerService getUserManager() {
874 if (mUserManager == null) {
875 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
876 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
877 }
878 return mUserManager;
879 }
880
881 AppOpsService getAppOpsService() {
882 if (mAppOpsService == null) {
883 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
884 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
885 }
886 return mAppOpsService;
887 }
888
889 boolean hasUserRestriction(String restriction, int userId) {
890 return getUserManager().hasUserRestriction(restriction, userId);
891 }
892
Michal Karpinski15486842019-04-25 17:33:42 +0100893 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
894 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700895 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100896 if (mode == AppOpsManager.MODE_DEFAULT) {
897 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
898 == PERMISSION_GRANTED;
899 }
900 return mode == AppOpsManager.MODE_ALLOWED;
901 }
902
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700903 @VisibleForTesting
904 protected void setRecentTasks(RecentTasks recentTasks) {
905 mRecentTasks = recentTasks;
906 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700907 }
908
909 RecentTasks getRecentTasks() {
910 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 ClientLifecycleManager getLifecycleManager() {
914 return mLifecycleManager;
915 }
916
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700917 ActivityStartController getActivityStartController() {
918 return mActivityStartController;
919 }
920
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700921 TaskChangeNotificationController getTaskChangeNotificationController() {
922 return mTaskChangeNotificationController;
923 }
924
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700925 LockTaskController getLockTaskController() {
926 return mLockTaskController;
927 }
928
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 /**
930 * Return the global configuration used by the process corresponding to the input pid. This is
931 * usually the global configuration with some overrides specific to that process.
932 */
933 Configuration getGlobalConfigurationForCallingPid() {
934 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800935 return getGlobalConfigurationForPid(pid);
936 }
937
938 /**
939 * Return the global configuration used by the process corresponding to the given pid.
940 */
941 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 if (pid == MY_PID || pid < 0) {
943 return getGlobalConfiguration();
944 }
945 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100946 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900947 return app != null ? app.getConfiguration() : getGlobalConfiguration();
948 }
949 }
950
951 /**
952 * Return the device configuration info used by the process corresponding to the input pid.
953 * The value is consistent with the global configuration for the process.
954 */
955 @Override
956 public ConfigurationInfo getDeviceConfigurationInfo() {
957 ConfigurationInfo config = new ConfigurationInfo();
958 synchronized (mGlobalLock) {
959 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
960 config.reqTouchScreen = globalConfig.touchscreen;
961 config.reqKeyboardType = globalConfig.keyboard;
962 config.reqNavigation = globalConfig.navigation;
963 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
964 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
965 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
966 }
967 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
968 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
969 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
970 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700971 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900972 }
973 return config;
974 }
975
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700976 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700977 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700978 }
979
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 public static final class Lifecycle extends SystemService {
981 private final ActivityTaskManagerService mService;
982
983 public Lifecycle(Context context) {
984 super(context);
985 mService = new ActivityTaskManagerService(context);
986 }
987
988 @Override
989 public void onStart() {
990 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 }
993
Garfield Tan891146c2018-10-09 12:14:00 -0700994 @Override
995 public void onUnlockUser(int userId) {
996 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800997 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700998 }
999 }
1000
1001 @Override
1002 public void onCleanupUser(int userId) {
1003 synchronized (mService.getGlobalLock()) {
1004 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1005 }
1006 }
1007
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 public ActivityTaskManagerService getService() {
1009 return mService;
1010 }
1011 }
1012
1013 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001014 public final int startActivity(IApplicationThread caller, String callingPackage,
1015 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1016 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1017 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1018 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1019 UserHandle.getCallingUserId());
1020 }
1021
1022 @Override
1023 public final int startActivities(IApplicationThread caller, String callingPackage,
1024 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1025 int userId) {
1026 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 enforceNotIsolatedCaller(reason);
1028 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001030 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1031 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1032 reason, null /* originatingPendingIntent */,
1033 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 }
1035
1036 @Override
1037 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1040 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1041 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1042 true /*validateIncomingUser*/);
1043 }
1044
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001045 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1047 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1048 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001049 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001051 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1053
1054 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001055 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 .setCaller(caller)
1057 .setCallingPackage(callingPackage)
1058 .setResolvedType(resolvedType)
1059 .setResultTo(resultTo)
1060 .setResultWho(resultWho)
1061 .setRequestCode(requestCode)
1062 .setStartFlags(startFlags)
1063 .setProfilerInfo(profilerInfo)
1064 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001065 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .execute();
1067
1068 }
1069
1070 @Override
1071 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1072 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001073 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1074 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 // Refuse possible leaked file descriptors
1076 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1077 throw new IllegalArgumentException("File descriptors passed in Intent");
1078 }
1079
1080 if (!(target instanceof PendingIntentRecord)) {
1081 throw new IllegalArgumentException("Bad PendingIntent object");
1082 }
1083
1084 PendingIntentRecord pir = (PendingIntentRecord)target;
1085
1086 synchronized (mGlobalLock) {
1087 // If this is coming from the currently resumed activity, it is
1088 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001089 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 if (stack.mResumedActivity != null &&
1091 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001092 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001093 }
1094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001095 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 }
1098
1099 @Override
1100 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1101 Bundle bOptions) {
1102 // Refuse possible leaked file descriptors
1103 if (intent != null && intent.hasFileDescriptors()) {
1104 throw new IllegalArgumentException("File descriptors passed in Intent");
1105 }
1106 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1107
1108 synchronized (mGlobalLock) {
1109 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1110 if (r == null) {
1111 SafeActivityOptions.abort(options);
1112 return false;
1113 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001114 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 // The caller is not running... d'oh!
1116 SafeActivityOptions.abort(options);
1117 return false;
1118 }
1119 intent = new Intent(intent);
1120 // The caller is not allowed to change the data.
1121 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1122 // And we are resetting to find the next component...
1123 intent.setComponent(null);
1124
1125 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1126
1127 ActivityInfo aInfo = null;
1128 try {
1129 List<ResolveInfo> resolves =
1130 AppGlobals.getPackageManager().queryIntentActivities(
1131 intent, r.resolvedType,
1132 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1133 UserHandle.getCallingUserId()).getList();
1134
1135 // Look for the original activity in the list...
1136 final int N = resolves != null ? resolves.size() : 0;
1137 for (int i=0; i<N; i++) {
1138 ResolveInfo rInfo = resolves.get(i);
1139 if (rInfo.activityInfo.packageName.equals(r.packageName)
1140 && rInfo.activityInfo.name.equals(r.info.name)) {
1141 // We found the current one... the next matching is
1142 // after it.
1143 i++;
1144 if (i<N) {
1145 aInfo = resolves.get(i).activityInfo;
1146 }
1147 if (debug) {
1148 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1149 + "/" + r.info.name);
1150 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1151 ? "null" : aInfo.packageName + "/" + aInfo.name));
1152 }
1153 break;
1154 }
1155 }
1156 } catch (RemoteException e) {
1157 }
1158
1159 if (aInfo == null) {
1160 // Nobody who is next!
1161 SafeActivityOptions.abort(options);
1162 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1163 return false;
1164 }
1165
1166 intent.setComponent(new ComponentName(
1167 aInfo.applicationInfo.packageName, aInfo.name));
1168 intent.setFlags(intent.getFlags()&~(
1169 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1170 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1171 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1172 FLAG_ACTIVITY_NEW_TASK));
1173
1174 // Okay now we need to start the new activity, replacing the currently running activity.
1175 // This is a little tricky because we want to start the new one as if the current one is
1176 // finished, but not finish the current one first so that there is no flicker.
1177 // And thus...
1178 final boolean wasFinishing = r.finishing;
1179 r.finishing = true;
1180
1181 // Propagate reply information over to the new activity.
1182 final ActivityRecord resultTo = r.resultTo;
1183 final String resultWho = r.resultWho;
1184 final int requestCode = r.requestCode;
1185 r.resultTo = null;
1186 if (resultTo != null) {
1187 resultTo.removeResultsLocked(r, resultWho, requestCode);
1188 }
1189
1190 final long origId = Binder.clearCallingIdentity();
1191 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001192 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001193 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001194 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001195 .setResolvedType(r.resolvedType)
1196 .setActivityInfo(aInfo)
1197 .setResultTo(resultTo != null ? resultTo.appToken : null)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setCallingPid(-1)
1201 .setCallingUid(r.launchedFromUid)
1202 .setCallingPackage(r.launchedFromPackage)
1203 .setRealCallingPid(-1)
1204 .setRealCallingUid(r.launchedFromUid)
1205 .setActivityOptions(options)
1206 .execute();
1207 Binder.restoreCallingIdentity(origId);
1208
1209 r.finishing = wasFinishing;
1210 if (res != ActivityManager.START_SUCCESS) {
1211 return false;
1212 }
1213 return true;
1214 }
1215 }
1216
1217 @Override
1218 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1219 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1220 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1221 final WaitResult res = new WaitResult();
1222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001223 enforceNotIsolatedCaller("startActivityAndWait");
1224 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1225 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001227 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setCaller(caller)
1229 .setCallingPackage(callingPackage)
1230 .setResolvedType(resolvedType)
1231 .setResultTo(resultTo)
1232 .setResultWho(resultWho)
1233 .setRequestCode(requestCode)
1234 .setStartFlags(startFlags)
1235 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001236 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setProfilerInfo(profilerInfo)
1238 .setWaitResult(res)
1239 .execute();
1240 }
1241 return res;
1242 }
1243
1244 @Override
1245 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1246 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1247 int startFlags, Configuration config, Bundle bOptions, int userId) {
1248 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001249 enforceNotIsolatedCaller("startActivityWithConfig");
1250 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1251 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001252 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001253 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001254 .setCaller(caller)
1255 .setCallingPackage(callingPackage)
1256 .setResolvedType(resolvedType)
1257 .setResultTo(resultTo)
1258 .setResultWho(resultWho)
1259 .setRequestCode(requestCode)
1260 .setStartFlags(startFlags)
1261 .setGlobalConfiguration(config)
1262 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001263 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 .execute();
1265 }
1266 }
1267
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
1269 @Override
1270 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1271 int callingUid = Binder.getCallingUid();
1272 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1273 throw new SecurityException("Only the system process can request a permission token, "
1274 + "received request from uid: " + callingUid);
1275 }
1276 IBinder permissionToken = new Binder();
1277 synchronized (mGlobalLock) {
1278 mStartActivitySources.put(permissionToken, delegatorToken);
1279 }
1280
1281 Message expireMsg = PooledLambda.obtainMessage(
1282 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1283 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1284
1285 Message forgetMsg = PooledLambda.obtainMessage(
1286 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1287 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1288
1289 return permissionToken;
1290 }
1291
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 @Override
1293 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1294 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1296 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001298 // permission grants) as any app that may launch one of your own activities. So we only
1299 // allow this in two cases:
1300 // 1) The caller is an activity that is part of the core framework, and then only when it
1301 // is running as the system.
1302 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1303 // can only be requested by a system activity, which may then delegate this call to
1304 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 final ActivityRecord sourceRecord;
1306 final int targetUid;
1307 final String targetPackage;
1308 final boolean isResolver;
1309 synchronized (mGlobalLock) {
1310 if (resultTo == null) {
1311 throw new SecurityException("Must be called from an activity");
1312 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001313 final IBinder sourceToken;
1314 if (permissionToken != null) {
1315 // To even attempt to use a permissionToken, an app must also have this signature
1316 // permission.
1317 mAmInternal.enforceCallingPermission(
1318 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1319 "startActivityAsCaller");
1320 // If called with a permissionToken, we want the sourceRecord from the delegator
1321 // activity that requested this token.
1322 sourceToken = mStartActivitySources.remove(permissionToken);
1323 if (sourceToken == null) {
1324 // Invalid permissionToken, check if it recently expired.
1325 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1326 throw new SecurityException("Called with expired permission token: "
1327 + permissionToken);
1328 } else {
1329 throw new SecurityException("Called with invalid permission token: "
1330 + permissionToken);
1331 }
1332 }
1333 } else {
1334 // This method was called directly by the source.
1335 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337
Wale Ogunwaled32da472018-11-16 07:19:28 -08001338 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339 if (sourceRecord == null) {
1340 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 }
1342 if (sourceRecord.app == null) {
1343 throw new SecurityException("Called without a process attached to activity");
1344 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345
1346 // Whether called directly or from a delegate, the source activity must be from the
1347 // android package.
1348 if (!sourceRecord.info.packageName.equals("android")) {
1349 throw new SecurityException("Must be called from an activity that is "
1350 + "declared in the android package");
1351 }
1352
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001353 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 // This is still okay, as long as this activity is running under the
1355 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001356 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001358 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 + " must be system uid or original calling uid "
1360 + sourceRecord.launchedFromUid);
1361 }
1362 }
1363 if (ignoreTargetSecurity) {
1364 if (intent.getComponent() == null) {
1365 throw new SecurityException(
1366 "Component must be specified with ignoreTargetSecurity");
1367 }
1368 if (intent.getSelector() != null) {
1369 throw new SecurityException(
1370 "Selector not allowed with ignoreTargetSecurity");
1371 }
1372 }
1373 targetUid = sourceRecord.launchedFromUid;
1374 targetPackage = sourceRecord.launchedFromPackage;
1375 isResolver = sourceRecord.isResolverOrChildActivity();
1376 }
1377
1378 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001379 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 }
1381
1382 // TODO: Switch to user app stacks here.
1383 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001384 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 .setCallingUid(targetUid)
1386 .setCallingPackage(targetPackage)
1387 .setResolvedType(resolvedType)
1388 .setResultTo(resultTo)
1389 .setResultWho(resultWho)
1390 .setRequestCode(requestCode)
1391 .setStartFlags(startFlags)
1392 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001393 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1395 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001396 // The target may well be in the background, which would normally prevent it
1397 // from starting an activity. Here we definitely want the start to succeed.
1398 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .execute();
1400 } catch (SecurityException e) {
1401 // XXX need to figure out how to propagate to original app.
1402 // A SecurityException here is generally actually a fault of the original
1403 // calling activity (such as a fairly granting permissions), so propagate it
1404 // back to them.
1405 /*
1406 StringBuilder msg = new StringBuilder();
1407 msg.append("While launching");
1408 msg.append(intent.toString());
1409 msg.append(": ");
1410 msg.append(e.getMessage());
1411 */
1412 throw e;
1413 }
1414 }
1415
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1417 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1418 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1419 }
1420
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 @Override
1422 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1423 Intent intent, String resolvedType, IVoiceInteractionSession session,
1424 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1425 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001426 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 if (session == null || interactor == null) {
1428 throw new NullPointerException("null session or interactor");
1429 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001432 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 .setCallingUid(callingUid)
1434 .setCallingPackage(callingPackage)
1435 .setResolvedType(resolvedType)
1436 .setVoiceSession(session)
1437 .setVoiceInteractor(interactor)
1438 .setStartFlags(startFlags)
1439 .setProfilerInfo(profilerInfo)
1440 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001441 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
1446 @Override
1447 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1448 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1450 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001452 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .setCallingUid(callingUid)
1454 .setCallingPackage(callingPackage)
1455 .setResolvedType(resolvedType)
1456 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001457 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001458 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .execute();
1460 }
1461
Riddle Hsu609a8e22019-06-27 16:46:29 -06001462 /**
1463 * Start the recents activity to perform the recents animation.
1464 *
1465 * @param intent The intent to start the recents activity.
1466 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1467 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1470 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001473 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001477 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1478 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480
1481 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001484 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001485 if (recentsAnimationRunner == null) {
1486 anim.preloadRecentsActivity();
1487 } else {
1488 anim.startRecentsActivity(recentsAnimationRunner);
1489 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490 }
1491 } finally {
1492 Binder.restoreCallingIdentity(origId);
1493 }
1494 }
1495
1496 @Override
1497 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 "startActivityFromRecents()");
1500
1501 final int callingPid = Binder.getCallingPid();
1502 final int callingUid = Binder.getCallingUid();
1503 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1504 final long origId = Binder.clearCallingIdentity();
1505 try {
1506 synchronized (mGlobalLock) {
1507 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1508 safeOptions);
1509 }
1510 } finally {
1511 Binder.restoreCallingIdentity(origId);
1512 }
1513 }
1514
1515 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001516 * Public API to check if the client is allowed to start an activity on specified display.
1517 *
1518 * If the target display is private or virtual, some restrictions will apply.
1519 *
1520 * @param displayId Target display id.
1521 * @param intent Intent used to launch the activity.
1522 * @param resolvedType The MIME type of the intent.
1523 * @param userId The id of the user for whom the call is made.
1524 * @return {@code true} if a call to start an activity on the target display should succeed and
1525 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1526 */
1527 @Override
1528 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1529 String resolvedType, int userId) {
1530 final int callingUid = Binder.getCallingUid();
1531 final int callingPid = Binder.getCallingPid();
1532 final long origId = Binder.clearCallingIdentity();
1533
1534 try {
1535 // Collect information about the target of the Intent.
1536 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1537 0 /* startFlags */, null /* profilerInfo */, userId,
1538 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1539 UserHandle.USER_NULL));
1540 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1541
1542 synchronized (mGlobalLock) {
1543 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1544 aInfo);
1545 }
1546 } finally {
1547 Binder.restoreCallingIdentity(origId);
1548 }
1549 }
1550
1551 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 * This is the internal entry point for handling Activity.finish().
1553 *
1554 * @param token The Binder token referencing the Activity we want to finish.
1555 * @param resultCode Result code, if any, from this Activity.
1556 * @param resultData Result data (Intent), if any, from this Activity.
1557 * @param finishTask Whether to finish the task associated with this Activity.
1558 *
1559 * @return Returns true if the activity successfully finished, or false if it is still running.
1560 */
1561 @Override
1562 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1563 int finishTask) {
1564 // Refuse possible leaked file descriptors
1565 if (resultData != null && resultData.hasFileDescriptors()) {
1566 throw new IllegalArgumentException("File descriptors passed in Intent");
1567 }
1568
1569 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (r == null) {
1572 return true;
1573 }
1574 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001575 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (rootR == null) {
1578 Slog.w(TAG, "Finishing task with all activities already finished");
1579 }
1580 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1581 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001582 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 return false;
1584 }
1585
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001586 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1587 // We should consolidate.
1588 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001590 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (next != null) {
1592 // ask watcher if this is allowed
1593 boolean resumeOK = true;
1594 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001597 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 Watchdog.getInstance().setActivityController(null);
1599 }
1600
1601 if (!resumeOK) {
1602 Slog.i(TAG, "Not finishing activity because controller resumed");
1603 return false;
1604 }
1605 }
1606 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001607
1608 // note down that the process has finished an activity and is in background activity
1609 // starts grace period
1610 if (r.app != null) {
1611 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1612 }
1613
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001615 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 try {
1617 boolean res;
1618 final boolean finishWithRootActivity =
1619 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1620 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1621 || (finishWithRootActivity && r == rootR)) {
1622 // If requested, remove the task that is associated to this activity only if it
1623 // was the root activity in the task. The result code and data is ignored
1624 // because we don't support returning them across task boundaries. Also, to
1625 // keep backwards compatibility we remove the task from recents when finishing
1626 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001627 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 finishWithRootActivity, "finish-activity");
1629 if (!res) {
1630 Slog.i(TAG, "Removing task failed to finish activity");
1631 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001632 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001633 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001635 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001636 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 if (!res) {
1638 Slog.i(TAG, "Failed to finish by app-request");
1639 }
1640 }
1641 return res;
1642 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001643 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 Binder.restoreCallingIdentity(origId);
1645 }
1646 }
1647 }
1648
1649 @Override
1650 public boolean finishActivityAffinity(IBinder token) {
1651 synchronized (mGlobalLock) {
1652 final long origId = Binder.clearCallingIdentity();
1653 try {
1654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r == null) {
1656 return false;
1657 }
1658
1659 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1660 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001661 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 return false;
1663 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001664 r.finishActivityAffinity();
1665 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 } finally {
1667 Binder.restoreCallingIdentity(origId);
1668 }
1669 }
1670 }
1671
1672 @Override
1673 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1674 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001675 try {
1676 WindowProcessController proc = null;
1677 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001678 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001679 ActivityStack stack = ActivityRecord.getStackLocked(token);
1680 if (stack == null) {
1681 return;
1682 }
1683 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1684 false /* fromTimeout */, false /* processPausingActivities */, config);
1685 if (r != null) {
1686 proc = r.app;
1687 }
1688 if (stopProfiling && proc != null) {
1689 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 }
1691 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001692 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001693 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001694 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 }
1697
1698 @Override
1699 public final void activityResumed(IBinder token) {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 }
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001708 public final void activityTopResumedStateLost() {
1709 final long origId = Binder.clearCallingIdentity();
1710 synchronized (mGlobalLock) {
1711 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1712 }
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 public final void activityPaused(IBinder token) {
1718 final long origId = Binder.clearCallingIdentity();
1719 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001720 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 ActivityStack stack = ActivityRecord.getStackLocked(token);
1722 if (stack != null) {
1723 stack.activityPausedLocked(token, false);
1724 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001725 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 }
1727 Binder.restoreCallingIdentity(origId);
1728 }
1729
1730 @Override
1731 public final void activityStopped(IBinder token, Bundle icicle,
1732 PersistableBundle persistentState, CharSequence description) {
1733 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1734
1735 // Refuse possible leaked file descriptors
1736 if (icicle != null && icicle.hasFileDescriptors()) {
1737 throw new IllegalArgumentException("File descriptors passed in Bundle");
1738 }
1739
1740 final long origId = Binder.clearCallingIdentity();
1741
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001742 String restartingName = null;
1743 int restartingUid = 0;
1744 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001746 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001747 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001749 if (r.attachedToProcess()
1750 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1751 // The activity was requested to restart from
1752 // {@link #restartActivityProcessIfVisible}.
1753 restartingName = r.app.mName;
1754 restartingUid = r.app.mUid;
1755 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 r.activityStoppedLocked(icicle, persistentState, description);
1757 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 }
1760
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001761 if (restartingName != null) {
1762 // In order to let the foreground activity can be restarted with its saved state from
1763 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1764 // until the activity reports stopped with the state. And the activity record will be
1765 // kept because the record state is restarting, then the activity will be restarted
1766 // immediately if it is still the top one.
1767 mStackSupervisor.removeRestartTimeouts(r);
1768 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1769 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001770 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771
1772 Binder.restoreCallingIdentity(origId);
1773 }
1774
1775 @Override
1776 public final void activityDestroyed(IBinder token) {
1777 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1778 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001779 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001781 try {
1782 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1783 if (activity != null) {
1784 activity.destroyed("activityDestroyed");
1785 }
1786 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001787 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001788 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
1790 }
1791 }
1792
1793 @Override
1794 public final void activityRelaunched(IBinder token) {
1795 final long origId = Binder.clearCallingIdentity();
1796 synchronized (mGlobalLock) {
1797 mStackSupervisor.activityRelaunchedLocked(token);
1798 }
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801
1802 public final void activitySlept(IBinder token) {
1803 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1804
1805 final long origId = Binder.clearCallingIdentity();
1806
1807 synchronized (mGlobalLock) {
1808 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1809 if (r != null) {
1810 mStackSupervisor.activitySleptLocked(r);
1811 }
1812 }
1813
1814 Binder.restoreCallingIdentity(origId);
1815 }
1816
1817 @Override
1818 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1819 synchronized (mGlobalLock) {
1820 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r == null) {
1822 return;
1823 }
1824 final long origId = Binder.clearCallingIdentity();
1825 try {
1826 r.setRequestedOrientation(requestedOrientation);
1827 } finally {
1828 Binder.restoreCallingIdentity(origId);
1829 }
1830 }
1831 }
1832
1833 @Override
1834 public int getRequestedOrientation(IBinder token) {
1835 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001836 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1837 return (r != null)
1838 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
1840 }
1841
1842 @Override
1843 public void setImmersive(IBinder token, boolean immersive) {
1844 synchronized (mGlobalLock) {
1845 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1846 if (r == null) {
1847 throw new IllegalArgumentException();
1848 }
1849 r.immersive = immersive;
1850
1851 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001852 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001854 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 }
1856 }
1857 }
1858
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 void applyUpdateLockStateLocked(ActivityRecord r) {
1860 // Modifications to the UpdateLock state are done on our handler, outside
1861 // the activity manager's locks. The new state is determined based on the
1862 // state *now* of the relevant activity record. The object is passed to
1863 // the handler solely for logging detail, not to be consulted/modified.
1864 final boolean nextState = r != null && r.immersive;
1865 mH.post(() -> {
1866 if (mUpdateLock.isHeld() != nextState) {
1867 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1868 "Applying new update lock state '" + nextState + "' for " + r);
1869 if (nextState) {
1870 mUpdateLock.acquire();
1871 } else {
1872 mUpdateLock.release();
1873 }
1874 }
1875 });
1876 }
1877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 @Override
1879 public boolean isImmersive(IBinder token) {
1880 synchronized (mGlobalLock) {
1881 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 throw new IllegalArgumentException();
1884 }
1885 return r.immersive;
1886 }
1887 }
1888
1889 @Override
1890 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001893 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 return (r != null) ? r.immersive : false;
1895 }
1896 }
1897
1898 @Override
1899 public void overridePendingTransition(IBinder token, String packageName,
1900 int enterAnim, int exitAnim) {
1901 synchronized (mGlobalLock) {
1902 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1903 if (self == null) {
1904 return;
1905 }
1906
1907 final long origId = Binder.clearCallingIdentity();
1908
1909 if (self.isState(
1910 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001911 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001912 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914
1915 Binder.restoreCallingIdentity(origId);
1916 }
1917 }
1918
1919 @Override
1920 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001921 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001923 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 if (r == null) {
1925 return ActivityManager.COMPAT_MODE_UNKNOWN;
1926 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001927 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930
1931 @Override
1932 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001937 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001938 if (r == null) {
1939 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1940 return;
1941 }
1942 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001943 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 }
1945 }
1946
1947 @Override
1948 public int getLaunchedFromUid(IBinder activityToken) {
1949 ActivityRecord srec;
1950 synchronized (mGlobalLock) {
1951 srec = ActivityRecord.forTokenLocked(activityToken);
1952 }
1953 if (srec == null) {
1954 return -1;
1955 }
1956 return srec.launchedFromUid;
1957 }
1958
1959 @Override
1960 public String getLaunchedFromPackage(IBinder activityToken) {
1961 ActivityRecord srec;
1962 synchronized (mGlobalLock) {
1963 srec = ActivityRecord.forTokenLocked(activityToken);
1964 }
1965 if (srec == null) {
1966 return null;
1967 }
1968 return srec.launchedFromPackage;
1969 }
1970
1971 @Override
1972 public boolean convertFromTranslucent(IBinder token) {
1973 final long origId = Binder.clearCallingIdentity();
1974 try {
1975 synchronized (mGlobalLock) {
1976 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1977 if (r == null) {
1978 return false;
1979 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001980 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(origId);
1984 }
1985 }
1986
1987 @Override
1988 public boolean convertToTranslucent(IBinder token, Bundle options) {
1989 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1990 final long origId = Binder.clearCallingIdentity();
1991 try {
1992 synchronized (mGlobalLock) {
1993 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1994 if (r == null) {
1995 return false;
1996 }
Louis Changcdec0802019-11-11 11:45:07 +08001997 final Task task = r.getTask();
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001998 int index = task.mChildren.lastIndexOf(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002000 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2002 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002003 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 }
2005 } finally {
2006 Binder.restoreCallingIdentity(origId);
2007 }
2008 }
2009
2010 @Override
2011 public void notifyActivityDrawn(IBinder token) {
2012 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002016 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 }
2018 }
2019 }
2020
2021 @Override
2022 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2023 synchronized (mGlobalLock) {
2024 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2025 if (r == null) {
2026 return;
2027 }
2028 r.reportFullyDrawnLocked(restoredFromBundle);
2029 }
2030 }
2031
2032 @Override
2033 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2034 synchronized (mGlobalLock) {
2035 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2036 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2037 return stack.mDisplayId;
2038 }
2039 return DEFAULT_DISPLAY;
2040 }
2041 }
2042
2043 @Override
2044 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 long ident = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002049 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 return null;
2054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(ident);
2057 }
2058 }
2059
2060 @Override
2061 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2064 final long callingId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002067 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (stack == null) {
2069 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2070 return;
2071 }
2072 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002074 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002089 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002090 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (task == null) {
2092 return;
2093 }
2094 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002095 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002096 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002105 public void restartActivityProcessIfVisible(IBinder activityToken) {
2106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2111 if (r == null) {
2112 return;
2113 }
2114 r.restartProcessIfVisible();
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(callingId);
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
2127 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2128 "remove-task");
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133 }
2134
2135 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002136 public void removeAllVisibleRecentTasks() {
2137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002141 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002142 } finally {
2143 Binder.restoreCallingIdentity(ident);
2144 }
2145 }
2146 }
2147
2148 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2150 synchronized (mGlobalLock) {
2151 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2152 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002153 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2161 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002163 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2165 if (r != null) {
2166 return r.getActivityStack().navigateUpToLocked(
2167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002199 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
2201 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002217 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002240 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2242 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246 return null;
2247 }
2248
2249 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2252 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2253 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2254 return;
2255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Louis Changcdec0802019-11-11 11:45:07 +08002260 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 if (task == null) {
2263 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2264 return;
2265 }
2266
2267 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2268 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2269
2270 if (!task.isActivityTypeStandardOrUndefined()) {
2271 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2272 + " non-standard task " + taskId + " to windowing mode="
2273 + windowingMode);
2274 }
2275
2276 final ActivityStack stack = task.getStack();
2277 if (toTop) {
2278 stack.moveToFront("setTaskWindowingMode", task);
2279 }
2280 stack.setWindowingMode(windowingMode);
2281 } finally {
2282 Binder.restoreCallingIdentity(ident);
2283 }
2284 }
2285 }
2286
2287 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 ActivityRecord r = getCallingRecordLocked(token);
2291 return r != null ? r.info.packageName : null;
2292 }
2293 }
2294
2295 @Override
2296 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 ActivityRecord r = getCallingRecordLocked(token);
2299 return r != null ? r.intent.getComponent() : null;
2300 }
2301 }
2302
2303 private ActivityRecord getCallingRecordLocked(IBinder token) {
2304 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2305 if (r == null) {
2306 return null;
2307 }
2308 return r.resultTo;
2309 }
2310
2311 @Override
2312 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314
2315 synchronized (mGlobalLock) {
2316 final long origId = Binder.clearCallingIdentity();
2317 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002318 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 } finally {
2320 Binder.restoreCallingIdentity(origId);
2321 }
2322 }
2323 }
2324
Mark Renouf446251d2019-04-26 10:22:41 -04002325 @Override
2326 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2327 synchronized (mGlobalLock) {
2328 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2329 if (r == null) {
2330 return;
2331 }
2332 ActivityStack stack = r.getActivityStack();
2333 if (stack != null && stack.isSingleTaskInstance()) {
2334 // Single-task stacks are used for activities which are presented in floating
2335 // windows above full screen activities. Instead of directly finishing the
2336 // task, a task change listener is used to notify SystemUI so the action can be
2337 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002338 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002339 mTaskChangeNotificationController
2340 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2341 } else {
2342 try {
2343 callback.requestFinish();
2344 } catch (RemoteException e) {
2345 Slog.e(TAG, "Failed to invoke request finish callback", e);
2346 }
2347 }
2348 }
2349 }
2350
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 /**
2352 * TODO: Add mController hook
2353 */
2354 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2356 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358
2359 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2360 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2362 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 }
2364 }
2365
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2367 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002369
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002372 if (!isSameApp(callingUid, callingPackage)) {
2373 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2374 + Binder.getCallingPid() + " as package " + callingPackage;
2375 Slog.w(TAG, msg);
2376 throw new SecurityException(msg);
2377 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 SafeActivityOptions.abort(options);
2380 return;
2381 }
2382 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 WindowProcessController callerApp = null;
2384 if (appThread != null) {
2385 callerApp = getProcessController(appThread);
2386 }
2387 final ActivityStarter starter = getActivityStartController().obtainStarter(
2388 null /* intent */, "moveTaskToFront");
2389 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2390 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002391 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 return;
2393 }
2394 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 try {
Louis Changcdec0802019-11-11 11:45:07 +08002396 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 if (task == null) {
2398 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002402 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002404 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 return;
2406 }
2407 ActivityOptions realOptions = options != null
2408 ? options.getOptions(mStackSupervisor)
2409 : null;
2410 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2411 false /* forceNonResizable */);
2412
Wale Ogunwale21e06482019-11-18 05:14:15 -08002413 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 if (topActivity != null) {
2415
2416 // We are reshowing a task, use a starting window to hide the initial draw delay
2417 // so the transition can start earlier.
2418 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2419 true /* taskSwitch */, fromRecents);
2420 }
2421 } finally {
2422 Binder.restoreCallingIdentity(origId);
2423 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 }
2425
Ricky Waiaca8a772019-04-04 16:01:06 +01002426 /**
2427 * Return true if callingUid is system, or packageName belongs to that callingUid.
2428 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002429 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002430 try {
2431 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2432 if (packageName == null) {
2433 return false;
2434 }
2435 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2436 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2437 UserHandle.getUserId(callingUid));
2438 return UserHandle.isSameApp(callingUid, uid);
2439 }
2440 } catch (RemoteException e) {
2441 // Should not happen
2442 }
2443 return true;
2444 }
2445
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002446 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2447 int callingPid, int callingUid, String name) {
2448 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2449 return true;
2450 }
2451
2452 if (getRecentTasks().isCallerRecents(sourceUid)) {
2453 return true;
2454 }
2455
2456 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2457 if (perm == PackageManager.PERMISSION_GRANTED) {
2458 return true;
2459 }
2460 if (checkAllowAppSwitchUid(sourceUid)) {
2461 return true;
2462 }
2463
2464 // If the actual IPC caller is different from the logical source, then
2465 // also see if they are allowed to control app switches.
2466 if (callingUid != -1 && callingUid != sourceUid) {
2467 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2468 if (perm == PackageManager.PERMISSION_GRANTED) {
2469 return true;
2470 }
2471 if (checkAllowAppSwitchUid(callingUid)) {
2472 return true;
2473 }
2474 }
2475
2476 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2477 return false;
2478 }
2479
2480 private boolean checkAllowAppSwitchUid(int uid) {
2481 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2482 if (types != null) {
2483 for (int i = types.size() - 1; i >= 0; i--) {
2484 if (types.valueAt(i).intValue() == uid) {
2485 return true;
2486 }
2487 }
2488 }
2489 return false;
2490 }
2491
2492 @Override
2493 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2494 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2495 "setActivityController()");
2496 synchronized (mGlobalLock) {
2497 mController = controller;
2498 mControllerIsAMonkey = imAMonkey;
2499 Watchdog.getInstance().setActivityController(controller);
2500 }
2501 }
2502
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002503 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 synchronized (mGlobalLock) {
2505 return mController != null && mControllerIsAMonkey;
2506 }
2507 }
2508
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 @Override
2510 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2511 synchronized (mGlobalLock) {
2512 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2513 }
2514 }
2515
2516 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2518 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2519 }
2520
2521 @Override
2522 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2523 @WindowConfiguration.ActivityType int ignoreActivityType,
2524 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2525 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002526 final int callingPid = Binder.getCallingPid();
2527 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002528 final int[] profileIds = getUserManager().getProfileIds(
2529 UserHandle.getUserId(callingUid), true);
2530 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2531 for (int i = 0; i < profileIds.length; i++) {
2532 callingProfileIds.add(profileIds[i]);
2533 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002534 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2535
2536 synchronized (mGlobalLock) {
2537 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2538
Nicholas Sauer0259e532019-08-30 08:24:55 -07002539 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002540 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002541 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 }
2543
2544 return list;
2545 }
2546
2547 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2549 synchronized (mGlobalLock) {
2550 final long origId = Binder.clearCallingIdentity();
2551 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2552 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002553 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 }
2555 Binder.restoreCallingIdentity(origId);
2556 }
2557 }
2558
2559 @Override
2560 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 ActivityStack stack = ActivityRecord.getStackLocked(token);
2563 if (stack != null) {
2564 return stack.willActivityBeVisibleLocked(token);
2565 }
2566 return false;
2567 }
2568 }
2569
2570 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 synchronized (mGlobalLock) {
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
Louis Changcdec0802019-11-11 11:45:07 +08002576 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 if (task == null) {
2578 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2579 return;
2580 }
2581
2582 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2583 + " to stackId=" + stackId + " toTop=" + toTop);
2584
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (stack == null) {
2587 throw new IllegalStateException(
2588 "moveTaskToStack: No stack for stackId=" + stackId);
2589 }
2590 if (!stack.isActivityTypeStandardOrUndefined()) {
2591 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2592 + taskId + " to stack " + stackId);
2593 }
2594 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002595 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2597 }
2598 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2599 "moveTaskToStack");
2600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
2603 }
2604 }
2605
2606 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002607 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2608 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609
2610 final long ident = Binder.clearCallingIdentity();
2611 try {
2612 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002613 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2614 if (stack == null) {
2615 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2616 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002618 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2619 throw new IllegalArgumentException("Stack: " + stackId
2620 + " doesn't support animated resize.");
2621 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002622 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002623 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 }
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 }
2629
wilsonshih5c4cf522019-01-25 09:03:47 +08002630 @Override
2631 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2632 int animationDuration) {
2633 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2634
2635 final long ident = Binder.clearCallingIdentity();
2636 try {
2637 synchronized (mGlobalLock) {
2638 if (xOffset == 0 && yOffset == 0) {
2639 return;
2640 }
2641 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2642 if (stack == null) {
2643 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2644 return;
2645 }
2646 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2647 throw new IllegalArgumentException("Stack: " + stackId
2648 + " doesn't support animated resize.");
2649 }
2650 final Rect destBounds = new Rect();
2651 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002652 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002653 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2654 return;
2655 }
2656 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002657 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002658 animationDuration, false /* fromFullscreen */);
2659 }
2660 } finally {
2661 Binder.restoreCallingIdentity(ident);
2662 }
2663 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 /**
2665 * Moves the specified task to the primary-split-screen stack.
2666 *
2667 * @param taskId Id of task to move.
2668 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2669 * exist already. See
2670 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2671 * and
2672 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2673 * @param toTop If the task and stack should be moved to the top.
2674 * @param animate Whether we should play an animation for the moving the task.
2675 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2676 * stack. Pass {@code null} to use default bounds.
2677 * @param showRecents If the recents activity should be shown on the other side of the task
2678 * going into split-screen mode.
2679 */
2680 @Override
2681 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2682 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002683 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 "setTaskWindowingModeSplitScreenPrimary()");
2685 synchronized (mGlobalLock) {
2686 final long ident = Binder.clearCallingIdentity();
2687 try {
Louis Changcdec0802019-11-11 11:45:07 +08002688 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002689 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 if (task == null) {
2691 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2692 return false;
2693 }
2694 if (DEBUG_STACK) Slog.d(TAG_STACK,
2695 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2696 + " to createMode=" + createMode + " toTop=" + toTop);
2697 if (!task.isActivityTypeStandardOrUndefined()) {
2698 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2699 + " non-standard task " + taskId + " to split-screen windowing mode");
2700 }
2701
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002702 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 final int windowingMode = task.getWindowingMode();
2704 final ActivityStack stack = task.getStack();
2705 if (toTop) {
2706 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2707 }
2708 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002709 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2710 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 return windowingMode != task.getWindowingMode();
2712 } finally {
2713 Binder.restoreCallingIdentity(ident);
2714 }
2715 }
2716 }
2717
2718 /**
2719 * Removes stacks in the input windowing modes from the system if they are of activity type
2720 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2721 */
2722 @Override
2723 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 "removeStacksInWindowingModes()");
2726
2727 synchronized (mGlobalLock) {
2728 final long ident = Binder.clearCallingIdentity();
2729 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002730 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
2736
2737 @Override
2738 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002739 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 "removeStacksWithActivityTypes()");
2741
2742 synchronized (mGlobalLock) {
2743 final long ident = Binder.clearCallingIdentity();
2744 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002745 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 } finally {
2747 Binder.restoreCallingIdentity(ident);
2748 }
2749 }
2750 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751
2752 @Override
2753 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2754 int userId) {
2755 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2757 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 final boolean detailed = checkGetTasksPermission(
2760 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2761 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 == PackageManager.PERMISSION_GRANTED;
2763
2764 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002765 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 callingUid);
2767 }
2768 }
2769
2770 @Override
2771 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 long ident = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002776 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 }
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782
2783 @Override
2784 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002785 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 long ident = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002789 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 } finally {
2792 Binder.restoreCallingIdentity(ident);
2793 }
2794 }
2795
2796 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002797 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2798 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2799 long ident = Binder.clearCallingIdentity();
2800 try {
2801 synchronized (mGlobalLock) {
2802 return mRootActivityContainer.getAllStackInfos(displayId);
2803 }
2804 } finally {
2805 Binder.restoreCallingIdentity(ident);
2806 }
2807 }
2808
2809 @Override
2810 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2811 int displayId) {
2812 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2813 long ident = Binder.clearCallingIdentity();
2814 try {
2815 synchronized (mGlobalLock) {
2816 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2817 }
2818 } finally {
2819 Binder.restoreCallingIdentity(ident);
2820 }
2821 }
2822
2823 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002825 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 final long callingUid = Binder.getCallingUid();
2827 final long origId = Binder.clearCallingIdentity();
2828 try {
2829 synchronized (mGlobalLock) {
2830 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002831 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2833 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2834 }
2835 } finally {
2836 Binder.restoreCallingIdentity(origId);
2837 }
2838 }
2839
2840 @Override
2841 public void startLockTaskModeByToken(IBinder token) {
2842 synchronized (mGlobalLock) {
2843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2844 if (r == null) {
2845 return;
2846 }
Louis Changcdec0802019-11-11 11:45:07 +08002847 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 }
2849 }
2850
2851 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002852 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 // This makes inner call to look as if it was initiated by system.
2855 long ident = Binder.clearCallingIdentity();
2856 try {
2857 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002858 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002859 MATCH_TASK_IN_STACKS_ONLY);
2860 if (task == null) {
2861 return;
2862 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863
2864 // When starting lock task mode the stack must be in front and focused
2865 task.getStack().moveToFront("startSystemLockTaskMode");
2866 startLockTaskModeLocked(task, true /* isSystemCaller */);
2867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override
2874 public void stopLockTaskModeByToken(IBinder token) {
2875 synchronized (mGlobalLock) {
2876 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2877 if (r == null) {
2878 return;
2879 }
Louis Changcdec0802019-11-11 11:45:07 +08002880 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 }
2882 }
2883
2884 /**
2885 * This API should be called by SystemUI only when user perform certain action to dismiss
2886 * lock task mode. We should only dismiss pinned lock task mode in this case.
2887 */
2888 @Override
2889 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002890 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2892 }
2893
Louis Changcdec0802019-11-11 11:45:07 +08002894 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2896 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2897 return;
2898 }
2899
Wale Ogunwaled32da472018-11-16 07:19:28 -08002900 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 if (stack == null || task != stack.topTask()) {
2902 throw new IllegalArgumentException("Invalid task, not in foreground");
2903 }
2904
2905 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2906 // system or a specific app.
2907 // * System-initiated requests will only start the pinned mode (screen pinning)
2908 // * App-initiated requests
2909 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2910 // - will start the pinned mode, otherwise
2911 final int callingUid = Binder.getCallingUid();
2912 long ident = Binder.clearCallingIdentity();
2913 try {
2914 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002915 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002917 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
Louis Changcdec0802019-11-11 11:45:07 +08002923 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 final int callingUid = Binder.getCallingUid();
2925 long ident = Binder.clearCallingIdentity();
2926 try {
2927 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002928 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 }
2930 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2931 // task and jumping straight into a call in the case of emergency call back.
2932 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2933 if (tm != null) {
2934 tm.showInCallScreen(false);
2935 }
2936 } finally {
2937 Binder.restoreCallingIdentity(ident);
2938 }
2939 }
2940
2941 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002942 public void updateLockTaskPackages(int userId, String[] packages) {
2943 final int callingUid = Binder.getCallingUid();
2944 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2945 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2946 "updateLockTaskPackages()");
2947 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002948 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002949 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2950 + Arrays.toString(packages));
2951 getLockTaskController().updateLockTaskPackages(userId, packages);
2952 }
2953 }
2954
2955 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 public boolean isInLockTaskMode() {
2957 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2958 }
2959
2960 @Override
2961 public int getLockTaskModeState() {
2962 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002963 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965 }
2966
2967 @Override
2968 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2969 synchronized (mGlobalLock) {
2970 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2971 if (r != null) {
2972 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002973 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 }
2976 }
2977 }
2978
2979 @Override
2980 public Bundle getActivityOptions(IBinder token) {
2981 final long origId = Binder.clearCallingIdentity();
2982 try {
2983 synchronized (mGlobalLock) {
2984 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2985 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002986 final ActivityOptions activityOptions = r.takeOptionsLocked(
2987 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 return activityOptions == null ? null : activityOptions.toBundle();
2989 }
2990 return null;
2991 }
2992 } finally {
2993 Binder.restoreCallingIdentity(origId);
2994 }
2995 }
2996
2997 @Override
2998 public List<IBinder> getAppTasks(String callingPackage) {
2999 int callingUid = Binder.getCallingUid();
3000 long ident = Binder.clearCallingIdentity();
3001 try {
3002 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003003 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005 } finally {
3006 Binder.restoreCallingIdentity(ident);
3007 }
3008 }
3009
3010 @Override
3011 public void finishVoiceTask(IVoiceInteractionSession session) {
3012 synchronized (mGlobalLock) {
3013 final long origId = Binder.clearCallingIdentity();
3014 try {
3015 // TODO: VI Consider treating local voice interactions and voice tasks
3016 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003017 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 } finally {
3019 Binder.restoreCallingIdentity(origId);
3020 }
3021 }
3022
3023 }
3024
3025 @Override
3026 public boolean isTopOfTask(IBinder token) {
3027 synchronized (mGlobalLock) {
3028 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003029 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 }
3031 }
3032
3033 @Override
3034 public void notifyLaunchTaskBehindComplete(IBinder token) {
3035 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3036 }
3037
3038 @Override
3039 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003040 mH.post(() -> {
3041 synchronized (mGlobalLock) {
3042 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003043 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003044 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003045 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003046 } catch (RemoteException e) {
3047 }
3048 }
3049 }
3050
3051 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 }
3053
3054 /** Called from an app when assist data is ready. */
3055 @Override
3056 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3057 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003058 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 synchronized (pae) {
3060 pae.result = extras;
3061 pae.structure = structure;
3062 pae.content = content;
3063 if (referrer != null) {
3064 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3065 }
3066 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003067 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003068 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003069 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 structure.setHomeActivity(pae.isHome);
3071 }
3072 pae.haveResult = true;
3073 pae.notifyAll();
3074 if (pae.intent == null && pae.receiver == null) {
3075 // Caller is just waiting for the result.
3076 return;
3077 }
3078 }
3079 // We are now ready to launch the assist activity.
3080 IAssistDataReceiver sendReceiver = null;
3081 Bundle sendBundle = null;
3082 synchronized (mGlobalLock) {
3083 buildAssistBundleLocked(pae, extras);
3084 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003085 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 if (!exists) {
3087 // Timed out.
3088 return;
3089 }
3090
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 // Caller wants result sent back to them.
3093 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003094 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003095 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003096 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3097 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3099 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3100 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3101 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3102 }
3103 }
3104 if (sendReceiver != null) {
3105 try {
3106 sendReceiver.onHandleAssistData(sendBundle);
3107 } catch (RemoteException e) {
3108 }
3109 return;
3110 }
3111
3112 final long ident = Binder.clearCallingIdentity();
3113 try {
3114 if (TextUtils.equals(pae.intent.getAction(),
3115 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003116 // Start voice interaction through VoiceInteractionManagerService.
3117 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3118 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 } else {
3120 pae.intent.replaceExtras(pae.extras);
3121 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3122 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3123 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003124 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125
3126 try {
3127 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3128 } catch (ActivityNotFoundException e) {
3129 Slog.w(TAG, "No activity to handle assist action.", e);
3130 }
3131 }
3132 } finally {
3133 Binder.restoreCallingIdentity(ident);
3134 }
3135 }
3136
3137 @Override
3138 public int addAppTask(IBinder activityToken, Intent intent,
3139 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3140 final int callingUid = Binder.getCallingUid();
3141 final long callingIdent = Binder.clearCallingIdentity();
3142
3143 try {
3144 synchronized (mGlobalLock) {
3145 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3146 if (r == null) {
3147 throw new IllegalArgumentException("Activity does not exist; token="
3148 + activityToken);
3149 }
3150 ComponentName comp = intent.getComponent();
3151 if (comp == null) {
3152 throw new IllegalArgumentException("Intent " + intent
3153 + " must specify explicit component");
3154 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003155 if (thumbnail.getWidth() != mThumbnailWidth
3156 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 throw new IllegalArgumentException("Bad thumbnail size: got "
3158 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003159 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 }
3161 if (intent.getSelector() != null) {
3162 intent.setSelector(null);
3163 }
3164 if (intent.getSourceBounds() != null) {
3165 intent.setSourceBounds(null);
3166 }
3167 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3168 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3169 // The caller has added this as an auto-remove task... that makes no
3170 // sense, so turn off auto-remove.
3171 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3172 }
3173 }
3174 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3175 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3176 if (ainfo.applicationInfo.uid != callingUid) {
3177 throw new SecurityException(
3178 "Can't add task for another application: target uid="
3179 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3180 }
3181
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003182 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003183 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003184 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003186 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003188 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 return INVALID_TASK_ID;
3190 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003191 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192
3193 // TODO: Send the thumbnail to WM to store it.
3194
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003195 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 } finally {
3198 Binder.restoreCallingIdentity(callingIdent);
3199 }
3200 }
3201
3202 @Override
3203 public Point getAppTaskThumbnailSize() {
3204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 }
3207 }
3208
3209 @Override
3210 public void setTaskResizeable(int taskId, int resizeableMode) {
3211 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003212 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3214 if (task == null) {
3215 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3216 return;
3217 }
3218 task.setResizeMode(resizeableMode);
3219 }
3220 }
3221
3222 @Override
3223 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003224 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 long ident = Binder.clearCallingIdentity();
3226 try {
3227 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003228 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003229 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 if (task == null) {
3231 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3232 return;
3233 }
3234 // Place the task in the right stack if it isn't there already based on
3235 // the requested bounds.
3236 // The stack transition logic is:
3237 // - a null bounds on a freeform task moves that task to fullscreen
3238 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3239 // that task to freeform
3240 // - otherwise the task is not moved
3241 ActivityStack stack = task.getStack();
3242 if (!task.getWindowConfiguration().canResizeTask()) {
3243 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3244 }
3245 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3246 stack = stack.getDisplay().getOrCreateStack(
3247 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3248 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3249 stack = stack.getDisplay().getOrCreateStack(
3250 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3251 }
3252
3253 // Reparent the task to the right stack if necessary
3254 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3255 if (stack != task.getStack()) {
3256 // Defer resume until the task is resized below
3257 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3258 DEFER_RESUME, "resizeTask");
3259 preserveWindow = false;
3260 }
3261
3262 // After reparenting (which only resizes the task to the stack bounds), resize the
3263 // task to the actual bounds provided
3264 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3265 }
3266 } finally {
3267 Binder.restoreCallingIdentity(ident);
3268 }
3269 }
3270
Evan Roskyddedfd42019-10-04 13:38:38 -07003271 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3272 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003273 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003274 throw new RuntimeException("Invalid token in task transaction");
3275 }
3276 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3277 // masks here.
3278 int configMask = change.getConfigSetMask();
3279 int windowMask = change.getWindowSetMask();
3280 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3281 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3282 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3283 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3284 c.setTo(change.getConfiguration(), configMask, windowMask);
3285 container.onRequestedOverrideConfigurationChanged(c);
3286 }
3287
3288 @Override
3289 public void applyContainerTransaction(WindowContainerTransaction t) {
3290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3291 long ident = Binder.clearCallingIdentity();
3292 try {
3293 if (t == null) {
3294 return;
3295 }
3296 synchronized (mGlobalLock) {
3297 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3298 t.getChanges().entrySet().iterator();
3299 while (entries.hasNext()) {
3300 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3301 entries.next();
3302 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3303 entry.getKey()).getContainer();
3304 sanitizeAndApplyConfigChange(cc, entry.getValue());
3305 }
3306 }
3307 } finally {
3308 Binder.restoreCallingIdentity(ident);
3309 }
3310 }
3311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 @Override
3313 public boolean releaseActivityInstance(IBinder token) {
3314 synchronized (mGlobalLock) {
3315 final long origId = Binder.clearCallingIdentity();
3316 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003317 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3318 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 return false;
3320 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003321 r.destroyImmediately(true /* removeFromApp */, "app-req");
3322 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } finally {
3324 Binder.restoreCallingIdentity(origId);
3325 }
3326 }
3327 }
3328
3329 @Override
3330 public void releaseSomeActivities(IApplicationThread appInt) {
3331 synchronized (mGlobalLock) {
3332 final long origId = Binder.clearCallingIdentity();
3333 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003334 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003335 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 } finally {
3337 Binder.restoreCallingIdentity(origId);
3338 }
3339 }
3340 }
3341
3342 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003343 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 != PackageManager.PERMISSION_GRANTED) {
3346 throw new SecurityException("Requires permission "
3347 + android.Manifest.permission.DEVICE_POWER);
3348 }
3349
3350 synchronized (mGlobalLock) {
3351 long ident = Binder.clearCallingIdentity();
3352 if (mKeyguardShown != keyguardShowing) {
3353 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003354 final Message msg = PooledLambda.obtainMessage(
3355 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3356 keyguardShowing);
3357 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359 try {
wilsonshih177261f2019-02-22 12:02:18 +08003360 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(ident);
3363 }
3364 }
3365
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 mH.post(() -> {
3367 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3368 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3369 }
3370 });
3371 }
3372
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003373 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 mH.post(() -> {
3375 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3376 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3377 }
3378 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 }
3380
3381 @Override
3382 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3384 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385
3386 final File passedIconFile = new File(filePath);
3387 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3388 passedIconFile.getName());
3389 if (!legitIconFile.getPath().equals(filePath)
3390 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3391 throw new IllegalArgumentException("Bad file path: " + filePath
3392 + " passed for userId " + userId);
3393 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003394 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396
3397 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 synchronized (mGlobalLock) {
3401 final long ident = Binder.clearCallingIdentity();
3402 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003403 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 if (stack == null) {
3405 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3406 return;
3407 }
3408 if (!stack.isActivityTypeStandardOrUndefined()) {
3409 throw new IllegalArgumentException(
3410 "Removing non-standard stack is not allowed.");
3411 }
3412 mStackSupervisor.removeStack(stack);
3413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
3416 }
3417 }
3418
3419 @Override
3420 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422
3423 synchronized (mGlobalLock) {
3424 final long ident = Binder.clearCallingIdentity();
3425 try {
3426 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3427 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003428 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433 }
3434
3435 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003436 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 synchronized (mGlobalLock) {
3438 long ident = Binder.clearCallingIdentity();
3439 try {
3440 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3441 if (r == null) {
3442 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003443 "toggleFreeformWindowingMode: No activity record matching token="
3444 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003447 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003448 if (stack == null) {
3449 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3450 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 }
3452
Yunfan Chend967af82019-01-17 18:30:18 +09003453 if (!stack.inFreeformWindowingMode()
3454 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3455 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3456 + "toggle between fullscreen and freeform.");
3457 }
3458
3459 if (stack.inFreeformWindowingMode()) {
3460 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003461 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003462 throw new IllegalStateException("Size-compat windows are currently not"
3463 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003464 } else if (stack.getParent().inFreeformWindowingMode()) {
3465 // If the window is on a freeform display, set it to undefined. It will be
3466 // resolved to freeform and it can adjust windowing mode when the display mode
3467 // changes in runtime.
3468 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003469 } else {
3470 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3471 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 } finally {
3473 Binder.restoreCallingIdentity(ident);
3474 }
3475 }
3476 }
3477
3478 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3479 @Override
3480 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003483 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
3486 /** Unregister a task stack listener so that it stops receiving callbacks. */
3487 @Override
3488 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003491 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 }
3493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 @Override
3495 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3496 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3497 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3498 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3499 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3500 }
3501
3502 @Override
3503 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3504 IBinder activityToken, int flags) {
3505 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3506 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3507 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3508 }
3509
3510 @Override
3511 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3512 Bundle args) {
3513 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3514 true /* focused */, true /* newSessionId */, userHandle, args,
3515 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3516 }
3517
3518 @Override
3519 public Bundle getAssistContextExtras(int requestType) {
3520 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3521 null, null, true /* focused */, true /* newSessionId */,
3522 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3523 if (pae == null) {
3524 return null;
3525 }
3526 synchronized (pae) {
3527 while (!pae.haveResult) {
3528 try {
3529 pae.wait();
3530 } catch (InterruptedException e) {
3531 }
3532 }
3533 }
3534 synchronized (mGlobalLock) {
3535 buildAssistBundleLocked(pae, pae.result);
3536 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003537 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 }
3539 return pae.extras;
3540 }
3541
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 /**
3543 * Binder IPC calls go through the public entry point.
3544 * This can be called with or without the global lock held.
3545 */
3546 private static int checkCallingPermission(String permission) {
3547 return checkPermission(
3548 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3549 }
3550
3551 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003552 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003553 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3554 mAmInternal.enforceCallingPermission(permission, func);
3555 }
3556 }
3557
3558 @VisibleForTesting
3559 int checkGetTasksPermission(String permission, int pid, int uid) {
3560 return checkPermission(permission, pid, uid);
3561 }
3562
3563 static int checkPermission(String permission, int pid, int uid) {
3564 if (permission == null) {
3565 return PackageManager.PERMISSION_DENIED;
3566 }
3567 return checkComponentPermission(permission, pid, uid, -1, true);
3568 }
3569
Wale Ogunwale214f3482018-10-04 11:00:47 -07003570 public static int checkComponentPermission(String permission, int pid, int uid,
3571 int owningUid, boolean exported) {
3572 return ActivityManagerService.checkComponentPermission(
3573 permission, pid, uid, owningUid, exported);
3574 }
3575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3577 if (getRecentTasks().isCallerRecents(callingUid)) {
3578 // Always allow the recents component to get tasks
3579 return true;
3580 }
3581
3582 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3583 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3584 if (!allowed) {
3585 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3586 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3587 // Temporary compatibility: some existing apps on the system image may
3588 // still be requesting the old permission and not switched to the new
3589 // one; if so, we'll still allow them full access. This means we need
3590 // to see if they are holding the old permission and are a system app.
3591 try {
3592 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3593 allowed = true;
3594 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3595 + " is using old GET_TASKS but privileged; allowing");
3596 }
3597 } catch (RemoteException e) {
3598 }
3599 }
3600 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3601 + " does not hold REAL_GET_TASKS; limiting output");
3602 }
3603 return allowed;
3604 }
3605
Nicholas Sauer0259e532019-08-30 08:24:55 -07003606 boolean isCrossUserAllowed(int pid, int uid) {
3607 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3608 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3609 }
3610
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3612 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3613 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3614 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003615 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003616 "enqueueAssistContext()");
3617
3618 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003619 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 if (activity == null) {
3621 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3622 return null;
3623 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003624 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3626 return null;
3627 }
3628 if (focused) {
3629 if (activityToken != null) {
3630 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3631 if (activity != caller) {
3632 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3633 + " is not current top " + activity);
3634 return null;
3635 }
3636 }
3637 } else {
3638 activity = ActivityRecord.forTokenLocked(activityToken);
3639 if (activity == null) {
3640 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3641 + " couldn't be found");
3642 return null;
3643 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003644 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3646 return null;
3647 }
3648 }
3649
3650 PendingAssistExtras pae;
3651 Bundle extras = new Bundle();
3652 if (args != null) {
3653 extras.putAll(args);
3654 }
3655 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003656 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657
3658 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3659 userHandle);
3660 pae.isHome = activity.isActivityTypeHome();
3661
3662 // Increment the sessionId if necessary
3663 if (newSessionId) {
3664 mViSessionId++;
3665 }
3666 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003667 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3668 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003670 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 } catch (RemoteException e) {
3672 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3673 return null;
3674 }
3675 return pae;
3676 }
3677 }
3678
3679 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3680 if (result != null) {
3681 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3682 }
3683 if (pae.hint != null) {
3684 pae.extras.putBoolean(pae.hint, true);
3685 }
3686 }
3687
3688 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3689 IAssistDataReceiver receiver;
3690 synchronized (mGlobalLock) {
3691 mPendingAssistExtras.remove(pae);
3692 receiver = pae.receiver;
3693 }
3694 if (receiver != null) {
3695 // Caller wants result sent back to them.
3696 Bundle sendBundle = new Bundle();
3697 // At least return the receiver extras
3698 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3699 try {
3700 pae.receiver.onHandleAssistData(sendBundle);
3701 } catch (RemoteException e) {
3702 }
3703 }
3704 }
3705
3706 public class PendingAssistExtras extends Binder implements Runnable {
3707 public final ActivityRecord activity;
3708 public boolean isHome;
3709 public final Bundle extras;
3710 public final Intent intent;
3711 public final String hint;
3712 public final IAssistDataReceiver receiver;
3713 public final int userHandle;
3714 public boolean haveResult = false;
3715 public Bundle result = null;
3716 public AssistStructure structure = null;
3717 public AssistContent content = null;
3718 public Bundle receiverExtras;
3719
3720 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3721 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3722 int _userHandle) {
3723 activity = _activity;
3724 extras = _extras;
3725 intent = _intent;
3726 hint = _hint;
3727 receiver = _receiver;
3728 receiverExtras = _receiverExtras;
3729 userHandle = _userHandle;
3730 }
3731
3732 @Override
3733 public void run() {
3734 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3735 synchronized (this) {
3736 haveResult = true;
3737 notifyAll();
3738 }
3739 pendingAssistExtrasTimedOut(this);
3740 }
3741 }
3742
3743 @Override
3744 public boolean isAssistDataAllowedOnCurrentActivity() {
3745 int userId;
3746 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003747 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3749 return false;
3750 }
3751
Wale Ogunwale21e06482019-11-18 05:14:15 -08003752 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 if (activity == null) {
3754 return false;
3755 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003756 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 }
3758 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3759 }
3760
3761 @Override
3762 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3763 long ident = Binder.clearCallingIdentity();
3764 try {
3765 synchronized (mGlobalLock) {
3766 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003767 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (top != caller) {
3769 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3770 + " is not current top " + top);
3771 return false;
3772 }
3773 if (!top.nowVisible) {
3774 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3775 + " is not visible");
3776 return false;
3777 }
3778 }
3779 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3780 token);
3781 } finally {
3782 Binder.restoreCallingIdentity(ident);
3783 }
3784 }
3785
3786 @Override
3787 public boolean isRootVoiceInteraction(IBinder token) {
3788 synchronized (mGlobalLock) {
3789 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3790 if (r == null) {
3791 return false;
3792 }
3793 return r.rootVoiceInteraction;
3794 }
3795 }
3796
Wale Ogunwalef6733932018-06-27 05:14:34 -07003797 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3798 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3799 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3800 if (activityToCallback == null) return;
3801 activityToCallback.setVoiceSessionLocked(voiceSession);
3802
3803 // Inform the activity
3804 try {
3805 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3806 voiceInteractor);
3807 long token = Binder.clearCallingIdentity();
3808 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003809 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003810 } finally {
3811 Binder.restoreCallingIdentity(token);
3812 }
3813 // TODO: VI Should we cache the activity so that it's easier to find later
3814 // rather than scan through all the stacks and activities?
3815 } catch (RemoteException re) {
3816 activityToCallback.clearVoiceSessionLocked();
3817 // TODO: VI Should this terminate the voice session?
3818 }
3819 }
3820
3821 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3822 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3823 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3824 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3825 boolean wasRunningVoice = mRunningVoice != null;
3826 mRunningVoice = session;
3827 if (!wasRunningVoice) {
3828 mVoiceWakeLock.acquire();
3829 updateSleepIfNeededLocked();
3830 }
3831 }
3832 }
3833
3834 void finishRunningVoiceLocked() {
3835 if (mRunningVoice != null) {
3836 mRunningVoice = null;
3837 mVoiceWakeLock.release();
3838 updateSleepIfNeededLocked();
3839 }
3840 }
3841
3842 @Override
3843 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3844 synchronized (mGlobalLock) {
3845 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3846 if (keepAwake) {
3847 mVoiceWakeLock.acquire();
3848 } else {
3849 mVoiceWakeLock.release();
3850 }
3851 }
3852 }
3853 }
3854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 @Override
3856 public ComponentName getActivityClassForToken(IBinder token) {
3857 synchronized (mGlobalLock) {
3858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3859 if (r == null) {
3860 return null;
3861 }
3862 return r.intent.getComponent();
3863 }
3864 }
3865
3866 @Override
3867 public String getPackageForToken(IBinder token) {
3868 synchronized (mGlobalLock) {
3869 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3870 if (r == null) {
3871 return null;
3872 }
3873 return r.packageName;
3874 }
3875 }
3876
3877 @Override
3878 public void showLockTaskEscapeMessage(IBinder token) {
3879 synchronized (mGlobalLock) {
3880 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3881 if (r == null) {
3882 return;
3883 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003884 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 }
3886 }
3887
3888 @Override
3889 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003890 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 final long token = Binder.clearCallingIdentity();
3892 try {
3893 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003894 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(token);
3898 }
3899 }
3900
3901 /**
3902 * Try to place task to provided position. The final position might be different depending on
3903 * current user and stacks state. The task will be moved to target stack if it's currently in
3904 * different stack.
3905 */
3906 @Override
3907 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 synchronized (mGlobalLock) {
3910 long ident = Binder.clearCallingIdentity();
3911 try {
3912 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3913 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003914 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 if (task == null) {
3916 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3917 + taskId);
3918 }
3919
Wale Ogunwaled32da472018-11-16 07:19:28 -08003920 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921
3922 if (stack == null) {
3923 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3924 + stackId);
3925 }
3926 if (!stack.isActivityTypeStandardOrUndefined()) {
3927 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3928 + " the position of task " + taskId + " in/to non-standard stack");
3929 }
3930
3931 // TODO: Have the callers of this API call a separate reparent method if that is
3932 // what they intended to do vs. having this method also do reparenting.
3933 if (task.getStack() == stack) {
3934 // Change position in current stack.
3935 stack.positionChildAt(task, position);
3936 } else {
3937 // Reparent to new stack.
3938 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3939 !DEFER_RESUME, "positionTaskInStack");
3940 }
3941 } finally {
3942 Binder.restoreCallingIdentity(ident);
3943 }
3944 }
3945 }
3946
3947 @Override
3948 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3949 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3950 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003951 + Arrays.toString(horizontalSizeConfiguration) + " "
3952 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 synchronized (mGlobalLock) {
3954 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3955 if (record == null) {
3956 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3957 + "found for: " + token);
3958 }
3959 record.setSizeConfigurations(horizontalSizeConfiguration,
3960 verticalSizeConfigurations, smallestSizeConfigurations);
3961 }
3962 }
3963
3964 /**
3965 * Dismisses split-screen multi-window mode.
3966 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3967 */
3968 @Override
3969 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003970 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3972 final long ident = Binder.clearCallingIdentity();
3973 try {
3974 synchronized (mGlobalLock) {
3975 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003976 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 if (stack == null) {
3978 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3979 return;
3980 }
3981
3982 if (toTop) {
3983 // Caller wants the current split-screen primary stack to be the top stack after
3984 // it goes fullscreen, so move it to the front.
3985 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003986 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003988 // stack after it goes fullscreen, so we move the focus to the top-most
3989 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3991 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3992 if (otherStack != null) {
3993 otherStack.moveToFront("dismissSplitScreenMode_other");
3994 }
3995 }
3996
Evan Rosky10475742018-09-05 19:02:48 -07003997 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 }
3999 } finally {
4000 Binder.restoreCallingIdentity(ident);
4001 }
4002 }
4003
4004 /**
4005 * Dismisses Pip
4006 * @param animate True if the dismissal should be animated.
4007 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4008 * default animation duration should be used.
4009 */
4010 @Override
4011 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 final long ident = Binder.clearCallingIdentity();
4014 try {
4015 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004016 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004017 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 if (stack == null) {
4019 Slog.w(TAG, "dismissPip: pinned stack not found.");
4020 return;
4021 }
4022 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4023 throw new IllegalArgumentException("Stack: " + stack
4024 + " doesn't support animated resize.");
4025 }
4026 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004027 stack.animateResizePinnedStack(null /* destBounds */,
4028 null /* sourceHintBounds */, animationDuration,
4029 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004031 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 }
4033 }
4034 } finally {
4035 Binder.restoreCallingIdentity(ident);
4036 }
4037 }
4038
4039 @Override
4040 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 synchronized (mGlobalLock) {
4043 mSuppressResizeConfigChanges = suppress;
4044 }
4045 }
4046
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 @Override
4048 // TODO: API should just be about changing windowing modes...
4049 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 "moveTasksToFullscreenStack()");
4052 synchronized (mGlobalLock) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004055 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 if (stack != null){
4057 if (!stack.isActivityTypeStandardOrUndefined()) {
4058 throw new IllegalArgumentException(
4059 "You can't move tasks from non-standard stacks.");
4060 }
4061 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4062 }
4063 } finally {
4064 Binder.restoreCallingIdentity(origId);
4065 }
4066 }
4067 }
4068
4069 /**
4070 * Moves the top activity in the input stackId to the pinned stack.
4071 *
4072 * @param stackId Id of stack to move the top activity to pinned stack.
4073 * @param bounds Bounds to use for pinned stack.
4074 *
4075 * @return True if the top activity of the input stack was successfully moved to the pinned
4076 * stack.
4077 */
4078 @Override
4079 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004080 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 "moveTopActivityToPinnedStack()");
4082 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004083 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4085 + "Device doesn't support picture-in-picture mode");
4086 }
4087
4088 long ident = Binder.clearCallingIdentity();
4089 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004090 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 } finally {
4092 Binder.restoreCallingIdentity(ident);
4093 }
4094 }
4095 }
4096
4097 @Override
4098 public boolean isInMultiWindowMode(IBinder token) {
4099 final long origId = Binder.clearCallingIdentity();
4100 try {
4101 synchronized (mGlobalLock) {
4102 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4103 if (r == null) {
4104 return false;
4105 }
4106 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4107 return r.inMultiWindowMode();
4108 }
4109 } finally {
4110 Binder.restoreCallingIdentity(origId);
4111 }
4112 }
4113
4114 @Override
4115 public boolean isInPictureInPictureMode(IBinder token) {
4116 final long origId = Binder.clearCallingIdentity();
4117 try {
4118 synchronized (mGlobalLock) {
4119 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4120 }
4121 } finally {
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124 }
4125
4126 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004127 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4128 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 return false;
4130 }
4131
4132 // If we are animating to fullscreen then we have already dispatched the PIP mode
4133 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004134 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004135 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004136 }
4137
4138 @Override
4139 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4140 final long origId = Binder.clearCallingIdentity();
4141 try {
4142 synchronized (mGlobalLock) {
4143 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4144 "enterPictureInPictureMode", token, params);
4145
4146 // If the activity is already in picture in picture mode, then just return early
4147 if (isInPictureInPictureMode(r)) {
4148 return true;
4149 }
4150
4151 // Activity supports picture-in-picture, now check that we can enter PiP at this
4152 // point, if it is
4153 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4154 false /* beforeStopping */)) {
4155 return false;
4156 }
4157
4158 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004159 synchronized (mGlobalLock) {
4160 // Only update the saved args from the args that are set
4161 r.pictureInPictureArgs.copyOnlySet(params);
4162 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4163 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4164 // Adjust the source bounds by the insets for the transition down
4165 final Rect sourceBounds = new Rect(
4166 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004167 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004168 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004170 stack.setPictureInPictureAspectRatio(aspectRatio);
4171 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004172 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4173 r.info.applicationInfo.uid, r.shortComponentName,
4174 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004175 logPictureInPictureArgs(params);
4176 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 };
4178
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004179 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 // If the keyguard is showing or occluded, then try and dismiss it before
4181 // entering picture-in-picture (this will prompt the user to authenticate if the
4182 // device is currently locked).
4183 dismissKeyguard(token, new KeyguardDismissCallback() {
4184 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 public void onDismissSucceeded() {
4186 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 }
4188 }, null /* message */);
4189 } else {
4190 // Enter picture in picture immediately otherwise
4191 enterPipRunnable.run();
4192 }
4193 return true;
4194 }
4195 } finally {
4196 Binder.restoreCallingIdentity(origId);
4197 }
4198 }
4199
4200 @Override
4201 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4202 final long origId = Binder.clearCallingIdentity();
4203 try {
4204 synchronized (mGlobalLock) {
4205 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4206 "setPictureInPictureParams", token, params);
4207
4208 // Only update the saved args from the args that are set
4209 r.pictureInPictureArgs.copyOnlySet(params);
4210 if (r.inPinnedWindowingMode()) {
4211 // If the activity is already in picture-in-picture, update the pinned stack now
4212 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4213 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004214 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 if (!stack.isAnimatingBoundsToFullscreen()) {
4216 stack.setPictureInPictureAspectRatio(
4217 r.pictureInPictureArgs.getAspectRatio());
4218 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4219 }
4220 }
4221 logPictureInPictureArgs(params);
4222 }
4223 } finally {
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226 }
4227
4228 @Override
4229 public int getMaxNumPictureInPictureActions(IBinder token) {
4230 // Currently, this is a static constant, but later, we may change this to be dependent on
4231 // the context of the activity
4232 return 3;
4233 }
4234
4235 private void logPictureInPictureArgs(PictureInPictureParams params) {
4236 if (params.hasSetActions()) {
4237 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4238 params.getActions().size());
4239 }
4240 if (params.hasSetAspectRatio()) {
4241 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4242 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4243 MetricsLogger.action(lm);
4244 }
4245 }
4246
4247 /**
4248 * Checks the state of the system and the activity associated with the given {@param token} to
4249 * verify that picture-in-picture is supported for that activity.
4250 *
4251 * @return the activity record for the given {@param token} if all the checks pass.
4252 */
4253 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4254 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004255 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 throw new IllegalStateException(caller
4257 + ": Device doesn't support picture-in-picture mode.");
4258 }
4259
4260 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4261 if (r == null) {
4262 throw new IllegalStateException(caller
4263 + ": Can't find activity for token=" + token);
4264 }
4265
4266 if (!r.supportsPictureInPicture()) {
4267 throw new IllegalStateException(caller
4268 + ": Current activity does not support picture-in-picture.");
4269 }
4270
4271 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004272 && !mWindowManager.isValidPictureInPictureAspectRatio(
4273 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 final float minAspectRatio = mContext.getResources().getFloat(
4275 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4276 final float maxAspectRatio = mContext.getResources().getFloat(
4277 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4278 throw new IllegalArgumentException(String.format(caller
4279 + ": Aspect ratio is too extreme (must be between %f and %f).",
4280 minAspectRatio, maxAspectRatio));
4281 }
4282
4283 // Truncate the number of actions if necessary
4284 params.truncateActions(getMaxNumPictureInPictureActions(token));
4285
4286 return r;
4287 }
4288
4289 @Override
4290 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 synchronized (mGlobalLock) {
4293 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4294 if (r == null) {
4295 throw new IllegalArgumentException("Activity does not exist; token="
4296 + activityToken);
4297 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004298 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
4300 }
4301
4302 @Override
4303 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4304 Rect tempDockedTaskInsetBounds,
4305 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 long ident = Binder.clearCallingIdentity();
4308 try {
4309 synchronized (mGlobalLock) {
4310 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4311 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4312 PRESERVE_WINDOWS);
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
4319 @Override
4320 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004321 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 final long ident = Binder.clearCallingIdentity();
4323 try {
4324 synchronized (mGlobalLock) {
4325 mStackSupervisor.setSplitScreenResizing(resizing);
4326 }
4327 } finally {
4328 Binder.restoreCallingIdentity(ident);
4329 }
4330 }
4331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 /**
4333 * Check that we have the features required for VR-related API calls, and throw an exception if
4334 * not.
4335 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004336 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 if (!mContext.getPackageManager().hasSystemFeature(
4338 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4339 throw new UnsupportedOperationException("VR mode not supported on this device!");
4340 }
4341 }
4342
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 @Override
4344 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346
4347 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4348
4349 ActivityRecord r;
4350 synchronized (mGlobalLock) {
4351 r = ActivityRecord.isInStackLocked(token);
4352 }
4353
4354 if (r == null) {
4355 throw new IllegalArgumentException();
4356 }
4357
4358 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004359 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 VrManagerInternal.NO_ERROR) {
4361 return err;
4362 }
4363
4364 // Clear the binder calling uid since this path may call moveToTask().
4365 final long callingId = Binder.clearCallingIdentity();
4366 try {
4367 synchronized (mGlobalLock) {
4368 r.requestedVrComponent = (enabled) ? packageName : null;
4369
4370 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004371 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374 return 0;
4375 }
4376 } finally {
4377 Binder.restoreCallingIdentity(callingId);
4378 }
4379 }
4380
4381 @Override
4382 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4383 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4384 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004385 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4387 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4388 }
Louis Changcdec0802019-11-11 11:45:07 +08004389 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 || activity.voiceSession != null) {
4391 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4392 return;
4393 }
4394 if (activity.pendingVoiceInteractionStart) {
4395 Slog.w(TAG, "Pending start of voice interaction already.");
4396 return;
4397 }
4398 activity.pendingVoiceInteractionStart = true;
4399 }
4400 LocalServices.getService(VoiceInteractionManagerInternal.class)
4401 .startLocalVoiceInteraction(callingActivity, options);
4402 }
4403
4404 @Override
4405 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .stopLocalVoiceInteraction(callingActivity);
4408 }
4409
4410 @Override
4411 public boolean supportsLocalVoiceInteraction() {
4412 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .supportsLocalVoiceInteraction();
4414 }
4415
4416 /** Notifies all listeners when the pinned stack animation starts. */
4417 @Override
4418 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004419 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 /** Notifies all listeners when the pinned stack animation ends. */
4423 @Override
4424 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 }
4427
4428 @Override
4429 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 final long ident = Binder.clearCallingIdentity();
4432 try {
4433 synchronized (mGlobalLock) {
4434 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4435 }
4436 } finally {
4437 Binder.restoreCallingIdentity(ident);
4438 }
4439 }
4440
4441 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444
4445 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004446 if (mWindowManager == null) {
4447 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4448 return false;
4449 }
4450
4451 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
4455
Riddle Hsua0022cd2019-09-09 21:12:41 +08004456 mH.sendMessage(PooledLambda.obtainMessage(
4457 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4458 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459
4460 final long origId = Binder.clearCallingIdentity();
4461 try {
4462 if (values != null) {
4463 Settings.System.clearConfiguration(values);
4464 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 UserHandle.USER_NULL, false /* deferResume */,
4467 mTmpUpdateConfigurationResult);
4468 return mTmpUpdateConfigurationResult.changes != 0;
4469 } finally {
4470 Binder.restoreCallingIdentity(origId);
4471 }
4472 }
4473 }
4474
4475 @Override
4476 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4477 CharSequence message) {
4478 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4481 }
4482 final long callingId = Binder.clearCallingIdentity();
4483 try {
4484 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 } finally {
4488 Binder.restoreCallingIdentity(callingId);
4489 }
4490 }
4491
4492 @Override
4493 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 "cancelTaskWindowTransition()");
4496 final long ident = Binder.clearCallingIdentity();
4497 try {
4498 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004499 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 MATCH_TASK_IN_STACKS_ONLY);
4501 if (task == null) {
4502 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4503 return;
4504 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004505 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
4507 } finally {
4508 Binder.restoreCallingIdentity(ident);
4509 }
4510 }
4511
4512 @Override
4513 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 final long ident = Binder.clearCallingIdentity();
4516 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 } finally {
4519 Binder.restoreCallingIdentity(ident);
4520 }
4521 }
4522
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004523 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4524 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004525 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004526 synchronized (mGlobalLock) {
4527 task = mRootActivityContainer.anyTaskForId(taskId,
4528 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4529 if (task == null) {
4530 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4531 return null;
4532 }
4533 }
4534 // Don't call this while holding the lock as this operation might hit the disk.
4535 return task.getSnapshot(reducedResolution, restoreFromDisk);
4536 }
4537
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 @Override
4539 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4540 synchronized (mGlobalLock) {
4541 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4542 if (r == null) {
4543 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4544 + token);
4545 return;
4546 }
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
4549 r.setDisablePreviewScreenshots(disable);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
4556 /** Return the user id of the last resumed activity. */
4557 @Override
4558 public @UserIdInt
4559 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4562 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004563 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004564 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004566 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568 }
4569
4570 @Override
4571 public void updateLockTaskFeatures(int userId, int flags) {
4572 final int callingUid = Binder.getCallingUid();
4573 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004574 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 "updateLockTaskFeatures()");
4576 }
4577 synchronized (mGlobalLock) {
4578 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4579 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004580 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 }
4582 }
4583
4584 @Override
4585 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4586 synchronized (mGlobalLock) {
4587 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4588 if (r == null) {
4589 return;
4590 }
4591 final long origId = Binder.clearCallingIdentity();
4592 try {
4593 r.setShowWhenLocked(showWhenLocked);
4594 } finally {
4595 Binder.restoreCallingIdentity(origId);
4596 }
4597 }
4598 }
4599
4600 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004601 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4618 synchronized (mGlobalLock) {
4619 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4620 if (r == null) {
4621 return;
4622 }
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
4625 r.setTurnScreenOn(turnScreenOn);
4626 } finally {
4627 Binder.restoreCallingIdentity(origId);
4628 }
4629 }
4630 }
4631
4632 @Override
4633 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004634 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004636 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 synchronized (mGlobalLock) {
4638 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4639 if (r == null) {
4640 return;
4641 }
4642 final long origId = Binder.clearCallingIdentity();
4643 try {
4644 r.registerRemoteAnimations(definition);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
4651 @Override
4652 public void registerRemoteAnimationForNextActivityStart(String packageName,
4653 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004656 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004657 synchronized (mGlobalLock) {
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004660 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 packageName, adapter);
4662 } finally {
4663 Binder.restoreCallingIdentity(origId);
4664 }
4665 }
4666 }
4667
Evan Rosky966759f2019-01-15 10:33:58 -08004668 @Override
4669 public void registerRemoteAnimationsForDisplay(int displayId,
4670 RemoteAnimationDefinition definition) {
4671 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4672 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004673 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004674 synchronized (mGlobalLock) {
4675 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4676 if (display == null) {
4677 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4678 return;
4679 }
4680 final long origId = Binder.clearCallingIdentity();
4681 try {
4682 display.mDisplayContent.registerRemoteAnimations(definition);
4683 } finally {
4684 Binder.restoreCallingIdentity(origId);
4685 }
4686 }
4687 }
4688
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4690 @Override
4691 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4692 synchronized (mGlobalLock) {
4693 final long origId = Binder.clearCallingIdentity();
4694 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004695 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004696 } finally {
4697 Binder.restoreCallingIdentity(origId);
4698 }
4699 }
4700 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004701
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 @Override
4703 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004704 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004706 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004707 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004708 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 }
4710 }
4711
4712 @Override
4713 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 != PERMISSION_GRANTED) {
4716 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4717 + Binder.getCallingPid()
4718 + ", uid=" + Binder.getCallingUid()
4719 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4720 Slog.w(TAG, msg);
4721 throw new SecurityException(msg);
4722 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004723 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004725 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004726 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004727 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 }
4729 }
4730
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004731 @Override
4732 public void stopAppSwitches() {
4733 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4734 synchronized (mGlobalLock) {
4735 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004736 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 mDidAppSwitch = false;
4738 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4739 }
4740 }
4741
4742 @Override
4743 public void resumeAppSwitches() {
4744 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4745 synchronized (mGlobalLock) {
4746 // Note that we don't execute any pending app switches... we will
4747 // let those wait until either the timeout, or the next start
4748 // activity request.
4749 mAppSwitchesAllowedTime = 0;
4750 }
4751 }
4752
Ricky Wai906af482019-06-03 17:25:28 +01004753 long getLastStopAppSwitchesTime() {
4754 return mLastStopAppSwitchesTime;
4755 }
4756
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 void onStartActivitySetDidAppSwitch() {
4758 if (mDidAppSwitch) {
4759 // This is the second allowed switch since we stopped switches, so now just generally
4760 // allow switches. Use case:
4761 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4762 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4763 // anyone to switch again).
4764 mAppSwitchesAllowedTime = 0;
4765 } else {
4766 mDidAppSwitch = true;
4767 }
4768 }
4769
4770 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004771 boolean shouldDisableNonVrUiLocked() {
4772 return mVrController.shouldDisableNonVrUiLocked();
4773 }
4774
Wale Ogunwale53783742018-09-16 10:21:51 -07004775 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004776 // 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 +00004777 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004779 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4780 + " to main display for VR");
4781 mRootActivityContainer.moveStackToDisplay(
4782 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004783 }
4784 mH.post(() -> {
4785 if (!mVrController.onVrModeChanged(r)) {
4786 return;
4787 }
4788 synchronized (mGlobalLock) {
4789 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4790 mWindowManager.disableNonVrUi(disableNonVrUi);
4791 if (disableNonVrUi) {
4792 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4793 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004794 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 }
4796 }
4797 });
4798 }
4799
Wale Ogunwale53783742018-09-16 10:21:51 -07004800 @Override
4801 public int getPackageScreenCompatMode(String packageName) {
4802 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4803 synchronized (mGlobalLock) {
4804 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4805 }
4806 }
4807
4808 @Override
4809 public void setPackageScreenCompatMode(String packageName, int mode) {
4810 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4811 "setPackageScreenCompatMode");
4812 synchronized (mGlobalLock) {
4813 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4814 }
4815 }
4816
4817 @Override
4818 public boolean getPackageAskScreenCompat(String packageName) {
4819 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4820 synchronized (mGlobalLock) {
4821 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4822 }
4823 }
4824
4825 @Override
4826 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4827 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4828 "setPackageAskScreenCompat");
4829 synchronized (mGlobalLock) {
4830 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4831 }
4832 }
4833
Wale Ogunwale64258362018-10-16 15:13:37 -07004834 public static String relaunchReasonToString(int relaunchReason) {
4835 switch (relaunchReason) {
4836 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4837 return "window_resize";
4838 case RELAUNCH_REASON_FREE_RESIZE:
4839 return "free_resize";
4840 default:
4841 return null;
4842 }
4843 }
4844
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004845 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004846 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004847 }
4848
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004849 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004850 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004851 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4852 }
4853
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004854 boolean isKeyguardLocked() {
4855 return mKeyguardController.isKeyguardLocked();
4856 }
4857
Garfield Tan01548632018-11-27 10:15:48 -08004858 /**
4859 * Clears launch params for the given package.
4860 * @param packageNames the names of the packages of which the launch params are to be cleared
4861 */
4862 @Override
4863 public void clearLaunchParamsForPackages(List<String> packageNames) {
4864 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4865 "clearLaunchParamsForPackages");
4866 synchronized (mGlobalLock) {
4867 for (int i = 0; i < packageNames.size(); ++i) {
4868 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4869 }
4870 }
4871 }
4872
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004873 /**
4874 * Makes the display with the given id a single task instance display. I.e the display can only
4875 * contain one task.
4876 */
4877 @Override
4878 public void setDisplayToSingleTaskInstance(int displayId) {
4879 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4880 "setDisplayToSingleTaskInstance");
4881 final long origId = Binder.clearCallingIdentity();
4882 try {
4883 final ActivityDisplay display =
4884 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4885 if (display != null) {
4886 display.setDisplayToSingleTaskInstance();
4887 }
4888 } finally {
4889 Binder.restoreCallingIdentity(origId);
4890 }
4891 }
4892
Wale Ogunwale31913b52018-10-13 08:29:31 -07004893 void dumpLastANRLocked(PrintWriter pw) {
4894 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4895 if (mLastANRState == null) {
4896 pw.println(" <no ANR has occurred since boot>");
4897 } else {
4898 pw.println(mLastANRState);
4899 }
4900 }
4901
4902 void dumpLastANRTracesLocked(PrintWriter pw) {
4903 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4904
4905 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4906 if (ArrayUtils.isEmpty(files)) {
4907 pw.println(" <no ANR has occurred since boot>");
4908 return;
4909 }
4910 // Find the latest file.
4911 File latest = null;
4912 for (File f : files) {
4913 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4914 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004915 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004916 }
4917 pw.print("File: ");
4918 pw.print(latest.getName());
4919 pw.println();
4920 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4921 String line;
4922 while ((line = in.readLine()) != null) {
4923 pw.println(line);
4924 }
4925 } catch (IOException e) {
4926 pw.print("Unable to read: ");
4927 pw.print(e);
4928 pw.println();
4929 }
4930 }
4931
4932 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4933 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4934 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4935 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4936 }
4937
4938 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4939 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4940 pw.println(header);
4941
Wale Ogunwaled32da472018-11-16 07:19:28 -08004942 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 dumpPackage);
4944 boolean needSep = printedAnything;
4945
4946 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004947 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004948 " ResumedActivity: ");
4949 if (printed) {
4950 printedAnything = true;
4951 needSep = false;
4952 }
4953
4954 if (dumpPackage == null) {
4955 if (needSep) {
4956 pw.println();
4957 }
4958 printedAnything = true;
4959 mStackSupervisor.dump(pw, " ");
4960 }
4961
4962 if (!printedAnything) {
4963 pw.println(" (nothing)");
4964 }
4965 }
4966
4967 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004968 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004969 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004970 pw.println(" ");
4971 }
4972
4973 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4974 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4975 getActivityStartController().dump(pw, "", dumpPackage);
4976 }
4977
4978 /**
4979 * There are three things that cmd can be:
4980 * - a flattened component name that matches an existing activity
4981 * - the cmd arg isn't the flattened component name of an existing activity:
4982 * dump all activity whose component contains the cmd as a substring
4983 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004984 * <p>
4985 * The caller should not hold lock when calling this method because it will wait for the
4986 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 *
4988 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4989 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4990 */
4991 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4992 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4993 ArrayList<ActivityRecord> activities;
4994
4995 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004996 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 dumpFocusedStackOnly);
4998 }
4999
5000 if (activities.size() <= 0) {
5001 return false;
5002 }
5003
5004 String[] newArgs = new String[args.length - opti];
5005 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5006
Louis Changcdec0802019-11-11 11:45:07 +08005007 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005008 boolean needSep = false;
5009 for (int i = activities.size() - 1; i >= 0; i--) {
5010 ActivityRecord r = activities.get(i);
5011 if (needSep) {
5012 pw.println();
5013 }
5014 needSep = true;
5015 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005016 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 if (lastTask != task) {
5018 lastTask = task;
5019 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005020 pw.print(" id="); pw.print(lastTask.mTaskId);
5021 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 if (dumpAll) {
5023 lastTask.dump(pw, " ");
5024 }
5025 }
5026 }
5027 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5028 }
5029 return true;
5030 }
5031
5032 /**
5033 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5034 * there is a thread associated with the activity.
5035 */
5036 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5037 final ActivityRecord r, String[] args, boolean dumpAll) {
5038 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005039 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005040 synchronized (mGlobalLock) {
5041 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5042 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5043 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005044 if (r.hasProcess()) {
5045 pw.println(r.app.getPid());
5046 appThread = r.app.getThread();
5047 } else {
5048 pw.println("(not running)");
5049 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005050 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005051 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 }
5053 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005054 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005055 // flush anything that is already in the PrintWriter since the thread is going
5056 // to write to the file descriptor directly
5057 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005058 try (TransferPipe tp = new TransferPipe()) {
5059 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5060 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005061 } catch (IOException e) {
5062 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5063 } catch (RemoteException e) {
5064 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5065 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005066 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005067 }
5068
sanryhuang498e77e2018-12-06 14:57:01 +08005069 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5070 boolean testPssMode) {
5071 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5072 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5073 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005074 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5076 st.toString());
5077 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5079 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5080 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005081 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5082 testPssMode);
5083 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005084 }
5085
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086 int getCurrentUserId() {
5087 return mAmInternal.getCurrentUserId();
5088 }
5089
5090 private void enforceNotIsolatedCaller(String caller) {
5091 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5092 throw new SecurityException("Isolated process not allowed to call " + caller);
5093 }
5094 }
5095
Wale Ogunwalef6733932018-06-27 05:14:34 -07005096 public Configuration getConfiguration() {
5097 Configuration ci;
5098 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005099 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 ci.userSetLocale = false;
5101 }
5102 return ci;
5103 }
5104
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 /**
5106 * Current global configuration information. Contains general settings for the entire system,
5107 * also corresponds to the merged configuration of the default display.
5108 */
5109 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005110 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 }
5112
5113 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5114 boolean initLocale) {
5115 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5116 }
5117
5118 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5119 boolean initLocale, boolean deferResume) {
5120 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5121 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5122 UserHandle.USER_NULL, deferResume);
5123 }
5124
Wale Ogunwale59507092018-10-29 09:00:30 -07005125 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005126 final long origId = Binder.clearCallingIdentity();
5127 try {
5128 synchronized (mGlobalLock) {
5129 updateConfigurationLocked(values, null, false, true, userId,
5130 false /* deferResume */);
5131 }
5132 } finally {
5133 Binder.restoreCallingIdentity(origId);
5134 }
5135 }
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5138 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5139 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5140 deferResume, null /* result */);
5141 }
5142
5143 /**
5144 * Do either or both things: (1) change the current configuration, and (2)
5145 * make sure the given activity is running with the (now) current
5146 * configuration. Returns true if the activity has been left running, or
5147 * false if <var>starting</var> is being destroyed to match the new
5148 * configuration.
5149 *
5150 * @param userId is only used when persistent parameter is set to true to persist configuration
5151 * for that particular user
5152 */
5153 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5154 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5155 ActivityTaskManagerService.UpdateConfigurationResult result) {
5156 int changes = 0;
5157 boolean kept = true;
5158
Riddle Hsua0022cd2019-09-09 21:12:41 +08005159 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160 try {
5161 if (values != null) {
5162 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5163 deferResume);
5164 }
5165
5166 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5167 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005168 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169 }
5170
5171 if (result != null) {
5172 result.changes = changes;
5173 result.activityRelaunched = !kept;
5174 }
5175 return kept;
5176 }
5177
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005179 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005181
5182 final ActivityDisplay defaultDisplay =
5183 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5184
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185 mTempConfig.setTo(getGlobalConfiguration());
5186 final int changes = mTempConfig.updateFrom(values);
5187 if (changes == 0) {
5188 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5189 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5190 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5191 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005192 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193 return 0;
5194 }
5195
5196 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5197 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005198 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5200 values.colorMode,
5201 values.densityDpi,
5202 values.fontScale,
5203 values.hardKeyboardHidden,
5204 values.keyboard,
5205 values.keyboardHidden,
5206 values.mcc,
5207 values.mnc,
5208 values.navigation,
5209 values.navigationHidden,
5210 values.orientation,
5211 values.screenHeightDp,
5212 values.screenLayout,
5213 values.screenWidthDp,
5214 values.smallestScreenWidthDp,
5215 values.touchscreen,
5216 values.uiMode);
5217
5218
5219 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5220 final LocaleList locales = values.getLocales();
5221 int bestLocaleIndex = 0;
5222 if (locales.size() > 1) {
5223 if (mSupportedSystemLocales == null) {
5224 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5225 }
5226 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5227 }
5228 SystemProperties.set("persist.sys.locale",
5229 locales.get(bestLocaleIndex).toLanguageTag());
5230 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005231
5232 final Message m = PooledLambda.obtainMessage(
5233 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5234 locales.get(bestLocaleIndex));
5235 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 }
5237
Yunfan Chen75157d72018-07-27 14:47:21 +09005238 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005241 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242
5243 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5244 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005245 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246
5247 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005248 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249
5250 AttributeCache ac = AttributeCache.instance();
5251 if (ac != null) {
5252 ac.updateConfiguration(mTempConfig);
5253 }
5254
5255 // Make sure all resources in our process are updated right now, so that anyone who is going
5256 // to retrieve resource values after we return will be sure to get the new ones. This is
5257 // especially important during boot, where the first config change needs to guarantee all
5258 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005259 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260
5261 // We need another copy of global config because we're scheduling some calls instead of
5262 // running them in place. We need to be sure that object we send will be handled unchanged.
5263 final Configuration configCopy = new Configuration(mTempConfig);
5264 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005265 final Message msg = PooledLambda.obtainMessage(
5266 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5267 this, userId, configCopy);
5268 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269 }
5270
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005271 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5272 for (int i = pidMap.size() - 1; i >= 0; i--) {
5273 final int pid = pidMap.keyAt(i);
5274 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005275 if (DEBUG_CONFIGURATION) {
5276 Slog.v(TAG_CONFIGURATION, "Update process config of "
5277 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005279 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280 }
5281
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005282 final Message msg = PooledLambda.obtainMessage(
5283 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5284 mAmInternal, changes, initLocale);
5285 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005286
5287 // Override configuration of the default display duplicates global config, so we need to
5288 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005289 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5290 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291
5292 return changes;
5293 }
5294
Riddle Hsua0022cd2019-09-09 21:12:41 +08005295 /** @see WindowSurfacePlacer#deferLayout */
5296 void deferWindowLayout() {
5297 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5298 // Reset the reasons at the first entrance because we only care about the changes in the
5299 // deferred scope.
5300 mLayoutReasons = 0;
5301 }
5302
5303 mWindowManager.mWindowPlacerLocked.deferLayout();
5304 }
5305
5306 /** @see WindowSurfacePlacer#continueLayout */
5307 void continueWindowLayout() {
5308 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5309 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5310 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5311 }
5312 }
5313
5314 /**
5315 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5316 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5317 * defer count is gone.
5318 */
5319 void addWindowLayoutReasons(@LayoutReason int reasons) {
5320 mLayoutReasons |= reasons;
5321 }
5322
Wale Ogunwalef6733932018-06-27 05:14:34 -07005323 private void updateEventDispatchingLocked(boolean booted) {
5324 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5325 }
5326
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005327 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5328 final ContentResolver resolver = mContext.getContentResolver();
5329 Settings.System.putConfigurationForUser(resolver, config, userId);
5330 }
5331
5332 private void sendLocaleToMountDaemonMsg(Locale l) {
5333 try {
5334 IBinder service = ServiceManager.getService("mount");
5335 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5336 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5337 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5338 } catch (RemoteException e) {
5339 Log.e(TAG, "Error storing locale for decryption UI", e);
5340 }
5341 }
5342
Alison Cichowlas3e340502018-08-07 17:15:01 -04005343 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5344 mStartActivitySources.remove(permissionToken);
5345 mExpiredStartAsCallerTokens.add(permissionToken);
5346 }
5347
5348 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5349 mExpiredStartAsCallerTokens.remove(permissionToken);
5350 }
5351
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005352 boolean isActivityStartsLoggingEnabled() {
5353 return mAmInternal.isActivityStartsLoggingEnabled();
5354 }
5355
Michal Karpinski8596ded2018-11-14 14:43:48 +00005356 boolean isBackgroundActivityStartsEnabled() {
5357 return mAmInternal.isBackgroundActivityStartsEnabled();
5358 }
5359
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005361 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005362 mWindowManager.enableScreenAfterBoot();
5363
5364 synchronized (mGlobalLock) {
5365 updateEventDispatchingLocked(booted);
5366 }
5367 }
5368
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005369 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5370 if (r == null || !r.hasProcess()) {
5371 return KEY_DISPATCHING_TIMEOUT_MS;
5372 }
5373 return getInputDispatchingTimeoutLocked(r.app);
5374 }
5375
5376 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005377 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005378 }
5379
Wale Ogunwalef6733932018-06-27 05:14:34 -07005380 /**
5381 * Decide based on the configuration whether we should show the ANR,
5382 * crash, etc dialogs. The idea is that if there is no affordance to
5383 * press the on-screen buttons, or the user experience would be more
5384 * greatly impacted than the crash itself, we shouldn't show the dialog.
5385 *
5386 * A thought: SystemUI might also want to get told about this, the Power
5387 * dialog / global actions also might want different behaviors.
5388 */
5389 private void updateShouldShowDialogsLocked(Configuration config) {
5390 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5391 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5392 && config.navigation == Configuration.NAVIGATION_NONAV);
5393 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5394 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5395 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5396 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5397 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5398 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5399 HIDE_ERROR_DIALOGS, 0) != 0;
5400 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5401 }
5402
5403 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5404 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5405 FONT_SCALE, 1.0f, userId);
5406
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005407 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005408 if (getGlobalConfiguration().fontScale == scaleFactor) {
5409 return;
5410 }
5411
5412 final Configuration configuration
5413 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5414 configuration.fontScale = scaleFactor;
5415 updatePersistentConfiguration(configuration, userId);
5416 }
5417 }
5418
5419 // Actually is sleeping or shutting down or whatever else in the future
5420 // is an inactive state.
5421 boolean isSleepingOrShuttingDownLocked() {
5422 return isSleepingLocked() || mShuttingDown;
5423 }
5424
5425 boolean isSleepingLocked() {
5426 return mSleeping;
5427 }
5428
Riddle Hsu16567132018-08-16 21:37:47 +08005429 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005431 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 if (task.isActivityTypeStandard()) {
5433 if (mCurAppTimeTracker != r.appTimeTracker) {
5434 // We are switching app tracking. Complete the current one.
5435 if (mCurAppTimeTracker != null) {
5436 mCurAppTimeTracker.stop();
5437 mH.obtainMessage(
5438 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005439 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 mCurAppTimeTracker = null;
5441 }
5442 if (r.appTimeTracker != null) {
5443 mCurAppTimeTracker = r.appTimeTracker;
5444 startTimeTrackingFocusedActivityLocked();
5445 }
5446 } else {
5447 startTimeTrackingFocusedActivityLocked();
5448 }
5449 } else {
5450 r.appTimeTracker = null;
5451 }
5452 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5453 // TODO: Probably not, because we don't want to resume voice on switching
5454 // back to this activity
5455 if (task.voiceInteractor != null) {
5456 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5457 } else {
5458 finishRunningVoiceLocked();
5459
5460 if (mLastResumedActivity != null) {
5461 final IVoiceInteractionSession session;
5462
Louis Changcdec0802019-11-11 11:45:07 +08005463 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005464 if (lastResumedActivityTask != null
5465 && lastResumedActivityTask.voiceSession != null) {
5466 session = lastResumedActivityTask.voiceSession;
5467 } else {
5468 session = mLastResumedActivity.voiceSession;
5469 }
5470
5471 if (session != null) {
5472 // We had been in a voice interaction session, but now focused has
5473 // move to something different. Just finish the session, we can't
5474 // return to it and retain the proper state and synchronization with
5475 // the voice interaction service.
5476 finishVoiceTask(session);
5477 }
5478 }
5479 }
5480
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005481 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5482 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 }
5484 updateResumedAppTrace(r);
5485 mLastResumedActivity = r;
5486
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005487 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488
5489 applyUpdateLockStateLocked(r);
5490 applyUpdateVrModeLocked(r);
5491
Jeff Changd136e772019-11-05 20:33:52 +08005492 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005493 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 r == null ? "NULL" : r.shortComponentName,
5495 reason);
5496 }
5497
5498 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5499 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005500 final ActivityTaskManagerInternal.SleepToken token =
5501 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005502 updateSleepIfNeededLocked();
5503 return token;
5504 }
5505 }
5506
5507 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005508 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 final boolean wasSleeping = mSleeping;
5510 boolean updateOomAdj = false;
5511
5512 if (!shouldSleep) {
5513 // If wasSleeping is true, we need to wake up activity manager state from when
5514 // we started sleeping. In either case, we need to apply the sleep tokens, which
5515 // will wake up stacks or put them to sleep as appropriate.
5516 if (wasSleeping) {
5517 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005518 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5519 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 startTimeTrackingFocusedActivityLocked();
5521 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005522 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005523 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5524 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005525 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526 if (wasSleeping) {
5527 updateOomAdj = true;
5528 }
5529 } else if (!mSleeping && shouldSleep) {
5530 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005531 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5532 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005533 if (mCurAppTimeTracker != null) {
5534 mCurAppTimeTracker.stop();
5535 }
5536 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005537 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 mStackSupervisor.goingToSleepLocked();
5539 updateResumedAppTrace(null /* resumed */);
5540 updateOomAdj = true;
5541 }
5542 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005543 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 }
5545 }
5546
5547 void updateOomAdj() {
5548 mH.post(mAmInternal::updateOomAdj);
5549 }
5550
Wale Ogunwale53783742018-09-16 10:21:51 -07005551 void updateCpuStats() {
5552 mH.post(mAmInternal::updateCpuStats);
5553 }
5554
Hui Yu03d12402018-12-06 18:00:37 -08005555 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5556 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005557 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5558 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005559 mH.sendMessage(m);
5560 }
5561
Hui Yu03d12402018-12-06 18:00:37 -08005562 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005563 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005564 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005565 if (task != null) {
5566 final ActivityRecord rootActivity = task.getRootActivity();
5567 if (rootActivity != null) {
5568 taskRoot = rootActivity.mActivityComponent;
5569 }
5570 }
5571
Hui Yu03d12402018-12-06 18:00:37 -08005572 final Message m = PooledLambda.obtainMessage(
5573 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005574 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005575 mH.sendMessage(m);
5576 }
5577
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005578 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5579 String hostingType) {
5580 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005581 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5582 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005583 + activity.processName);
5584 }
5585 // Post message to start process to avoid possible deadlock of calling into AMS with the
5586 // ATMS lock held.
5587 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5588 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5589 isTop, hostingType, activity.intent.getComponent());
5590 mH.sendMessage(m);
5591 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005592 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005593 }
5594 }
5595
Wale Ogunwale53783742018-09-16 10:21:51 -07005596 void setBooting(boolean booting) {
5597 mAmInternal.setBooting(booting);
5598 }
5599
5600 boolean isBooting() {
5601 return mAmInternal.isBooting();
5602 }
5603
5604 void setBooted(boolean booted) {
5605 mAmInternal.setBooted(booted);
5606 }
5607
5608 boolean isBooted() {
5609 return mAmInternal.isBooted();
5610 }
5611
5612 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5613 mH.post(() -> {
5614 if (finishBooting) {
5615 mAmInternal.finishBooting();
5616 }
5617 if (enableScreen) {
5618 mInternal.enableScreenAfterBoot(isBooted());
5619 }
5620 });
5621 }
5622
5623 void setHeavyWeightProcess(ActivityRecord root) {
5624 mHeavyWeightProcess = root.app;
5625 final Message m = PooledLambda.obtainMessage(
5626 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005627 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005628 mH.sendMessage(m);
5629 }
5630
5631 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5632 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5633 return;
5634 }
5635
5636 mHeavyWeightProcess = null;
5637 final Message m = PooledLambda.obtainMessage(
5638 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5639 proc.mUserId);
5640 mH.sendMessage(m);
5641 }
5642
5643 private void cancelHeavyWeightProcessNotification(int userId) {
5644 final INotificationManager inm = NotificationManager.getService();
5645 if (inm == null) {
5646 return;
5647 }
5648 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005649 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005650 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5651 } catch (RuntimeException e) {
5652 Slog.w(TAG, "Error canceling notification for service", e);
5653 } catch (RemoteException e) {
5654 }
5655
5656 }
5657
5658 private void postHeavyWeightProcessNotification(
5659 WindowProcessController proc, Intent intent, int userId) {
5660 if (proc == null) {
5661 return;
5662 }
5663
5664 final INotificationManager inm = NotificationManager.getService();
5665 if (inm == null) {
5666 return;
5667 }
5668
5669 try {
5670 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5671 String text = mContext.getString(R.string.heavy_weight_notification,
5672 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5673 Notification notification =
5674 new Notification.Builder(context,
5675 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5676 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5677 .setWhen(0)
5678 .setOngoing(true)
5679 .setTicker(text)
5680 .setColor(mContext.getColor(
5681 com.android.internal.R.color.system_notification_accent_color))
5682 .setContentTitle(text)
5683 .setContentText(
5684 mContext.getText(R.string.heavy_weight_notification_detail))
5685 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5686 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5687 new UserHandle(userId)))
5688 .build();
5689 try {
5690 inm.enqueueNotificationWithTag("android", "android", null,
5691 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5692 } catch (RuntimeException e) {
5693 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5694 } catch (RemoteException e) {
5695 }
5696 } catch (PackageManager.NameNotFoundException e) {
5697 Slog.w(TAG, "Unable to create context for heavy notification", e);
5698 }
5699
5700 }
5701
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005702 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5703 IBinder token, String resultWho, int requestCode, Intent[] intents,
5704 String[] resolvedTypes, int flags, Bundle bOptions) {
5705
5706 ActivityRecord activity = null;
5707 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5708 activity = ActivityRecord.isInStackLocked(token);
5709 if (activity == null) {
5710 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5711 return null;
5712 }
5713 if (activity.finishing) {
5714 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5715 return null;
5716 }
5717 }
5718
5719 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5720 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5721 bOptions);
5722 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5723 if (noCreate) {
5724 return rec;
5725 }
5726 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5727 if (activity.pendingResults == null) {
5728 activity.pendingResults = new HashSet<>();
5729 }
5730 activity.pendingResults.add(rec.ref);
5731 }
5732 return rec;
5733 }
5734
Andrii Kulian52d255c2018-07-13 11:32:19 -07005735 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005736 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005737 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005738 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5739 mCurAppTimeTracker.start(resumedActivity.packageName);
5740 }
5741 }
5742
5743 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5744 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005745 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005746 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5747 }
5748 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005749 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005750 constructResumedTraceName(resumed.packageName), 0);
5751 }
5752 mTracedResumedActivity = resumed;
5753 }
5754
5755 private String constructResumedTraceName(String packageName) {
5756 return "focused app: " + packageName;
5757 }
5758
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005759 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005760 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005761 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005762 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005763 // mainStack is null during startup.
5764 if (mainStack != null) {
5765 if (changes != 0 && starting == null) {
5766 // If the configuration changed, and the caller is not already
5767 // in the process of starting an activity, then find the top
5768 // activity to check if its configuration needs to change.
5769 starting = mainStack.topRunningActivityLocked();
5770 }
5771
5772 if (starting != null) {
5773 kept = starting.ensureActivityConfiguration(changes,
5774 false /* preserveWindow */);
5775 // And we need to make sure at this point that all other activities
5776 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005777 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005778 !PRESERVE_WINDOWS);
5779 }
5780 }
5781
5782 return kept;
5783 }
5784
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005785 void scheduleAppGcsLocked() {
5786 mH.post(() -> mAmInternal.scheduleAppGcs());
5787 }
5788
Wale Ogunwale53783742018-09-16 10:21:51 -07005789 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5790 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5791 }
5792
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005793 /**
5794 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5795 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5796 * on demand.
5797 */
5798 IPackageManager getPackageManager() {
5799 return AppGlobals.getPackageManager();
5800 }
5801
5802 PackageManagerInternal getPackageManagerInternalLocked() {
5803 if (mPmInternal == null) {
5804 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5805 }
5806 return mPmInternal;
5807 }
5808
Hai Zhangf4da9be2019-05-01 13:46:06 +08005809 PermissionPolicyInternal getPermissionPolicyInternal() {
5810 if (mPermissionPolicyInternal == null) {
5811 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5812 }
5813 return mPermissionPolicyInternal;
5814 }
5815
Wale Ogunwale008163e2018-07-23 23:11:08 -07005816 AppWarnings getAppWarningsLocked() {
5817 return mAppWarnings;
5818 }
5819
Wale Ogunwale214f3482018-10-04 11:00:47 -07005820 Intent getHomeIntent() {
5821 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5822 intent.setComponent(mTopComponent);
5823 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5824 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5825 intent.addCategory(Intent.CATEGORY_HOME);
5826 }
5827 return intent;
5828 }
5829
Chilun2ef71f72018-11-16 17:57:15 +08005830 /**
5831 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5832 * activities.
5833 *
5834 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5835 * component defined in config_secondaryHomeComponent.
5836 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5837 */
5838 Intent getSecondaryHomeIntent(String preferredPackage) {
5839 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005840 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5841 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5842 if (preferredPackage == null || useSystemProvidedLauncher) {
5843 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005844 final String secondaryHomeComponent = mContext.getResources().getString(
5845 com.android.internal.R.string.config_secondaryHomeComponent);
5846 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5847 } else {
5848 intent.setPackage(preferredPackage);
5849 }
5850 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5851 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5852 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5853 }
5854 return intent;
5855 }
5856
Wale Ogunwale214f3482018-10-04 11:00:47 -07005857 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5858 if (info == null) return null;
5859 ApplicationInfo newInfo = new ApplicationInfo(info);
5860 newInfo.initForUser(userId);
5861 return newInfo;
5862 }
5863
Wale Ogunwale9c103022018-10-18 07:44:54 -07005864 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005865 if (uid == SYSTEM_UID) {
5866 // The system gets to run in any process. If there are multiple processes with the same
5867 // uid, just pick the first (this should never happen).
5868 final SparseArray<WindowProcessController> procs =
5869 mProcessNames.getMap().get(processName);
5870 if (procs == null) return null;
5871 final int procCount = procs.size();
5872 for (int i = 0; i < procCount; i++) {
5873 final int procUid = procs.keyAt(i);
5874 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5875 // Don't use an app process or different user process for system component.
5876 continue;
5877 }
5878 return procs.valueAt(i);
5879 }
5880 }
5881
5882 return mProcessNames.get(processName, uid);
5883 }
5884
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005885 WindowProcessController getProcessController(IApplicationThread thread) {
5886 if (thread == null) {
5887 return null;
5888 }
5889
5890 final IBinder threadBinder = thread.asBinder();
5891 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5892 for (int i = pmap.size()-1; i >= 0; i--) {
5893 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5894 for (int j = procs.size() - 1; j >= 0; j--) {
5895 final WindowProcessController proc = procs.valueAt(j);
5896 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5897 return proc;
5898 }
5899 }
5900 }
5901
5902 return null;
5903 }
5904
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005905 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005906 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005907 if (proc == null) return null;
5908 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5909 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005910 }
5911 return null;
5912 }
5913
Riddle Hsua0536432019-02-16 00:38:59 +08005914 int getUidState(int uid) {
5915 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005916 }
5917
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005918 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005919 // A uid is considered to be foreground if it has a visible non-toast window.
5920 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005921 }
5922
Ricky Wai96f5c352019-04-10 18:40:17 +01005923 boolean isDeviceOwner(int uid) {
5924 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005925 }
5926
Ricky Wai96f5c352019-04-10 18:40:17 +01005927 void setDeviceOwnerUid(int uid) {
5928 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005929 }
5930
Wale Ogunwale9de19442018-10-18 19:05:03 -07005931 /**
5932 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5933 * the whitelist
5934 */
5935 String getPendingTempWhitelistTagForUidLocked(int uid) {
5936 return mPendingTempWhitelist.get(uid);
5937 }
5938
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005939 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5940 if (true || Build.IS_USER) {
5941 return;
5942 }
5943
5944 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5945 StrictMode.allowThreadDiskWrites();
5946 try {
5947 File tracesDir = new File("/data/anr");
5948 File tracesFile = null;
5949 try {
5950 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5951
5952 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005953 String timeString =
5954 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5955 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005956 sb.append(": ");
5957 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5958 sb.append(" since ");
5959 sb.append(msg);
5960 FileOutputStream fos = new FileOutputStream(tracesFile);
5961 fos.write(sb.toString().getBytes());
5962 if (app == null) {
5963 fos.write("\n*** No application process!".getBytes());
5964 }
5965 fos.close();
5966 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5967 } catch (IOException e) {
5968 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5969 return;
5970 }
5971
5972 if (app != null && app.getPid() > 0) {
5973 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5974 firstPids.add(app.getPid());
5975 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5976 }
5977
5978 File lastTracesFile = null;
5979 File curTracesFile = null;
5980 for (int i=9; i>=0; i--) {
5981 String name = String.format(Locale.US, "slow%02d.txt", i);
5982 curTracesFile = new File(tracesDir, name);
5983 if (curTracesFile.exists()) {
5984 if (lastTracesFile != null) {
5985 curTracesFile.renameTo(lastTracesFile);
5986 } else {
5987 curTracesFile.delete();
5988 }
5989 }
5990 lastTracesFile = curTracesFile;
5991 }
5992 tracesFile.renameTo(curTracesFile);
5993 } finally {
5994 StrictMode.setThreadPolicy(oldPolicy);
5995 }
5996 }
5997
Michal Karpinskida34cd42019-04-02 19:46:52 +01005998 boolean isAssociatedCompanionApp(int userId, int uid) {
5999 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6000 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006001 return false;
6002 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006003 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006004 }
6005
Issei Suzuki734bc942019-06-05 13:59:52 +02006006 void notifySingleTaskDisplayEmpty(int displayId) {
6007 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6008 }
6009
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006010 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006011 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006012
6013
Wale Ogunwale98875612018-10-12 07:53:02 -07006014 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6015 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006016
Riddle Hsud93a6c42018-11-29 21:50:06 +08006017 H(Looper looper) {
6018 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006019 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006020
6021 @Override
6022 public void handleMessage(Message msg) {
6023 switch (msg.what) {
6024 case REPORT_TIME_TRACKER_MSG: {
6025 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6026 tracker.deliverResult(mContext);
6027 } break;
6028 }
6029 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006030 }
6031
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006032 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006033 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006034
6035 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006036 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006037 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006038
6039 @Override
6040 public void handleMessage(Message msg) {
6041 switch (msg.what) {
6042 case DISMISS_DIALOG_UI_MSG: {
6043 final Dialog d = (Dialog) msg.obj;
6044 d.dismiss();
6045 break;
6046 }
6047 }
6048 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006049 }
6050
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006051 final class LocalService extends ActivityTaskManagerInternal {
6052 @Override
6053 public SleepToken acquireSleepToken(String tag, int displayId) {
6054 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006055 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057
6058 @Override
6059 public ComponentName getHomeActivityForUser(int userId) {
6060 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006061 final ActivityRecord homeActivity =
6062 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006063 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006064 }
6065 }
6066
6067 @Override
6068 public void onLocalVoiceInteractionStarted(IBinder activity,
6069 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6070 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006071 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006072 }
6073 }
6074
6075 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006076 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006077 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006078 synchronized (mGlobalLock) {
6079 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006080 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006081 }
6082 }
6083
6084 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006085 public void notifySingleTaskDisplayDrawn(int displayId) {
6086 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6087 }
6088
6089 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006090 public void notifyAppTransitionFinished() {
6091 synchronized (mGlobalLock) {
6092 mStackSupervisor.notifyAppTransitionDone();
6093 }
6094 }
6095
6096 @Override
6097 public void notifyAppTransitionCancelled() {
6098 synchronized (mGlobalLock) {
6099 mStackSupervisor.notifyAppTransitionDone();
6100 }
6101 }
6102
6103 @Override
6104 public List<IBinder> getTopVisibleActivities() {
6105 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006106 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 }
6108 }
6109
6110 @Override
6111 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6112 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006113 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 }
6115 }
6116
6117 @Override
6118 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6119 Bundle bOptions) {
6120 Preconditions.checkNotNull(intents, "intents");
6121 final String[] resolvedTypes = new String[intents.length];
6122
6123 // UID of the package on user userId.
6124 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6125 // packageUid may not be initialized.
6126 int packageUid = 0;
6127 final long ident = Binder.clearCallingIdentity();
6128
6129 try {
6130 for (int i = 0; i < intents.length; i++) {
6131 resolvedTypes[i] =
6132 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6133 }
6134
6135 packageUid = AppGlobals.getPackageManager().getPackageUid(
6136 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6137 } catch (RemoteException e) {
6138 // Shouldn't happen.
6139 } finally {
6140 Binder.restoreCallingIdentity(ident);
6141 }
6142
Riddle Hsu591bf612019-02-14 17:55:31 +08006143 return getActivityStartController().startActivitiesInPackage(
6144 packageUid, packageName,
6145 intents, resolvedTypes, null /* resultTo */,
6146 SafeActivityOptions.fromBundle(bOptions), userId,
6147 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6148 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006149 }
6150
6151 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006152 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6153 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6154 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6155 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006156 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006157 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006158 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6159 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6160 userId, validateIncomingUser, originatingPendingIntent,
6161 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006162 }
6163 }
6164
6165 @Override
6166 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6167 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6168 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006169 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006170 PendingIntentRecord originatingPendingIntent,
6171 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006172 synchronized (mGlobalLock) {
6173 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6174 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6175 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006176 validateIncomingUser, originatingPendingIntent,
6177 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006178 }
6179 }
6180
6181 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6183 Intent intent, Bundle options, int userId) {
6184 return ActivityTaskManagerService.this.startActivityAsUser(
6185 caller, callerPacakge, intent,
6186 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6187 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6188 false /*validateIncomingUser*/);
6189 }
6190
6191 @Override
lumark588a3e82018-07-20 18:53:54 +08006192 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 synchronized (mGlobalLock) {
6194
6195 // We might change the visibilities here, so prepare an empty app transition which
6196 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006197 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006199 if (activityDisplay == null) {
6200 return;
6201 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006202 final DisplayContent dc = activityDisplay.mDisplayContent;
6203 final boolean wasTransitionSet =
6204 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006206 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006208 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209
6210 // If there was a transition set already we don't want to interfere with it as we
6211 // might be starting it too early.
6212 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006213 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215 }
6216 if (callback != null) {
6217 callback.run();
6218 }
6219 }
6220
6221 @Override
6222 public void notifyKeyguardTrustedChanged() {
6223 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006224 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006225 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
6227 }
6228 }
6229
6230 /**
6231 * Called after virtual display Id is updated by
6232 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6233 * {@param vrVr2dDisplayId}.
6234 */
6235 @Override
6236 public void setVr2dDisplayId(int vr2dDisplayId) {
6237 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6238 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006239 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241 }
6242
6243 @Override
6244 public void setFocusedActivity(IBinder token) {
6245 synchronized (mGlobalLock) {
6246 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6247 if (r == null) {
6248 throw new IllegalArgumentException(
6249 "setFocusedActivity: No activity record matching token=" + token);
6250 }
Louis Chang19443452018-10-09 12:10:21 +08006251 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006252 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 }
6254 }
6255 }
6256
6257 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006259 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 }
6261
6262 @Override
6263 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006264 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 }
6266
6267 @Override
6268 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006269 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006270 }
6271
6272 @Override
6273 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6274 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6275 }
6276
6277 @Override
6278 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006279 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006281
6282 @Override
6283 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6284 synchronized (mGlobalLock) {
6285 mActiveVoiceInteractionServiceComponent = component;
6286 }
6287 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006288
6289 @Override
6290 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6291 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6292 return;
6293 }
6294 synchronized (mGlobalLock) {
6295 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6296 if (types == null) {
6297 if (uid < 0) {
6298 return;
6299 }
6300 types = new ArrayMap<>();
6301 mAllowAppSwitchUids.put(userId, types);
6302 }
6303 if (uid < 0) {
6304 types.remove(type);
6305 } else {
6306 types.put(type, uid);
6307 }
6308 }
6309 }
6310
6311 @Override
6312 public void onUserStopped(int userId) {
6313 synchronized (mGlobalLock) {
6314 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6315 mAllowAppSwitchUids.remove(userId);
6316 }
6317 }
6318
6319 @Override
6320 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6321 synchronized (mGlobalLock) {
6322 return ActivityTaskManagerService.this.isGetTasksAllowed(
6323 caller, callingPid, callingUid);
6324 }
6325 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006326
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 onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006330 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006331 mProcessNames.put(proc.mName, proc.mUid, proc);
6332 }
6333 }
6334
Riddle Hsua0536432019-02-16 00:38:59 +08006335 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006336 @Override
6337 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006338 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006339 mProcessNames.remove(name, uid);
6340 }
6341 }
6342
Riddle Hsua0536432019-02-16 00:38:59 +08006343 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006344 @Override
6345 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006346 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006347 if (proc == mHomeProcess) {
6348 mHomeProcess = null;
6349 }
6350 if (proc == mPreviousProcess) {
6351 mPreviousProcess = null;
6352 }
6353 }
6354 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006357 @Override
6358 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006360 return mTopProcessState;
6361 }
6362 }
6363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006365 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006366 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006368 return proc == mHeavyWeightProcess;
6369 }
6370 }
6371
Riddle Hsua0536432019-02-16 00:38:59 +08006372 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006373 @Override
6374 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006375 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006376 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6377 }
6378 }
6379
6380 @Override
6381 public void finishHeavyWeightApp() {
6382 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006383 if (mHeavyWeightProcess != null) {
6384 mHeavyWeightProcess.finishActivities();
6385 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006386 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6387 mHeavyWeightProcess);
6388 }
6389 }
6390
Riddle Hsua0536432019-02-16 00:38:59 +08006391 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006392 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006393 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006394 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395 return isSleepingLocked();
6396 }
6397 }
6398
6399 @Override
6400 public boolean isShuttingDown() {
6401 synchronized (mGlobalLock) {
6402 return mShuttingDown;
6403 }
6404 }
6405
6406 @Override
6407 public boolean shuttingDown(boolean booted, int timeout) {
6408 synchronized (mGlobalLock) {
6409 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006410 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006411 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006412 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006413 return mStackSupervisor.shutdownLocked(timeout);
6414 }
6415 }
6416
6417 @Override
6418 public void enableScreenAfterBoot(boolean booted) {
6419 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006420 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006421 mWindowManager.enableScreenAfterBoot();
6422 updateEventDispatchingLocked(booted);
6423 }
6424 }
6425
6426 @Override
6427 public boolean showStrictModeViolationDialog() {
6428 synchronized (mGlobalLock) {
6429 return mShowDialogs && !mSleeping && !mShuttingDown;
6430 }
6431 }
6432
6433 @Override
6434 public void showSystemReadyErrorDialogsIfNeeded() {
6435 synchronized (mGlobalLock) {
6436 try {
6437 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6438 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6439 + " data partition or your device will be unstable.");
6440 mUiHandler.post(() -> {
6441 if (mShowDialogs) {
6442 AlertDialog d = new BaseErrorDialog(mUiContext);
6443 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6444 d.setCancelable(false);
6445 d.setTitle(mUiContext.getText(R.string.android_system_label));
6446 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6447 d.setButton(DialogInterface.BUTTON_POSITIVE,
6448 mUiContext.getText(R.string.ok),
6449 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6450 d.show();
6451 }
6452 });
6453 }
6454 } catch (RemoteException e) {
6455 }
6456
6457 if (!Build.isBuildConsistent()) {
6458 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6459 mUiHandler.post(() -> {
6460 if (mShowDialogs) {
6461 AlertDialog d = new BaseErrorDialog(mUiContext);
6462 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6463 d.setCancelable(false);
6464 d.setTitle(mUiContext.getText(R.string.android_system_label));
6465 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6466 d.setButton(DialogInterface.BUTTON_POSITIVE,
6467 mUiContext.getText(R.string.ok),
6468 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6469 d.show();
6470 }
6471 });
6472 }
6473 }
6474 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006475
6476 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006477 public void onProcessMapped(int pid, WindowProcessController proc) {
6478 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006479 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006480 }
6481 }
6482
6483 @Override
6484 public void onProcessUnMapped(int pid) {
6485 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006486 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006487 }
6488 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006489
6490 @Override
6491 public void onPackageDataCleared(String name) {
6492 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006493 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006494 mAppWarnings.onPackageDataCleared(name);
6495 }
6496 }
6497
6498 @Override
6499 public void onPackageUninstalled(String name) {
6500 synchronized (mGlobalLock) {
6501 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006502 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006503 }
6504 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006505
6506 @Override
6507 public void onPackageAdded(String name, boolean replacing) {
6508 synchronized (mGlobalLock) {
6509 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6510 }
6511 }
6512
6513 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006514 public void onPackageReplaced(ApplicationInfo aInfo) {
6515 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006516 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006517 }
6518 }
6519
6520 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006521 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6522 synchronized (mGlobalLock) {
6523 return compatibilityInfoForPackageLocked(ai);
6524 }
6525 }
6526
Yunfan Chen75157d72018-07-27 14:47:21 +09006527 /**
6528 * Set the corresponding display information for the process global configuration. To be
6529 * called when we need to show IME on a different display.
6530 *
6531 * @param pid The process id associated with the IME window.
6532 * @param displayId The ID of the display showing the IME.
6533 */
6534 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006535 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006536 // Don't update process-level configuration for Multi-Client IME process since other
6537 // IMEs on other displays will also receive this configuration change due to IME
6538 // services use the same application config/context.
6539 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006540
Yunfan Chen75157d72018-07-27 14:47:21 +09006541 if (pid == MY_PID || pid < 0) {
6542 if (DEBUG_CONFIGURATION) {
6543 Slog.w(TAG,
6544 "Trying to update display configuration for system/invalid process.");
6545 }
6546 return;
6547 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006548 synchronized (mGlobalLock) {
6549 final ActivityDisplay activityDisplay =
6550 mRootActivityContainer.getActivityDisplay(displayId);
6551 if (activityDisplay == null) {
6552 // Call might come when display is not yet added or has been removed.
6553 if (DEBUG_CONFIGURATION) {
6554 Slog.w(TAG, "Trying to update display configuration for non-existing "
6555 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006556 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006557 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006558 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006559 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006560 if (process == null) {
6561 if (DEBUG_CONFIGURATION) {
6562 Slog.w(TAG, "Trying to update display configuration for invalid "
6563 + "process, pid=" + pid);
6564 }
6565 return;
6566 }
lumarkddc77fb2019-06-27 22:22:23 +08006567 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006568 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6569 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006570 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006571
6572 @Override
6573 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006574 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006575 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006576 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6577 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006578 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006579 }
6580 }
6581 }
6582
6583 @Override
6584 public void clearPendingResultForActivity(IBinder activityToken,
6585 WeakReference<PendingIntentRecord> pir) {
6586 synchronized (mGlobalLock) {
6587 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6588 if (r != null && r.pendingResults != null) {
6589 r.pendingResults.remove(pir);
6590 }
6591 }
6592 }
6593
6594 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006595 public ActivityTokens getTopActivityForTask(int taskId) {
6596 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006597 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6598 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006599 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6600 + " Requested task not found");
6601 return null;
6602 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006603 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006604 if (activity == null) {
6605 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6606 + " Requested activity not found");
6607 return null;
6608 }
6609 if (!activity.attachedToProcess()) {
6610 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6611 + activity);
6612 return null;
6613 }
6614 return new ActivityTokens(activity.appToken, activity.assistToken,
6615 activity.app.getThread());
6616 }
6617 }
6618
6619 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620 public IIntentSender getIntentSender(int type, String packageName,
6621 int callingUid, int userId, IBinder token, String resultWho,
6622 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6623 Bundle bOptions) {
6624 synchronized (mGlobalLock) {
6625 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6626 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6627 }
6628 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006629
6630 @Override
6631 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6632 synchronized (mGlobalLock) {
6633 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6634 if (r == null) {
6635 return null;
6636 }
6637 if (r.mServiceConnectionsHolder == null) {
6638 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6639 ActivityTaskManagerService.this, r);
6640 }
6641
6642 return r.mServiceConnectionsHolder;
6643 }
6644 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006645
6646 @Override
6647 public Intent getHomeIntent() {
6648 synchronized (mGlobalLock) {
6649 return ActivityTaskManagerService.this.getHomeIntent();
6650 }
6651 }
6652
6653 @Override
6654 public boolean startHomeActivity(int userId, String reason) {
6655 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006656 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006657 }
6658 }
6659
6660 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006661 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006662 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006663 synchronized (mGlobalLock) {
6664 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006665 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006666 }
Chilun8b1f1be2019-03-13 17:14:36 +08006667 }
6668
6669 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006670 public boolean startHomeOnAllDisplays(int userId, String reason) {
6671 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006672 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006673 }
6674 }
6675
Riddle Hsua0536432019-02-16 00:38:59 +08006676 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006677 @Override
6678 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006679 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680 if (mFactoryTest == FACTORY_TEST_OFF) {
6681 return false;
6682 }
6683 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6684 && wpc.mName.equals(mTopComponent.getPackageName())) {
6685 return true;
6686 }
6687 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6688 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6689 }
6690 }
6691
6692 @Override
6693 public void updateTopComponentForFactoryTest() {
6694 synchronized (mGlobalLock) {
6695 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6696 return;
6697 }
6698 final ResolveInfo ri = mContext.getPackageManager()
6699 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6700 final CharSequence errorMsg;
6701 if (ri != null) {
6702 final ActivityInfo ai = ri.activityInfo;
6703 final ApplicationInfo app = ai.applicationInfo;
6704 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6705 mTopAction = Intent.ACTION_FACTORY_TEST;
6706 mTopData = null;
6707 mTopComponent = new ComponentName(app.packageName, ai.name);
6708 errorMsg = null;
6709 } else {
6710 errorMsg = mContext.getResources().getText(
6711 com.android.internal.R.string.factorytest_not_system);
6712 }
6713 } else {
6714 errorMsg = mContext.getResources().getText(
6715 com.android.internal.R.string.factorytest_no_action);
6716 }
6717 if (errorMsg == null) {
6718 return;
6719 }
6720
6721 mTopAction = null;
6722 mTopData = null;
6723 mTopComponent = null;
6724 mUiHandler.post(() -> {
6725 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6726 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006727 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006728 });
6729 }
6730 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731
Riddle Hsua0536432019-02-16 00:38:59 +08006732 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006733 @Override
6734 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6735 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006736 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006738 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006739
6740 wpc.clearRecentTasks();
6741 wpc.clearActivities();
6742
6743 if (wpc.isInstrumenting()) {
6744 finishInstrumentationCallback.run();
6745 }
6746
Jorim Jaggid0752812018-10-16 16:07:20 +02006747 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006748 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006749 try {
6750 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6751 // If there was nothing to resume, and we are not already restarting
6752 // this process, but there is a visible activity that is hosted by the
6753 // process...then make sure all visible activities are running, taking
6754 // care of restarting this process.
6755 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6756 !PRESERVE_WINDOWS);
6757 }
6758 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006759 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 }
6762 }
6763 }
6764
6765 @Override
6766 public void closeSystemDialogs(String reason) {
6767 enforceNotIsolatedCaller("closeSystemDialogs");
6768
6769 final int pid = Binder.getCallingPid();
6770 final int uid = Binder.getCallingUid();
6771 final long origId = Binder.clearCallingIdentity();
6772 try {
6773 synchronized (mGlobalLock) {
6774 // Only allow this from foreground processes, so that background
6775 // applications can't abuse it to prevent system UI from being shown.
6776 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006777 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 if (!proc.isPerceptible()) {
6779 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6780 + " from background process " + proc);
6781 return;
6782 }
6783 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 mWindowManager.closeSystemDialogs(reason);
6785
Wale Ogunwaled32da472018-11-16 07:19:28 -08006786 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006788 // Call into AM outside the synchronized block.
6789 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 } finally {
6791 Binder.restoreCallingIdentity(origId);
6792 }
6793 }
6794
6795 @Override
6796 public void cleanupDisabledPackageComponents(
6797 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6798 synchronized (mGlobalLock) {
6799 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006802 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 mStackSupervisor.scheduleIdleLocked();
6804 }
6805
6806 // Clean-up disabled tasks
6807 getRecentTasks().cleanupDisabledPackageTasksLocked(
6808 packageName, disabledClasses, userId);
6809 }
6810 }
6811
6812 @Override
6813 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6814 int userId) {
6815 synchronized (mGlobalLock) {
6816
6817 boolean didSomething =
6818 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006819 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 null, doit, evenPersistent, userId);
6821 return didSomething;
6822 }
6823 }
6824
6825 @Override
6826 public void resumeTopActivities(boolean scheduleIdle) {
6827 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006828 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 if (scheduleIdle) {
6830 mStackSupervisor.scheduleIdleLocked();
6831 }
6832 }
6833 }
6834
Riddle Hsua0536432019-02-16 00:38:59 +08006835 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 @Override
6837 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006838 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6840 }
6841 }
6842
Riddle Hsua0536432019-02-16 00:38:59 +08006843 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 @Override
6845 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006846 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006847 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6848 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6849 }
6850 try {
6851 return mRootActivityContainer.attachApplication(wpc);
6852 } finally {
6853 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6854 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 }
6856 }
6857
6858 @Override
6859 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6860 try {
6861 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6862 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6863 }
6864 } catch (RemoteException ex) {
6865 throw new SecurityException("Fail to check is caller a privileged app", ex);
6866 }
6867
6868 synchronized (mGlobalLock) {
6869 final long ident = Binder.clearCallingIdentity();
6870 try {
6871 if (mAmInternal.shouldConfirmCredentials(userId)) {
6872 if (mKeyguardController.isKeyguardLocked()) {
6873 // Showing launcher to avoid user entering credential twice.
6874 startHomeActivity(currentUserId, "notifyLockedProfile");
6875 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006876 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006877 }
6878 } finally {
6879 Binder.restoreCallingIdentity(ident);
6880 }
6881 }
6882 }
6883
6884 @Override
6885 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6886 mAmInternal.enforceCallingPermission(
6887 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6888
6889 synchronized (mGlobalLock) {
6890 final long ident = Binder.clearCallingIdentity();
6891 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006892 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6893 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6896 UserHandle.CURRENT);
6897 } finally {
6898 Binder.restoreCallingIdentity(ident);
6899 }
6900 }
6901 }
6902
6903 @Override
6904 public void writeActivitiesToProto(ProtoOutputStream proto) {
6905 synchronized (mGlobalLock) {
6906 // The output proto of "activity --proto activities"
6907 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006908 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006909 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6910 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 }
6912 }
6913
6914 @Override
6915 public void saveANRState(String reason) {
6916 synchronized (mGlobalLock) {
6917 final StringWriter sw = new StringWriter();
6918 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6919 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6920 if (reason != null) {
6921 pw.println(" Reason: " + reason);
6922 }
6923 pw.println();
6924 getActivityStartController().dump(pw, " ", null);
6925 pw.println();
6926 pw.println("-------------------------------------------------------------------------------");
6927 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6928 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6929 "" /* header */);
6930 pw.println();
6931 pw.close();
6932
6933 mLastANRState = sw.toString();
6934 }
6935 }
6936
6937 @Override
6938 public void clearSavedANRState() {
6939 synchronized (mGlobalLock) {
6940 mLastANRState = null;
6941 }
6942 }
6943
6944 @Override
6945 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6946 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6947 synchronized (mGlobalLock) {
6948 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6949 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6950 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6951 dumpLastANRLocked(pw);
6952 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6953 dumpLastANRTracesLocked(pw);
6954 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6955 dumpActivityStarterLocked(pw, dumpPackage);
6956 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6957 dumpActivityContainersLocked(pw);
6958 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6959 if (getRecentTasks() != null) {
6960 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6961 }
6962 }
6963 }
6964 }
6965
6966 @Override
6967 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6968 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6969 int wakefulness) {
6970 synchronized (mGlobalLock) {
6971 if (mHomeProcess != null && (dumpPackage == null
6972 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6973 if (needSep) {
6974 pw.println();
6975 needSep = false;
6976 }
6977 pw.println(" mHomeProcess: " + mHomeProcess);
6978 }
6979 if (mPreviousProcess != null && (dumpPackage == null
6980 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6981 if (needSep) {
6982 pw.println();
6983 needSep = false;
6984 }
6985 pw.println(" mPreviousProcess: " + mPreviousProcess);
6986 }
6987 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6988 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6989 StringBuilder sb = new StringBuilder(128);
6990 sb.append(" mPreviousProcessVisibleTime: ");
6991 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6992 pw.println(sb);
6993 }
6994 if (mHeavyWeightProcess != null && (dumpPackage == null
6995 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6996 if (needSep) {
6997 pw.println();
6998 needSep = false;
6999 }
7000 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7001 }
7002 if (dumpPackage == null) {
7003 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007004 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007005 }
7006 if (dumpAll) {
7007 if (dumpPackage == null) {
7008 pw.println(" mConfigWillChange: "
7009 + getTopDisplayFocusedStack().mConfigWillChange);
7010 }
7011 if (mCompatModePackages.getPackages().size() > 0) {
7012 boolean printed = false;
7013 for (Map.Entry<String, Integer> entry
7014 : mCompatModePackages.getPackages().entrySet()) {
7015 String pkg = entry.getKey();
7016 int mode = entry.getValue();
7017 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7018 continue;
7019 }
7020 if (!printed) {
7021 pw.println(" mScreenCompatPackages:");
7022 printed = true;
7023 }
7024 pw.println(" " + pkg + ": " + mode);
7025 }
7026 }
7027 }
7028
7029 if (dumpPackage == null) {
7030 pw.println(" mWakefulness="
7031 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007032 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 if (mRunningVoice != null) {
7034 pw.println(" mRunningVoice=" + mRunningVoice);
7035 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7036 }
7037 pw.println(" mSleeping=" + mSleeping);
7038 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7039 pw.println(" mVrController=" + mVrController);
7040 }
7041 if (mCurAppTimeTracker != null) {
7042 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7043 }
7044 if (mAllowAppSwitchUids.size() > 0) {
7045 boolean printed = false;
7046 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7047 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7048 for (int j = 0; j < types.size(); j++) {
7049 if (dumpPackage == null ||
7050 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7051 if (needSep) {
7052 pw.println();
7053 needSep = false;
7054 }
7055 if (!printed) {
7056 pw.println(" mAllowAppSwitchUids:");
7057 printed = true;
7058 }
7059 pw.print(" User ");
7060 pw.print(mAllowAppSwitchUids.keyAt(i));
7061 pw.print(": Type ");
7062 pw.print(types.keyAt(j));
7063 pw.print(" = ");
7064 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7065 pw.println();
7066 }
7067 }
7068 }
7069 }
7070 if (dumpPackage == null) {
7071 if (mController != null) {
7072 pw.println(" mController=" + mController
7073 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7074 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007075 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7076 pw.println(" mLaunchingActivityWakeLock="
7077 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007078 }
7079
7080 return needSep;
7081 }
7082 }
7083
7084 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007085 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7086 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 synchronized (mGlobalLock) {
7088 if (dumpPackage == null) {
7089 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7090 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007091 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7092 if (mRunningVoice != null) {
7093 final long vrToken = proto.start(
7094 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7095 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7096 mRunningVoice.toString());
7097 mVoiceWakeLock.writeToProto(
7098 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7099 proto.end(vrToken);
7100 }
7101 mVrController.writeToProto(proto,
7102 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007103 if (mController != null) {
7104 final long token = proto.start(CONTROLLER);
7105 proto.write(CONTROLLER, mController.toString());
7106 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7107 proto.end(token);
7108 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007109 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7110 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7111 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 }
7113
7114 if (mHomeProcess != null && (dumpPackage == null
7115 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007116 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007117 }
7118
7119 if (mPreviousProcess != null && (dumpPackage == null
7120 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007121 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7123 }
7124
7125 if (mHeavyWeightProcess != null && (dumpPackage == null
7126 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007127 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007128 }
7129
7130 for (Map.Entry<String, Integer> entry
7131 : mCompatModePackages.getPackages().entrySet()) {
7132 String pkg = entry.getKey();
7133 int mode = entry.getValue();
7134 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7135 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7136 proto.write(PACKAGE, pkg);
7137 proto.write(MODE, mode);
7138 proto.end(compatToken);
7139 }
7140 }
7141
7142 if (mCurAppTimeTracker != null) {
7143 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7144 }
7145
7146 }
7147 }
7148
7149 @Override
7150 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7151 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7152 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007153 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7154 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 }
7156
7157 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007158 public void dumpForOom(PrintWriter pw) {
7159 synchronized (mGlobalLock) {
7160 pw.println(" mHomeProcess: " + mHomeProcess);
7161 pw.println(" mPreviousProcess: " + mPreviousProcess);
7162 if (mHeavyWeightProcess != null) {
7163 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7164 }
7165 }
7166 }
7167
7168 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 public boolean canGcNow() {
7170 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007171 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007172 }
7173 }
7174
Riddle Hsua0536432019-02-16 00:38:59 +08007175 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007176 @Override
7177 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007178 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007179 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 return top != null ? top.app : null;
7181 }
7182 }
7183
Riddle Hsua0536432019-02-16 00:38:59 +08007184 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007185 @Override
7186 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007187 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007188 if (mRootActivityContainer != null) {
7189 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 }
7191 }
7192 }
7193
7194 @Override
7195 public void scheduleDestroyAllActivities(String reason) {
7196 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007197 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007198 }
7199 }
7200
7201 @Override
7202 public void removeUser(int userId) {
7203 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007204 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007205 }
7206 }
7207
7208 @Override
7209 public boolean switchUser(int userId, UserState userState) {
7210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007211 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 }
7213 }
7214
7215 @Override
7216 public void onHandleAppCrash(WindowProcessController wpc) {
7217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007218 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 }
7220 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007221
7222 @Override
7223 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7224 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007225 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007226 }
7227 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007228
Riddle Hsua0536432019-02-16 00:38:59 +08007229 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007230 @Override
7231 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007232 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007233 }
7234
Riddle Hsua0536432019-02-16 00:38:59 +08007235 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007236 @Override
7237 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007238 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007239 }
7240
Riddle Hsua0536432019-02-16 00:38:59 +08007241 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007242 @Override
7243 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007244 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007245 }
7246
Riddle Hsua0536432019-02-16 00:38:59 +08007247 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007248 @Override
7249 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007250 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007251 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007252
7253 @Override
7254 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007255 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007256 mPendingTempWhitelist.put(uid, tag);
7257 }
7258 }
7259
7260 @Override
7261 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007262 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007263 mPendingTempWhitelist.remove(uid);
7264 }
7265 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007266
7267 @Override
7268 public boolean handleAppCrashInActivityController(String processName, int pid,
7269 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7270 Runnable killCrashingAppCallback) {
7271 synchronized (mGlobalLock) {
7272 if (mController == null) {
7273 return false;
7274 }
7275
7276 try {
7277 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7278 stackTrace)) {
7279 killCrashingAppCallback.run();
7280 return true;
7281 }
7282 } catch (RemoteException e) {
7283 mController = null;
7284 Watchdog.getInstance().setActivityController(null);
7285 }
7286 return false;
7287 }
7288 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007289
7290 @Override
7291 public void removeRecentTasksByPackageName(String packageName, int userId) {
7292 synchronized (mGlobalLock) {
7293 mRecentTasks.removeTasksByPackageName(packageName, userId);
7294 }
7295 }
7296
7297 @Override
7298 public void cleanupRecentTasksForUser(int userId) {
7299 synchronized (mGlobalLock) {
7300 mRecentTasks.cleanupLocked(userId);
7301 }
7302 }
7303
7304 @Override
7305 public void loadRecentTasksForUser(int userId) {
7306 synchronized (mGlobalLock) {
7307 mRecentTasks.loadUserRecentsLocked(userId);
7308 }
7309 }
7310
7311 @Override
7312 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7313 synchronized (mGlobalLock) {
7314 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7315 }
7316 }
7317
7318 @Override
7319 public void flushRecentTasks() {
7320 mRecentTasks.flush();
7321 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007322
7323 @Override
7324 public WindowProcessController getHomeProcess() {
7325 synchronized (mGlobalLock) {
7326 return mHomeProcess;
7327 }
7328 }
7329
7330 @Override
7331 public WindowProcessController getPreviousProcess() {
7332 synchronized (mGlobalLock) {
7333 return mPreviousProcess;
7334 }
7335 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007336
7337 @Override
7338 public void clearLockedTasks(String reason) {
7339 synchronized (mGlobalLock) {
7340 getLockTaskController().clearLockedTasks(reason);
7341 }
7342 }
7343
7344 @Override
7345 public void updateUserConfiguration() {
7346 synchronized (mGlobalLock) {
7347 final Configuration configuration = new Configuration(getGlobalConfiguration());
7348 final int currentUserId = mAmInternal.getCurrentUserId();
7349 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7350 configuration, currentUserId, Settings.System.canWrite(mContext));
7351 updateConfigurationLocked(configuration, null /* starting */,
7352 false /* initLocale */, false /* persistent */, currentUserId,
7353 false /* deferResume */);
7354 }
7355 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007356
7357 @Override
7358 public boolean canShowErrorDialogs() {
7359 synchronized (mGlobalLock) {
7360 return mShowDialogs && !mSleeping && !mShuttingDown
7361 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7362 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7363 mAmInternal.getCurrentUserId())
7364 && !(UserManager.isDeviceInDemoMode(mContext)
7365 && mAmInternal.getCurrentUser().isDemo());
7366 }
7367 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007368
7369 @Override
7370 public void setProfileApp(String profileApp) {
7371 synchronized (mGlobalLock) {
7372 mProfileApp = profileApp;
7373 }
7374 }
7375
7376 @Override
7377 public void setProfileProc(WindowProcessController wpc) {
7378 synchronized (mGlobalLock) {
7379 mProfileProc = wpc;
7380 }
7381 }
7382
7383 @Override
7384 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7385 synchronized (mGlobalLock) {
7386 mProfilerInfo = profilerInfo;
7387 }
7388 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007389
7390 @Override
7391 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7392 synchronized (mGlobalLock) {
7393 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7394 }
7395 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007396
7397 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007398 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7399 boolean reducedResolution) {
7400 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7401 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007402 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007403
7404 @Override
7405 public boolean isUidForeground(int uid) {
7406 synchronized (mGlobalLock) {
7407 return ActivityTaskManagerService.this.isUidForeground(uid);
7408 }
7409 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007410
7411 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007412 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007413 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007414 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007415 }
7416 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007417
7418 @Override
7419 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007420 // Translate package names into UIDs
7421 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007422 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007423 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7424 if (uid >= 0) {
7425 result.add(uid);
7426 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007427 }
7428 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007429 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007430 }
7431 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007432 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007433}