blob: 222f26edaf5d9437c637e54bf6da7ca1cb5fe4e4 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800126import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700218import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.EventLog;
220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700230import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700249import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700250import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700251import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.LocalServices;
253import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700254import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800255import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700257import com.android.server.am.ActivityManagerService;
258import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
259import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
260import com.android.server.am.AppTimeTracker;
261import com.android.server.am.BaseErrorDialog;
262import com.android.server.am.EventLogTags;
263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900266import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700293import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800357 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800358 @VisibleForTesting
359 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 PowerManagerInternal mPowerManagerInternal;
361 private UsageStatsManagerInternal mUsageStatsInternal;
362
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700363 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 IntentFirewall mIntentFirewall;
365
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700366 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800367 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700369 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
371 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
372 *
373 * @see WindowManagerThreadPriorityBooster
374 */
375 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800377 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700378 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700379 private UserManagerService mUserManager;
380 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700381 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800382 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700383 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** All processes currently running that might have a window organized by name. */
385 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100386 /** All processes we currently have running mapped by pid and uid */
387 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** This is the process holding what we currently consider to be the "home" activity. */
389 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700390 /** The currently running heavy-weight process, if any. */
391 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700392 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /**
394 * This is the process holding the activity the user last visited that is in a different process
395 * from the one they are currently in.
396 */
397 WindowProcessController mPreviousProcess;
398 /** The time at which the previous process was last visible. */
399 long mPreviousProcessVisibleTime;
400
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700401 /** List of intents that were used to start the most recent tasks. */
402 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700403 /** State of external calls telling us if the device is awake or asleep. */
404 private boolean mKeyguardShown = false;
405
406 // Wrapper around VoiceInteractionServiceManager
407 private AssistUtils mAssistUtils;
408
409 // VoiceInteraction session ID that changes for each new request except when
410 // being called for multi-window assist in a single session.
411 private int mViSessionId = 1000;
412
413 // How long to wait in getAssistContextExtras for the activity and foreground services
414 // to respond with the result.
415 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
416
417 // How long top wait when going through the modern assist (which doesn't need to block
418 // on getting this result before starting to launch its UI).
419 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
420
421 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
422 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
423
Alison Cichowlas3e340502018-08-07 17:15:01 -0400424 // Permission tokens are used to temporarily granted a trusted app the ability to call
425 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
426 // showing any appropriate error messages to the user.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
428 10 * MINUTE_IN_MILLIS;
429
430 // How long before the service actually expires a token. This is slightly longer than
431 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
432 // expiration exception.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
434 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
435
436 // How long the service will remember expired tokens, for the purpose of providing error
437 // messaging when a client uses an expired token.
438 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
439 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
440
441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700467 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700575 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
Riddle Hsua0022cd2019-09-09 21:12:41 +0800603 @Retention(RetentionPolicy.SOURCE)
604 @IntDef({
605 LAYOUT_REASON_CONFIG_CHANGED,
606 LAYOUT_REASON_VISIBILITY_CHANGED,
607 })
608 @interface LayoutReason {}
609 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
610 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
611
612 /** The reasons to perform surface placement. */
613 @LayoutReason
614 private int mLayoutReasons;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
617 // automatically. Important for devices without direct input devices.
618 private boolean mShowDialogs = true;
619
620 /** Set if we are shutting down the system, similar to sleeping. */
621 boolean mShuttingDown = false;
622
623 /**
624 * We want to hold a wake lock while running a voice interaction session, since
625 * this may happen with the screen off and we need to keep the CPU running to
626 * be able to continue to interact with the user.
627 */
628 PowerManager.WakeLock mVoiceWakeLock;
629
630 /**
631 * Set while we are running a voice interaction. This overrides sleeping while it is active.
632 */
633 IVoiceInteractionSession mRunningVoice;
634
635 /**
636 * The last resumed activity. This is identical to the current resumed activity most
637 * of the time but could be different when we're pausing one activity before we resume
638 * another activity.
639 */
640 ActivityRecord mLastResumedActivity;
641
642 /**
643 * The activity that is currently being traced as the active resumed activity.
644 *
645 * @see #updateResumedAppTrace
646 */
647 private @Nullable ActivityRecord mTracedResumedActivity;
648
649 /** If non-null, we are tracking the time the user spends in the currently focused app. */
650 AppTimeTracker mCurAppTimeTracker;
651
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700652 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700653
Wale Ogunwale53783742018-09-16 10:21:51 -0700654 /**
655 * Packages that the user has asked to have run in screen size
656 * compatibility mode instead of filling the screen.
657 */
658 CompatModePackages mCompatModePackages;
659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private FontScaleSettingObserver mFontScaleSettingObserver;
661
Ricky Wai96f5c352019-04-10 18:40:17 +0100662 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private final class FontScaleSettingObserver extends ContentObserver {
665 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
666 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
667
668 public FontScaleSettingObserver() {
669 super(mH);
670 final ContentResolver resolver = mContext.getContentResolver();
671 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
672 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
673 UserHandle.USER_ALL);
674 }
675
676 @Override
677 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
678 if (mFontScaleUri.equals(uri)) {
679 updateFontScaleIfNeeded(userId);
680 } else if (mHideErrorDialogsUri.equals(uri)) {
681 synchronized (mGlobalLock) {
682 updateShouldShowDialogsLocked(getGlobalConfiguration());
683 }
684 }
685 }
686 }
687
Riddle Hsua0536432019-02-16 00:38:59 +0800688 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
689 @Target(ElementType.METHOD)
690 @Retention(RetentionPolicy.SOURCE)
691 @interface HotPath {
692 int NONE = 0;
693 int OOM_ADJUSTMENT = 1;
694 int LRU_UPDATE = 2;
695 int PROCESS_CHANGE = 3;
696 int caller() default NONE;
697 }
698
Charles Chen8d98dd22018-12-26 17:36:54 +0800699 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
700 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700701 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700702 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700703 mSystemThread = ActivityThread.currentActivityThread();
704 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700705 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800706 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700707 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700708 }
709
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700710 public void onSystemReady() {
711 synchronized (mGlobalLock) {
712 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
713 PackageManager.FEATURE_CANT_SAVE_STATE);
714 mAssistUtils = new AssistUtils(mContext);
715 mVrController.onSystemReady();
716 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700717 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700719 }
720
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700721 public void onInitPowerManagement() {
722 synchronized (mGlobalLock) {
723 mStackSupervisor.initPowerManagement();
724 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
725 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
726 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
727 mVoiceWakeLock.setReferenceCounted(false);
728 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700729 }
730
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700732 mFontScaleSettingObserver = new FontScaleSettingObserver();
733 }
734
Wale Ogunwale59507092018-10-29 09:00:30 -0700735 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700736 final boolean freeformWindowManagement =
737 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
738 || Settings.Global.getInt(
739 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
740
741 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
742 final boolean supportsPictureInPicture = supportsMultiWindow &&
743 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
744 final boolean supportsSplitScreenMultiWindow =
745 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
746 final boolean supportsMultiDisplay = mContext.getPackageManager()
747 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700748 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
749 final boolean forceResizable = Settings.Global.getInt(
750 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700751 final boolean sizeCompatFreeform = Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753
754 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900755 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756
757 final Configuration configuration = new Configuration();
758 Settings.System.getConfiguration(resolver, configuration);
759 if (forceRtl) {
760 // This will take care of setting the correct layout direction flags
761 configuration.setLayoutDirection(configuration.locale);
762 }
763
764 synchronized (mGlobalLock) {
765 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700766 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767 final boolean multiWindowFormEnabled = freeformWindowManagement
768 || supportsSplitScreenMultiWindow
769 || supportsPictureInPicture
770 || supportsMultiDisplay;
771 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
772 mSupportsMultiWindow = true;
773 mSupportsFreeformWindowManagement = freeformWindowManagement;
774 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
775 mSupportsPictureInPicture = supportsPictureInPicture;
776 mSupportsMultiDisplay = supportsMultiDisplay;
777 } else {
778 mSupportsMultiWindow = false;
779 mSupportsFreeformWindowManagement = false;
780 mSupportsSplitScreenMultiWindow = false;
781 mSupportsPictureInPicture = false;
782 mSupportsMultiDisplay = false;
783 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700784 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700785 // This happens before any activities are started, so we can change global configuration
786 // in-place.
787 updateConfigurationLocked(configuration, null, true);
788 final Configuration globalConfig = getGlobalConfiguration();
789 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
790
791 // Load resources only after the current configuration has been set.
792 final Resources res = mContext.getResources();
793 mThumbnailWidth = res.getDimensionPixelSize(
794 com.android.internal.R.dimen.thumbnail_width);
795 mThumbnailHeight = res.getDimensionPixelSize(
796 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 }
798 }
799
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800800 public WindowManagerGlobalLock getGlobalLock() {
801 return mGlobalLock;
802 }
803
Yunfan Chen585f2932019-01-29 16:04:45 +0900804 /** For test purpose only. */
805 @VisibleForTesting
806 public ActivityTaskManagerInternal getAtmInternal() {
807 return mInternal;
808 }
809
Riddle Hsud93a6c42018-11-29 21:50:06 +0800810 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
811 Looper looper) {
812 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700814 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700815 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800816 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700817 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700818 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
820 mTempConfig.setToDefaults();
821 mTempConfig.setLocales(LocaleList.getDefault());
822 mConfigurationSeq = mTempConfig.seq = 1;
823 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800824 mRootActivityContainer = new RootActivityContainer(this);
825 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700826
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700828 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700829 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700831 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700832 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700833 mKeyguardController = mStackSupervisor.getKeyguardController();
834 }
835
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700836 public void onActivityManagerInternalAdded() {
837 synchronized (mGlobalLock) {
838 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
839 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
840 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700841 }
842
Yunfan Chen75157d72018-07-27 14:47:21 +0900843 int increaseConfigurationSeqLocked() {
844 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
845 return mConfigurationSeq;
846 }
847
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700848 protected ActivityStackSupervisor createStackSupervisor() {
849 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
850 supervisor.initialize();
851 return supervisor;
852 }
853
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800854 protected AppWarnings createAppWarnings(
855 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
856 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
857 }
858
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 public void setWindowManager(WindowManagerService wm) {
860 synchronized (mGlobalLock) {
861 mWindowManager = wm;
862 mLockTaskController.setWindowManager(wm);
863 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800864 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700865 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700866 }
867
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700868 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
869 synchronized (mGlobalLock) {
870 mUsageStatsInternal = usageStatsManager;
871 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700872 }
873
Wale Ogunwalef6733932018-06-27 05:14:34 -0700874 UserManagerService getUserManager() {
875 if (mUserManager == null) {
876 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
877 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
878 }
879 return mUserManager;
880 }
881
882 AppOpsService getAppOpsService() {
883 if (mAppOpsService == null) {
884 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
885 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
886 }
887 return mAppOpsService;
888 }
889
890 boolean hasUserRestriction(String restriction, int userId) {
891 return getUserManager().hasUserRestriction(restriction, userId);
892 }
893
Michal Karpinski15486842019-04-25 17:33:42 +0100894 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
895 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700896 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100897 if (mode == AppOpsManager.MODE_DEFAULT) {
898 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
899 == PERMISSION_GRANTED;
900 }
901 return mode == AppOpsManager.MODE_ALLOWED;
902 }
903
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700904 @VisibleForTesting
905 protected void setRecentTasks(RecentTasks recentTasks) {
906 mRecentTasks = recentTasks;
907 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700908 }
909
910 RecentTasks getRecentTasks() {
911 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700912 }
913
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700914 ClientLifecycleManager getLifecycleManager() {
915 return mLifecycleManager;
916 }
917
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700918 ActivityStartController getActivityStartController() {
919 return mActivityStartController;
920 }
921
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700922 TaskChangeNotificationController getTaskChangeNotificationController() {
923 return mTaskChangeNotificationController;
924 }
925
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700926 LockTaskController getLockTaskController() {
927 return mLockTaskController;
928 }
929
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 /**
931 * Return the global configuration used by the process corresponding to the input pid. This is
932 * usually the global configuration with some overrides specific to that process.
933 */
934 Configuration getGlobalConfigurationForCallingPid() {
935 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800936 return getGlobalConfigurationForPid(pid);
937 }
938
939 /**
940 * Return the global configuration used by the process corresponding to the given pid.
941 */
942 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900943 if (pid == MY_PID || pid < 0) {
944 return getGlobalConfiguration();
945 }
946 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100947 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900948 return app != null ? app.getConfiguration() : getGlobalConfiguration();
949 }
950 }
951
952 /**
953 * Return the device configuration info used by the process corresponding to the input pid.
954 * The value is consistent with the global configuration for the process.
955 */
956 @Override
957 public ConfigurationInfo getDeviceConfigurationInfo() {
958 ConfigurationInfo config = new ConfigurationInfo();
959 synchronized (mGlobalLock) {
960 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
961 config.reqTouchScreen = globalConfig.touchscreen;
962 config.reqKeyboardType = globalConfig.keyboard;
963 config.reqNavigation = globalConfig.navigation;
964 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
965 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
966 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
967 }
968 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
969 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
970 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
971 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700972 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900973 }
974 return config;
975 }
976
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700977 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700978 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700979 }
980
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700981 public static final class Lifecycle extends SystemService {
982 private final ActivityTaskManagerService mService;
983
984 public Lifecycle(Context context) {
985 super(context);
986 mService = new ActivityTaskManagerService(context);
987 }
988
989 @Override
990 public void onStart() {
991 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700992 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 }
994
Garfield Tan891146c2018-10-09 12:14:00 -0700995 @Override
996 public void onUnlockUser(int userId) {
997 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800998 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700999 }
1000 }
1001
1002 @Override
1003 public void onCleanupUser(int userId) {
1004 synchronized (mService.getGlobalLock()) {
1005 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1006 }
1007 }
1008
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001009 public ActivityTaskManagerService getService() {
1010 return mService;
1011 }
1012 }
1013
1014 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 public final int startActivity(IApplicationThread caller, String callingPackage,
1016 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1017 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1018 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1019 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1020 UserHandle.getCallingUserId());
1021 }
1022
1023 @Override
1024 public final int startActivities(IApplicationThread caller, String callingPackage,
1025 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1026 int userId) {
1027 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001028 enforceNotIsolatedCaller(reason);
1029 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001031 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1032 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1033 reason, null /* originatingPendingIntent */,
1034 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 }
1036
1037 @Override
1038 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1039 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1040 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1041 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1042 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1043 true /*validateIncomingUser*/);
1044 }
1045
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001046 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1048 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1049 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001050 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001052 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001053 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1054
1055 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001056 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 .setCaller(caller)
1058 .setCallingPackage(callingPackage)
1059 .setResolvedType(resolvedType)
1060 .setResultTo(resultTo)
1061 .setResultWho(resultWho)
1062 .setRequestCode(requestCode)
1063 .setStartFlags(startFlags)
1064 .setProfilerInfo(profilerInfo)
1065 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001066 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 .execute();
1068
1069 }
1070
1071 @Override
1072 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1073 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001074 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1075 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 // Refuse possible leaked file descriptors
1077 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1078 throw new IllegalArgumentException("File descriptors passed in Intent");
1079 }
1080
1081 if (!(target instanceof PendingIntentRecord)) {
1082 throw new IllegalArgumentException("Bad PendingIntent object");
1083 }
1084
1085 PendingIntentRecord pir = (PendingIntentRecord)target;
1086
1087 synchronized (mGlobalLock) {
1088 // If this is coming from the currently resumed activity, it is
1089 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001090 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 if (stack.mResumedActivity != null &&
1092 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001094 }
1095 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001096 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 }
1099
1100 @Override
1101 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1102 Bundle bOptions) {
1103 // Refuse possible leaked file descriptors
1104 if (intent != null && intent.hasFileDescriptors()) {
1105 throw new IllegalArgumentException("File descriptors passed in Intent");
1106 }
1107 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1108
1109 synchronized (mGlobalLock) {
1110 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1111 if (r == null) {
1112 SafeActivityOptions.abort(options);
1113 return false;
1114 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001115 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 // The caller is not running... d'oh!
1117 SafeActivityOptions.abort(options);
1118 return false;
1119 }
1120 intent = new Intent(intent);
1121 // The caller is not allowed to change the data.
1122 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1123 // And we are resetting to find the next component...
1124 intent.setComponent(null);
1125
1126 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1127
1128 ActivityInfo aInfo = null;
1129 try {
1130 List<ResolveInfo> resolves =
1131 AppGlobals.getPackageManager().queryIntentActivities(
1132 intent, r.resolvedType,
1133 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1134 UserHandle.getCallingUserId()).getList();
1135
1136 // Look for the original activity in the list...
1137 final int N = resolves != null ? resolves.size() : 0;
1138 for (int i=0; i<N; i++) {
1139 ResolveInfo rInfo = resolves.get(i);
1140 if (rInfo.activityInfo.packageName.equals(r.packageName)
1141 && rInfo.activityInfo.name.equals(r.info.name)) {
1142 // We found the current one... the next matching is
1143 // after it.
1144 i++;
1145 if (i<N) {
1146 aInfo = resolves.get(i).activityInfo;
1147 }
1148 if (debug) {
1149 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1150 + "/" + r.info.name);
1151 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1152 ? "null" : aInfo.packageName + "/" + aInfo.name));
1153 }
1154 break;
1155 }
1156 }
1157 } catch (RemoteException e) {
1158 }
1159
1160 if (aInfo == null) {
1161 // Nobody who is next!
1162 SafeActivityOptions.abort(options);
1163 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1164 return false;
1165 }
1166
1167 intent.setComponent(new ComponentName(
1168 aInfo.applicationInfo.packageName, aInfo.name));
1169 intent.setFlags(intent.getFlags()&~(
1170 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1171 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1172 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1173 FLAG_ACTIVITY_NEW_TASK));
1174
1175 // Okay now we need to start the new activity, replacing the currently running activity.
1176 // This is a little tricky because we want to start the new one as if the current one is
1177 // finished, but not finish the current one first so that there is no flicker.
1178 // And thus...
1179 final boolean wasFinishing = r.finishing;
1180 r.finishing = true;
1181
1182 // Propagate reply information over to the new activity.
1183 final ActivityRecord resultTo = r.resultTo;
1184 final String resultWho = r.resultWho;
1185 final int requestCode = r.requestCode;
1186 r.resultTo = null;
1187 if (resultTo != null) {
1188 resultTo.removeResultsLocked(r, resultWho, requestCode);
1189 }
1190
1191 final long origId = Binder.clearCallingIdentity();
1192 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001195 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001196 .setResolvedType(r.resolvedType)
1197 .setActivityInfo(aInfo)
1198 .setResultTo(resultTo != null ? resultTo.appToken : null)
1199 .setResultWho(resultWho)
1200 .setRequestCode(requestCode)
1201 .setCallingPid(-1)
1202 .setCallingUid(r.launchedFromUid)
1203 .setCallingPackage(r.launchedFromPackage)
1204 .setRealCallingPid(-1)
1205 .setRealCallingUid(r.launchedFromUid)
1206 .setActivityOptions(options)
1207 .execute();
1208 Binder.restoreCallingIdentity(origId);
1209
1210 r.finishing = wasFinishing;
1211 if (res != ActivityManager.START_SUCCESS) {
1212 return false;
1213 }
1214 return true;
1215 }
1216 }
1217
1218 @Override
1219 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1220 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1221 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1222 final WaitResult res = new WaitResult();
1223 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001224 enforceNotIsolatedCaller("startActivityAndWait");
1225 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1226 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001228 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001229 .setCaller(caller)
1230 .setCallingPackage(callingPackage)
1231 .setResolvedType(resolvedType)
1232 .setResultTo(resultTo)
1233 .setResultWho(resultWho)
1234 .setRequestCode(requestCode)
1235 .setStartFlags(startFlags)
1236 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001237 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .setProfilerInfo(profilerInfo)
1239 .setWaitResult(res)
1240 .execute();
1241 }
1242 return res;
1243 }
1244
1245 @Override
1246 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1247 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1248 int startFlags, Configuration config, Bundle bOptions, int userId) {
1249 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001250 enforceNotIsolatedCaller("startActivityWithConfig");
1251 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1252 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001253 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001254 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 .setCaller(caller)
1256 .setCallingPackage(callingPackage)
1257 .setResolvedType(resolvedType)
1258 .setResultTo(resultTo)
1259 .setResultWho(resultWho)
1260 .setRequestCode(requestCode)
1261 .setStartFlags(startFlags)
1262 .setGlobalConfiguration(config)
1263 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001264 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001265 .execute();
1266 }
1267 }
1268
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269
1270 @Override
1271 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1272 int callingUid = Binder.getCallingUid();
1273 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1274 throw new SecurityException("Only the system process can request a permission token, "
1275 + "received request from uid: " + callingUid);
1276 }
1277 IBinder permissionToken = new Binder();
1278 synchronized (mGlobalLock) {
1279 mStartActivitySources.put(permissionToken, delegatorToken);
1280 }
1281
1282 Message expireMsg = PooledLambda.obtainMessage(
1283 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1284 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1285
1286 Message forgetMsg = PooledLambda.obtainMessage(
1287 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1288 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1289
1290 return permissionToken;
1291 }
1292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 @Override
1294 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1295 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1297 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 // permission grants) as any app that may launch one of your own activities. So we only
1300 // allow this in two cases:
1301 // 1) The caller is an activity that is part of the core framework, and then only when it
1302 // is running as the system.
1303 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1304 // can only be requested by a system activity, which may then delegate this call to
1305 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 final ActivityRecord sourceRecord;
1307 final int targetUid;
1308 final String targetPackage;
1309 final boolean isResolver;
1310 synchronized (mGlobalLock) {
1311 if (resultTo == null) {
1312 throw new SecurityException("Must be called from an activity");
1313 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001314 final IBinder sourceToken;
1315 if (permissionToken != null) {
1316 // To even attempt to use a permissionToken, an app must also have this signature
1317 // permission.
1318 mAmInternal.enforceCallingPermission(
1319 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1320 "startActivityAsCaller");
1321 // If called with a permissionToken, we want the sourceRecord from the delegator
1322 // activity that requested this token.
1323 sourceToken = mStartActivitySources.remove(permissionToken);
1324 if (sourceToken == null) {
1325 // Invalid permissionToken, check if it recently expired.
1326 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1327 throw new SecurityException("Called with expired permission token: "
1328 + permissionToken);
1329 } else {
1330 throw new SecurityException("Called with invalid permission token: "
1331 + permissionToken);
1332 }
1333 }
1334 } else {
1335 // This method was called directly by the source.
1336 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338
Wale Ogunwaled32da472018-11-16 07:19:28 -08001339 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001340 if (sourceRecord == null) {
1341 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
1343 if (sourceRecord.app == null) {
1344 throw new SecurityException("Called without a process attached to activity");
1345 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001346
1347 // Whether called directly or from a delegate, the source activity must be from the
1348 // android package.
1349 if (!sourceRecord.info.packageName.equals("android")) {
1350 throw new SecurityException("Must be called from an activity that is "
1351 + "declared in the android package");
1352 }
1353
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001354 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001355 // This is still okay, as long as this activity is running under the
1356 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001357 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001359 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 + " must be system uid or original calling uid "
1361 + sourceRecord.launchedFromUid);
1362 }
1363 }
1364 if (ignoreTargetSecurity) {
1365 if (intent.getComponent() == null) {
1366 throw new SecurityException(
1367 "Component must be specified with ignoreTargetSecurity");
1368 }
1369 if (intent.getSelector() != null) {
1370 throw new SecurityException(
1371 "Selector not allowed with ignoreTargetSecurity");
1372 }
1373 }
1374 targetUid = sourceRecord.launchedFromUid;
1375 targetPackage = sourceRecord.launchedFromPackage;
1376 isResolver = sourceRecord.isResolverOrChildActivity();
1377 }
1378
1379 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001380 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 }
1382
1383 // TODO: Switch to user app stacks here.
1384 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001385 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 .setCallingUid(targetUid)
1387 .setCallingPackage(targetPackage)
1388 .setResolvedType(resolvedType)
1389 .setResultTo(resultTo)
1390 .setResultWho(resultWho)
1391 .setRequestCode(requestCode)
1392 .setStartFlags(startFlags)
1393 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001394 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1396 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001397 // The target may well be in the background, which would normally prevent it
1398 // from starting an activity. Here we definitely want the start to succeed.
1399 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .execute();
1401 } catch (SecurityException e) {
1402 // XXX need to figure out how to propagate to original app.
1403 // A SecurityException here is generally actually a fault of the original
1404 // calling activity (such as a fairly granting permissions), so propagate it
1405 // back to them.
1406 /*
1407 StringBuilder msg = new StringBuilder();
1408 msg.append("While launching");
1409 msg.append(intent.toString());
1410 msg.append(": ");
1411 msg.append(e.getMessage());
1412 */
1413 throw e;
1414 }
1415 }
1416
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001417 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1418 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1419 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1420 }
1421
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 @Override
1423 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1424 Intent intent, String resolvedType, IVoiceInteractionSession session,
1425 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1426 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001427 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 if (session == null || interactor == null) {
1429 throw new NullPointerException("null session or interactor");
1430 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001433 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 .setCallingUid(callingUid)
1435 .setCallingPackage(callingPackage)
1436 .setResolvedType(resolvedType)
1437 .setVoiceSession(session)
1438 .setVoiceInteractor(interactor)
1439 .setStartFlags(startFlags)
1440 .setProfilerInfo(profilerInfo)
1441 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001442 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001443 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 .execute();
1445 }
1446
1447 @Override
1448 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1449 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001450 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1451 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001453 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .setCallingUid(callingUid)
1455 .setCallingPackage(callingPackage)
1456 .setResolvedType(resolvedType)
1457 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001458 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001459 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 .execute();
1461 }
1462
Riddle Hsu609a8e22019-06-27 16:46:29 -06001463 /**
1464 * Start the recents activity to perform the recents animation.
1465 *
1466 * @param intent The intent to start the recents activity.
1467 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1468 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001470 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1471 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001474 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 final long origId = Binder.clearCallingIdentity();
1476 try {
1477 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001478 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1479 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001480 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481
1482 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001483 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001484 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001485 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001486 if (recentsAnimationRunner == null) {
1487 anim.preloadRecentsActivity();
1488 } else {
1489 anim.startRecentsActivity(recentsAnimationRunner);
1490 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 }
1492 } finally {
1493 Binder.restoreCallingIdentity(origId);
1494 }
1495 }
1496
1497 @Override
1498 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 "startActivityFromRecents()");
1501
1502 final int callingPid = Binder.getCallingPid();
1503 final int callingUid = Binder.getCallingUid();
1504 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1505 final long origId = Binder.clearCallingIdentity();
1506 try {
1507 synchronized (mGlobalLock) {
1508 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1509 safeOptions);
1510 }
1511 } finally {
1512 Binder.restoreCallingIdentity(origId);
1513 }
1514 }
1515
1516 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001517 * Public API to check if the client is allowed to start an activity on specified display.
1518 *
1519 * If the target display is private or virtual, some restrictions will apply.
1520 *
1521 * @param displayId Target display id.
1522 * @param intent Intent used to launch the activity.
1523 * @param resolvedType The MIME type of the intent.
1524 * @param userId The id of the user for whom the call is made.
1525 * @return {@code true} if a call to start an activity on the target display should succeed and
1526 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1527 */
1528 @Override
1529 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1530 String resolvedType, int userId) {
1531 final int callingUid = Binder.getCallingUid();
1532 final int callingPid = Binder.getCallingPid();
1533 final long origId = Binder.clearCallingIdentity();
1534
1535 try {
1536 // Collect information about the target of the Intent.
1537 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1538 0 /* startFlags */, null /* profilerInfo */, userId,
1539 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1540 UserHandle.USER_NULL));
1541 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1542
1543 synchronized (mGlobalLock) {
1544 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1545 aInfo);
1546 }
1547 } finally {
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550 }
1551
1552 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 * This is the internal entry point for handling Activity.finish().
1554 *
1555 * @param token The Binder token referencing the Activity we want to finish.
1556 * @param resultCode Result code, if any, from this Activity.
1557 * @param resultData Result data (Intent), if any, from this Activity.
1558 * @param finishTask Whether to finish the task associated with this Activity.
1559 *
1560 * @return Returns true if the activity successfully finished, or false if it is still running.
1561 */
1562 @Override
1563 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1564 int finishTask) {
1565 // Refuse possible leaked file descriptors
1566 if (resultData != null && resultData.hasFileDescriptors()) {
1567 throw new IllegalArgumentException("File descriptors passed in Intent");
1568 }
1569
1570 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001571 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 if (r == null) {
1573 return true;
1574 }
1575 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001576 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001577 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 if (rootR == null) {
1579 Slog.w(TAG, "Finishing task with all activities already finished");
1580 }
1581 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1582 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001583 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 return false;
1585 }
1586
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001587 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1588 // We should consolidate.
1589 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001591 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 if (next != null) {
1593 // ask watcher if this is allowed
1594 boolean resumeOK = true;
1595 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001596 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001598 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599 Watchdog.getInstance().setActivityController(null);
1600 }
1601
1602 if (!resumeOK) {
1603 Slog.i(TAG, "Not finishing activity because controller resumed");
1604 return false;
1605 }
1606 }
1607 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001608
1609 // note down that the process has finished an activity and is in background activity
1610 // starts grace period
1611 if (r.app != null) {
1612 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1613 }
1614
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001616 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 try {
1618 boolean res;
1619 final boolean finishWithRootActivity =
1620 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1621 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1622 || (finishWithRootActivity && r == rootR)) {
1623 // If requested, remove the task that is associated to this activity only if it
1624 // was the root activity in the task. The result code and data is ignored
1625 // because we don't support returning them across task boundaries. Also, to
1626 // keep backwards compatibility we remove the task from recents when finishing
1627 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001628 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 finishWithRootActivity, "finish-activity");
1630 if (!res) {
1631 Slog.i(TAG, "Removing task failed to finish activity");
1632 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001633 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001634 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001636 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001637 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 if (!res) {
1639 Slog.i(TAG, "Failed to finish by app-request");
1640 }
1641 }
1642 return res;
1643 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001644 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public boolean finishActivityAffinity(IBinder token) {
1652 synchronized (mGlobalLock) {
1653 final long origId = Binder.clearCallingIdentity();
1654 try {
1655 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1656 if (r == null) {
1657 return false;
1658 }
1659
1660 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1661 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001662 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 return false;
1664 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001665 r.finishActivityAffinity();
1666 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 } finally {
1668 Binder.restoreCallingIdentity(origId);
1669 }
1670 }
1671 }
1672
1673 @Override
1674 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1675 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001676 try {
1677 WindowProcessController proc = null;
1678 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001679 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001680 ActivityStack stack = ActivityRecord.getStackLocked(token);
1681 if (stack == null) {
1682 return;
1683 }
1684 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1685 false /* fromTimeout */, false /* processPausingActivities */, config);
1686 if (r != null) {
1687 proc = r.app;
1688 }
1689 if (stopProfiling && proc != null) {
1690 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 }
1692 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001693 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001694 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 }
1698
1699 @Override
1700 public final void activityResumed(IBinder token) {
1701 final long origId = Binder.clearCallingIdentity();
1702 synchronized (mGlobalLock) {
1703 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 }
1705 Binder.restoreCallingIdentity(origId);
1706 }
1707
1708 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001709 public final void activityTopResumedStateLost() {
1710 final long origId = Binder.clearCallingIdentity();
1711 synchronized (mGlobalLock) {
1712 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1713 }
1714 Binder.restoreCallingIdentity(origId);
1715 }
1716
1717 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 public final void activityPaused(IBinder token) {
1719 final long origId = Binder.clearCallingIdentity();
1720 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001721 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 ActivityStack stack = ActivityRecord.getStackLocked(token);
1723 if (stack != null) {
1724 stack.activityPausedLocked(token, false);
1725 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001726 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 }
1728 Binder.restoreCallingIdentity(origId);
1729 }
1730
1731 @Override
1732 public final void activityStopped(IBinder token, Bundle icicle,
1733 PersistableBundle persistentState, CharSequence description) {
1734 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1735
1736 // Refuse possible leaked file descriptors
1737 if (icicle != null && icicle.hasFileDescriptors()) {
1738 throw new IllegalArgumentException("File descriptors passed in Bundle");
1739 }
1740
1741 final long origId = Binder.clearCallingIdentity();
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 String restartingName = null;
1744 int restartingUid = 0;
1745 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001747 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001748 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001750 if (r.attachedToProcess()
1751 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1752 // The activity was requested to restart from
1753 // {@link #restartActivityProcessIfVisible}.
1754 restartingName = r.app.mName;
1755 restartingUid = r.app.mUid;
1756 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 r.activityStoppedLocked(icicle, persistentState, description);
1758 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001759 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 }
1761
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001762 if (restartingName != null) {
1763 // In order to let the foreground activity can be restarted with its saved state from
1764 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1765 // until the activity reports stopped with the state. And the activity record will be
1766 // kept because the record state is restarting, then the activity will be restarted
1767 // immediately if it is still the top one.
1768 mStackSupervisor.removeRestartTimeouts(r);
1769 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1770 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001771 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772
1773 Binder.restoreCallingIdentity(origId);
1774 }
1775
1776 @Override
1777 public final void activityDestroyed(IBinder token) {
1778 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1779 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001780 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001781 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001782 try {
1783 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1784 if (activity != null) {
1785 activity.destroyed("activityDestroyed");
1786 }
1787 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001788 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001789 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 }
1792 }
1793
1794 @Override
1795 public final void activityRelaunched(IBinder token) {
1796 final long origId = Binder.clearCallingIdentity();
1797 synchronized (mGlobalLock) {
1798 mStackSupervisor.activityRelaunchedLocked(token);
1799 }
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 public final void activitySlept(IBinder token) {
1804 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1805
1806 final long origId = Binder.clearCallingIdentity();
1807
1808 synchronized (mGlobalLock) {
1809 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1810 if (r != null) {
1811 mStackSupervisor.activitySleptLocked(r);
1812 }
1813 }
1814
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
1818 @Override
1819 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1820 synchronized (mGlobalLock) {
1821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return;
1824 }
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 r.setRequestedOrientation(requestedOrientation);
1828 } finally {
1829 Binder.restoreCallingIdentity(origId);
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public int getRequestedOrientation(IBinder token) {
1836 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001837 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 return (r != null)
1839 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842
1843 @Override
1844 public void setImmersive(IBinder token, boolean immersive) {
1845 synchronized (mGlobalLock) {
1846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 throw new IllegalArgumentException();
1849 }
1850 r.immersive = immersive;
1851
1852 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001853 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858 }
1859
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 void applyUpdateLockStateLocked(ActivityRecord r) {
1861 // Modifications to the UpdateLock state are done on our handler, outside
1862 // the activity manager's locks. The new state is determined based on the
1863 // state *now* of the relevant activity record. The object is passed to
1864 // the handler solely for logging detail, not to be consulted/modified.
1865 final boolean nextState = r != null && r.immersive;
1866 mH.post(() -> {
1867 if (mUpdateLock.isHeld() != nextState) {
1868 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1869 "Applying new update lock state '" + nextState + "' for " + r);
1870 if (nextState) {
1871 mUpdateLock.acquire();
1872 } else {
1873 mUpdateLock.release();
1874 }
1875 }
1876 });
1877 }
1878
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 @Override
1880 public boolean isImmersive(IBinder token) {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 throw new IllegalArgumentException();
1885 }
1886 return r.immersive;
1887 }
1888 }
1889
1890 @Override
1891 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 return (r != null) ? r.immersive : false;
1896 }
1897 }
1898
1899 @Override
1900 public void overridePendingTransition(IBinder token, String packageName,
1901 int enterAnim, int exitAnim) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1904 if (self == null) {
1905 return;
1906 }
1907
1908 final long origId = Binder.clearCallingIdentity();
1909
1910 if (self.isState(
1911 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001912 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001913 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
1915
1916 Binder.restoreCallingIdentity(origId);
1917 }
1918 }
1919
1920 @Override
1921 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001924 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 if (r == null) {
1926 return ActivityManager.COMPAT_MODE_UNKNOWN;
1927 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 if (r == null) {
1940 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1941 return;
1942 }
1943 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public int getLaunchedFromUid(IBinder activityToken) {
1950 ActivityRecord srec;
1951 synchronized (mGlobalLock) {
1952 srec = ActivityRecord.forTokenLocked(activityToken);
1953 }
1954 if (srec == null) {
1955 return -1;
1956 }
1957 return srec.launchedFromUid;
1958 }
1959
1960 @Override
1961 public String getLaunchedFromPackage(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return null;
1968 }
1969 return srec.launchedFromPackage;
1970 }
1971
1972 @Override
1973 public boolean convertFromTranslucent(IBinder token) {
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001981 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 } finally {
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public boolean convertToTranslucent(IBinder token, Bundle options) {
1990 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1991 final long origId = Binder.clearCallingIdentity();
1992 try {
1993 synchronized (mGlobalLock) {
1994 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1995 if (r == null) {
1996 return false;
1997 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001998 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 int index = task.mActivities.lastIndexOf(r);
2000 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002001 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2003 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002004 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 } finally {
2007 Binder.restoreCallingIdentity(origId);
2008 }
2009 }
2010
2011 @Override
2012 public void notifyActivityDrawn(IBinder token) {
2013 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2014 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002015 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002017 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 }
2019 }
2020 }
2021
2022 @Override
2023 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2024 synchronized (mGlobalLock) {
2025 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2026 if (r == null) {
2027 return;
2028 }
2029 r.reportFullyDrawnLocked(restoredFromBundle);
2030 }
2031 }
2032
2033 @Override
2034 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2035 synchronized (mGlobalLock) {
2036 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2037 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2038 return stack.mDisplayId;
2039 }
2040 return DEFAULT_DISPLAY;
2041 }
2042 }
2043
2044 @Override
2045 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 long ident = Binder.clearCallingIdentity();
2048 try {
2049 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002050 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002052 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 }
2054 return null;
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(ident);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 if (stack == null) {
2070 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2071 return;
2072 }
2073 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
2084 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2087 final long callingId = Binder.clearCallingIdentity();
2088 try {
2089 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002090 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002091 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 if (task == null) {
2093 return;
2094 }
2095 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002096 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002097 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 }
2099 }
2100 } finally {
2101 Binder.restoreCallingIdentity(callingId);
2102 }
2103 }
2104
2105 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002106 public void restartActivityProcessIfVisible(IBinder activityToken) {
2107 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2108 final long callingId = Binder.clearCallingIdentity();
2109 try {
2110 synchronized (mGlobalLock) {
2111 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2112 if (r == null) {
2113 return;
2114 }
2115 r.restartProcessIfVisible();
2116 }
2117 } finally {
2118 Binder.restoreCallingIdentity(callingId);
2119 }
2120 }
2121
2122 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002125 synchronized (mGlobalLock) {
2126 final long ident = Binder.clearCallingIdentity();
2127 try {
2128 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2129 "remove-task");
2130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134 }
2135
2136 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002137 public void removeAllVisibleRecentTasks() {
2138 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2139 synchronized (mGlobalLock) {
2140 final long ident = Binder.clearCallingIdentity();
2141 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002142 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002143 } finally {
2144 Binder.restoreCallingIdentity(ident);
2145 }
2146 }
2147 }
2148
2149 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002150 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2151 synchronized (mGlobalLock) {
2152 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2153 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002154 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 }
2156 }
2157 return false;
2158 }
2159
2160 @Override
2161 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2162 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002163
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002164 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002165 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2166 if (r != null) {
2167 return r.getActivityStack().navigateUpToLocked(
2168 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002169 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002170 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002171 }
2172 }
2173
2174 /**
2175 * Attempts to move a task backwards in z-order (the order of activities within the task is
2176 * unchanged).
2177 *
2178 * There are several possible results of this call:
2179 * - if the task is locked, then we will show the lock toast
2180 * - if there is a task behind the provided task, then that task is made visible and resumed as
2181 * this task is moved to the back
2182 * - otherwise, if there are no other tasks in the stack:
2183 * - if this task is in the pinned stack, then we remove the stack completely, which will
2184 * have the effect of moving the task to the top or bottom of the fullscreen stack
2185 * (depending on whether it is visible)
2186 * - otherwise, we simply return home and hide this task
2187 *
2188 * @param token A reference to the activity we wish to move
2189 * @param nonRoot If false then this only works if the activity is the root
2190 * of a task; if true it will work for any activity in a task.
2191 * @return Returns true if the move completed, false if not.
2192 */
2193 @Override
2194 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002195 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 synchronized (mGlobalLock) {
2197 final long origId = Binder.clearCallingIdentity();
2198 try {
2199 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002200 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 if (task != null) {
2202 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2203 }
2204 } finally {
2205 Binder.restoreCallingIdentity(origId);
2206 }
2207 }
2208 return false;
2209 }
2210
2211 @Override
2212 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002213 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 long ident = Binder.clearCallingIdentity();
2215 Rect rect = new Rect();
2216 try {
2217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2220 if (task == null) {
2221 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2222 return rect;
2223 }
2224 if (task.getStack() != null) {
2225 // Return the bounds from window manager since it will be adjusted for various
2226 // things like the presense of a docked stack for tasks that aren't resizeable.
2227 task.getWindowContainerBounds(rect);
2228 } else {
2229 // Task isn't in window manager yet since it isn't associated with a stack.
2230 // Return the persist value from activity manager
2231 if (!task.matchParentBounds()) {
2232 rect.set(task.getBounds());
2233 } else if (task.mLastNonFullscreenBounds != null) {
2234 rect.set(task.mLastNonFullscreenBounds);
2235 }
2236 }
2237 }
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 return rect;
2242 }
2243
2244 @Override
2245 public ActivityManager.TaskDescription getTaskDescription(int id) {
2246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002249 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2251 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002252 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254 }
2255 return null;
2256 }
2257
2258 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2260 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2261 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2262 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2263 return;
2264 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 synchronized (mGlobalLock) {
2267 final long ident = Binder.clearCallingIdentity();
2268 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002269 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002270 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 if (task == null) {
2272 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2273 return;
2274 }
2275
2276 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2277 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2278
2279 if (!task.isActivityTypeStandardOrUndefined()) {
2280 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2281 + " non-standard task " + taskId + " to windowing mode="
2282 + windowingMode);
2283 }
2284
2285 final ActivityStack stack = task.getStack();
2286 if (toTop) {
2287 stack.moveToFront("setTaskWindowingMode", task);
2288 }
2289 stack.setWindowingMode(windowingMode);
2290 } finally {
2291 Binder.restoreCallingIdentity(ident);
2292 }
2293 }
2294 }
2295
2296 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.info.packageName : null;
2301 }
2302 }
2303
2304 @Override
2305 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 ActivityRecord r = getCallingRecordLocked(token);
2308 return r != null ? r.intent.getComponent() : null;
2309 }
2310 }
2311
2312 private ActivityRecord getCallingRecordLocked(IBinder token) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return null;
2316 }
2317 return r.resultTo;
2318 }
2319
2320 @Override
2321 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323
2324 synchronized (mGlobalLock) {
2325 final long origId = Binder.clearCallingIdentity();
2326 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002327 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 } finally {
2329 Binder.restoreCallingIdentity(origId);
2330 }
2331 }
2332 }
2333
Mark Renouf446251d2019-04-26 10:22:41 -04002334 @Override
2335 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2336 synchronized (mGlobalLock) {
2337 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2338 if (r == null) {
2339 return;
2340 }
2341 ActivityStack stack = r.getActivityStack();
2342 if (stack != null && stack.isSingleTaskInstance()) {
2343 // Single-task stacks are used for activities which are presented in floating
2344 // windows above full screen activities. Instead of directly finishing the
2345 // task, a task change listener is used to notify SystemUI so the action can be
2346 // handled specially.
2347 final TaskRecord task = r.getTaskRecord();
2348 mTaskChangeNotificationController
2349 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2350 } else {
2351 try {
2352 callback.requestFinish();
2353 } catch (RemoteException e) {
2354 Slog.e(TAG, "Failed to invoke request finish callback", e);
2355 }
2356 }
2357 }
2358 }
2359
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 /**
2361 * TODO: Add mController hook
2362 */
2363 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2365 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367
2368 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2369 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2371 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 }
2373 }
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2376 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002378
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 final int callingPid = Binder.getCallingPid();
2380 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002381 if (!isSameApp(callingUid, callingPackage)) {
2382 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2383 + Binder.getCallingPid() + " as package " + callingPackage;
2384 Slog.w(TAG, msg);
2385 throw new SecurityException(msg);
2386 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 SafeActivityOptions.abort(options);
2389 return;
2390 }
2391 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 WindowProcessController callerApp = null;
2393 if (appThread != null) {
2394 callerApp = getProcessController(appThread);
2395 }
2396 final ActivityStarter starter = getActivityStartController().obtainStarter(
2397 null /* intent */, "moveTaskToFront");
2398 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2399 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002400 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002401 return;
2402 }
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 if (task == null) {
2407 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002408 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 return;
2410 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002411 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002413 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 return;
2415 }
2416 ActivityOptions realOptions = options != null
2417 ? options.getOptions(mStackSupervisor)
2418 : null;
2419 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2420 false /* forceNonResizable */);
2421
2422 final ActivityRecord topActivity = task.getTopActivity();
2423 if (topActivity != null) {
2424
2425 // We are reshowing a task, use a starting window to hide the initial draw delay
2426 // so the transition can start earlier.
2427 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2428 true /* taskSwitch */, fromRecents);
2429 }
2430 } finally {
2431 Binder.restoreCallingIdentity(origId);
2432 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 }
2434
Ricky Waiaca8a772019-04-04 16:01:06 +01002435 /**
2436 * Return true if callingUid is system, or packageName belongs to that callingUid.
2437 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002438 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002439 try {
2440 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2441 if (packageName == null) {
2442 return false;
2443 }
2444 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2445 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2446 UserHandle.getUserId(callingUid));
2447 return UserHandle.isSameApp(callingUid, uid);
2448 }
2449 } catch (RemoteException e) {
2450 // Should not happen
2451 }
2452 return true;
2453 }
2454
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2456 int callingPid, int callingUid, String name) {
2457 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2458 return true;
2459 }
2460
2461 if (getRecentTasks().isCallerRecents(sourceUid)) {
2462 return true;
2463 }
2464
2465 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2466 if (perm == PackageManager.PERMISSION_GRANTED) {
2467 return true;
2468 }
2469 if (checkAllowAppSwitchUid(sourceUid)) {
2470 return true;
2471 }
2472
2473 // If the actual IPC caller is different from the logical source, then
2474 // also see if they are allowed to control app switches.
2475 if (callingUid != -1 && callingUid != sourceUid) {
2476 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(callingUid)) {
2481 return true;
2482 }
2483 }
2484
2485 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2486 return false;
2487 }
2488
2489 private boolean checkAllowAppSwitchUid(int uid) {
2490 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2491 if (types != null) {
2492 for (int i = types.size() - 1; i >= 0; i--) {
2493 if (types.valueAt(i).intValue() == uid) {
2494 return true;
2495 }
2496 }
2497 }
2498 return false;
2499 }
2500
2501 @Override
2502 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2503 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2504 "setActivityController()");
2505 synchronized (mGlobalLock) {
2506 mController = controller;
2507 mControllerIsAMonkey = imAMonkey;
2508 Watchdog.getInstance().setActivityController(controller);
2509 }
2510 }
2511
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002512 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 synchronized (mGlobalLock) {
2514 return mController != null && mControllerIsAMonkey;
2515 }
2516 }
2517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 @Override
2519 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2520 synchronized (mGlobalLock) {
2521 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2522 }
2523 }
2524
2525 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2527 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2528 }
2529
2530 @Override
2531 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2532 @WindowConfiguration.ActivityType int ignoreActivityType,
2533 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2534 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002535 final int callingPid = Binder.getCallingPid();
2536 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002537 final int[] profileIds = getUserManager().getProfileIds(
2538 UserHandle.getUserId(callingUid), true);
2539 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2540 for (int i = 0; i < profileIds.length; i++) {
2541 callingProfileIds.add(profileIds[i]);
2542 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2544
2545 synchronized (mGlobalLock) {
2546 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2547
Nicholas Sauer0259e532019-08-30 08:24:55 -07002548 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002549 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002550 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 }
2552
2553 return list;
2554 }
2555
2556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2558 synchronized (mGlobalLock) {
2559 final long origId = Binder.clearCallingIdentity();
2560 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2561 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002562 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002563 }
2564 Binder.restoreCallingIdentity(origId);
2565 }
2566 }
2567
2568 @Override
2569 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 ActivityStack stack = ActivityRecord.getStackLocked(token);
2572 if (stack != null) {
2573 return stack.willActivityBeVisibleLocked(token);
2574 }
2575 return false;
2576 }
2577 }
2578
2579 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 synchronized (mGlobalLock) {
2583 final long ident = Binder.clearCallingIdentity();
2584 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (task == null) {
2587 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2588 return;
2589 }
2590
2591 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2592 + " to stackId=" + stackId + " toTop=" + toTop);
2593
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 if (stack == null) {
2596 throw new IllegalStateException(
2597 "moveTaskToStack: No stack for stackId=" + stackId);
2598 }
2599 if (!stack.isActivityTypeStandardOrUndefined()) {
2600 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2601 + taskId + " to stack " + stackId);
2602 }
2603 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002604 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2606 }
2607 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2608 "moveTaskToStack");
2609 } finally {
2610 Binder.restoreCallingIdentity(ident);
2611 }
2612 }
2613 }
2614
2615 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002616 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2617 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002618
2619 final long ident = Binder.clearCallingIdentity();
2620 try {
2621 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002622 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2623 if (stack == null) {
2624 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2625 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002627 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2628 throw new IllegalArgumentException("Stack: " + stackId
2629 + " doesn't support animated resize.");
2630 }
2631 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2632 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
2638
wilsonshih5c4cf522019-01-25 09:03:47 +08002639 @Override
2640 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2641 int animationDuration) {
2642 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2643
2644 final long ident = Binder.clearCallingIdentity();
2645 try {
2646 synchronized (mGlobalLock) {
2647 if (xOffset == 0 && yOffset == 0) {
2648 return;
2649 }
2650 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2651 if (stack == null) {
2652 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2653 return;
2654 }
2655 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2656 throw new IllegalArgumentException("Stack: " + stackId
2657 + " doesn't support animated resize.");
2658 }
2659 final Rect destBounds = new Rect();
2660 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002661 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002662 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2663 return;
2664 }
2665 destBounds.offset(xOffset, yOffset);
2666 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2667 animationDuration, false /* fromFullscreen */);
2668 }
2669 } finally {
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002673 /**
2674 * Moves the specified task to the primary-split-screen stack.
2675 *
2676 * @param taskId Id of task to move.
2677 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2678 * exist already. See
2679 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2680 * and
2681 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2682 * @param toTop If the task and stack should be moved to the top.
2683 * @param animate Whether we should play an animation for the moving the task.
2684 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2685 * stack. Pass {@code null} to use default bounds.
2686 * @param showRecents If the recents activity should be shown on the other side of the task
2687 * going into split-screen mode.
2688 */
2689 @Override
2690 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2691 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002692 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 "setTaskWindowingModeSplitScreenPrimary()");
2694 synchronized (mGlobalLock) {
2695 final long ident = Binder.clearCallingIdentity();
2696 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002697 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002698 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 if (task == null) {
2700 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2701 return false;
2702 }
2703 if (DEBUG_STACK) Slog.d(TAG_STACK,
2704 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2705 + " to createMode=" + createMode + " toTop=" + toTop);
2706 if (!task.isActivityTypeStandardOrUndefined()) {
2707 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2708 + " non-standard task " + taskId + " to split-screen windowing mode");
2709 }
2710
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002711 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002712 final int windowingMode = task.getWindowingMode();
2713 final ActivityStack stack = task.getStack();
2714 if (toTop) {
2715 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2716 }
2717 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002718 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2719 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 return windowingMode != task.getWindowingMode();
2721 } finally {
2722 Binder.restoreCallingIdentity(ident);
2723 }
2724 }
2725 }
2726
2727 /**
2728 * Removes stacks in the input windowing modes from the system if they are of activity type
2729 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2730 */
2731 @Override
2732 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 "removeStacksInWindowingModes()");
2735
2736 synchronized (mGlobalLock) {
2737 final long ident = Binder.clearCallingIdentity();
2738 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002739 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 } finally {
2741 Binder.restoreCallingIdentity(ident);
2742 }
2743 }
2744 }
2745
2746 @Override
2747 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002748 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002749 "removeStacksWithActivityTypes()");
2750
2751 synchronized (mGlobalLock) {
2752 final long ident = Binder.clearCallingIdentity();
2753 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002754 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002755 } finally {
2756 Binder.restoreCallingIdentity(ident);
2757 }
2758 }
2759 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760
2761 @Override
2762 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2763 int userId) {
2764 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002765 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2766 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 final boolean detailed = checkGetTasksPermission(
2769 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2770 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 == PackageManager.PERMISSION_GRANTED;
2772
2773 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002774 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 callingUid);
2776 }
2777 }
2778
2779 @Override
2780 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 long ident = Binder.clearCallingIdentity();
2783 try {
2784 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002785 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 }
2787 } finally {
2788 Binder.restoreCallingIdentity(ident);
2789 }
2790 }
2791
2792 @Override
2793 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002794 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 long ident = Binder.clearCallingIdentity();
2796 try {
2797 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002798 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800 } finally {
2801 Binder.restoreCallingIdentity(ident);
2802 }
2803 }
2804
2805 @Override
2806 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 final long callingUid = Binder.getCallingUid();
2809 final long origId = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mGlobalLock) {
2812 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002813 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2815 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2816 }
2817 } finally {
2818 Binder.restoreCallingIdentity(origId);
2819 }
2820 }
2821
2822 @Override
2823 public void startLockTaskModeByToken(IBinder token) {
2824 synchronized (mGlobalLock) {
2825 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2826 if (r == null) {
2827 return;
2828 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002829 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 }
2831 }
2832
2833 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002834 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002835 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 // This makes inner call to look as if it was initiated by system.
2837 long ident = Binder.clearCallingIdentity();
2838 try {
2839 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002840 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002841 MATCH_TASK_IN_STACKS_ONLY);
2842 if (task == null) {
2843 return;
2844 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845
2846 // When starting lock task mode the stack must be in front and focused
2847 task.getStack().moveToFront("startSystemLockTaskMode");
2848 startLockTaskModeLocked(task, true /* isSystemCaller */);
2849 }
2850 } finally {
2851 Binder.restoreCallingIdentity(ident);
2852 }
2853 }
2854
2855 @Override
2856 public void stopLockTaskModeByToken(IBinder token) {
2857 synchronized (mGlobalLock) {
2858 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2859 if (r == null) {
2860 return;
2861 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002862 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 }
2864 }
2865
2866 /**
2867 * This API should be called by SystemUI only when user perform certain action to dismiss
2868 * lock task mode. We should only dismiss pinned lock task mode in this case.
2869 */
2870 @Override
2871 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002872 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2874 }
2875
2876 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2877 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2878 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2879 return;
2880 }
2881
Wale Ogunwaled32da472018-11-16 07:19:28 -08002882 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 if (stack == null || task != stack.topTask()) {
2884 throw new IllegalArgumentException("Invalid task, not in foreground");
2885 }
2886
2887 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2888 // system or a specific app.
2889 // * System-initiated requests will only start the pinned mode (screen pinning)
2890 // * App-initiated requests
2891 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2892 // - will start the pinned mode, otherwise
2893 final int callingUid = Binder.getCallingUid();
2894 long ident = Binder.clearCallingIdentity();
2895 try {
2896 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002897 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002899 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 } finally {
2901 Binder.restoreCallingIdentity(ident);
2902 }
2903 }
2904
2905 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2906 final int callingUid = Binder.getCallingUid();
2907 long ident = Binder.clearCallingIdentity();
2908 try {
2909 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002910 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 }
2912 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2913 // task and jumping straight into a call in the case of emergency call back.
2914 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2915 if (tm != null) {
2916 tm.showInCallScreen(false);
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002924 public void updateLockTaskPackages(int userId, String[] packages) {
2925 final int callingUid = Binder.getCallingUid();
2926 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2927 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2928 "updateLockTaskPackages()");
2929 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002930 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002931 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2932 + Arrays.toString(packages));
2933 getLockTaskController().updateLockTaskPackages(userId, packages);
2934 }
2935 }
2936
2937 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 public boolean isInLockTaskMode() {
2939 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2940 }
2941
2942 @Override
2943 public int getLockTaskModeState() {
2944 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002945 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 }
2948
2949 @Override
2950 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2951 synchronized (mGlobalLock) {
2952 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2953 if (r != null) {
2954 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002955 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002957 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 }
2959 }
2960 }
2961
2962 @Override
2963 public Bundle getActivityOptions(IBinder token) {
2964 final long origId = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
2967 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2968 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002969 final ActivityOptions activityOptions = r.takeOptionsLocked(
2970 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 return activityOptions == null ? null : activityOptions.toBundle();
2972 }
2973 return null;
2974 }
2975 } finally {
2976 Binder.restoreCallingIdentity(origId);
2977 }
2978 }
2979
2980 @Override
2981 public List<IBinder> getAppTasks(String callingPackage) {
2982 int callingUid = Binder.getCallingUid();
2983 long ident = Binder.clearCallingIdentity();
2984 try {
2985 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002986 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 }
2988 } finally {
2989 Binder.restoreCallingIdentity(ident);
2990 }
2991 }
2992
2993 @Override
2994 public void finishVoiceTask(IVoiceInteractionSession session) {
2995 synchronized (mGlobalLock) {
2996 final long origId = Binder.clearCallingIdentity();
2997 try {
2998 // TODO: VI Consider treating local voice interactions and voice tasks
2999 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003000 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 } finally {
3002 Binder.restoreCallingIdentity(origId);
3003 }
3004 }
3005
3006 }
3007
3008 @Override
3009 public boolean isTopOfTask(IBinder token) {
3010 synchronized (mGlobalLock) {
3011 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003012 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 }
3014 }
3015
3016 @Override
3017 public void notifyLaunchTaskBehindComplete(IBinder token) {
3018 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3019 }
3020
3021 @Override
3022 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003023 mH.post(() -> {
3024 synchronized (mGlobalLock) {
3025 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003026 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003027 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003028 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003029 } catch (RemoteException e) {
3030 }
3031 }
3032 }
3033
3034 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036
3037 /** Called from an app when assist data is ready. */
3038 @Override
3039 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3040 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 synchronized (pae) {
3043 pae.result = extras;
3044 pae.structure = structure;
3045 pae.content = content;
3046 if (referrer != null) {
3047 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3048 }
3049 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003050 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003051 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003052 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 structure.setHomeActivity(pae.isHome);
3054 }
3055 pae.haveResult = true;
3056 pae.notifyAll();
3057 if (pae.intent == null && pae.receiver == null) {
3058 // Caller is just waiting for the result.
3059 return;
3060 }
3061 }
3062 // We are now ready to launch the assist activity.
3063 IAssistDataReceiver sendReceiver = null;
3064 Bundle sendBundle = null;
3065 synchronized (mGlobalLock) {
3066 buildAssistBundleLocked(pae, extras);
3067 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003068 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 if (!exists) {
3070 // Timed out.
3071 return;
3072 }
3073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 // Caller wants result sent back to them.
3076 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003077 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003078 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003079 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3080 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3082 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3083 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3084 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3085 }
3086 }
3087 if (sendReceiver != null) {
3088 try {
3089 sendReceiver.onHandleAssistData(sendBundle);
3090 } catch (RemoteException e) {
3091 }
3092 return;
3093 }
3094
3095 final long ident = Binder.clearCallingIdentity();
3096 try {
3097 if (TextUtils.equals(pae.intent.getAction(),
3098 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003099 // Start voice interaction through VoiceInteractionManagerService.
3100 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3101 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 } else {
3103 pae.intent.replaceExtras(pae.extras);
3104 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3105 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3106 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003107 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003108
3109 try {
3110 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3111 } catch (ActivityNotFoundException e) {
3112 Slog.w(TAG, "No activity to handle assist action.", e);
3113 }
3114 }
3115 } finally {
3116 Binder.restoreCallingIdentity(ident);
3117 }
3118 }
3119
3120 @Override
3121 public int addAppTask(IBinder activityToken, Intent intent,
3122 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3123 final int callingUid = Binder.getCallingUid();
3124 final long callingIdent = Binder.clearCallingIdentity();
3125
3126 try {
3127 synchronized (mGlobalLock) {
3128 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3129 if (r == null) {
3130 throw new IllegalArgumentException("Activity does not exist; token="
3131 + activityToken);
3132 }
3133 ComponentName comp = intent.getComponent();
3134 if (comp == null) {
3135 throw new IllegalArgumentException("Intent " + intent
3136 + " must specify explicit component");
3137 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003138 if (thumbnail.getWidth() != mThumbnailWidth
3139 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 throw new IllegalArgumentException("Bad thumbnail size: got "
3141 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 }
3144 if (intent.getSelector() != null) {
3145 intent.setSelector(null);
3146 }
3147 if (intent.getSourceBounds() != null) {
3148 intent.setSourceBounds(null);
3149 }
3150 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3151 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3152 // The caller has added this as an auto-remove task... that makes no
3153 // sense, so turn off auto-remove.
3154 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3155 }
3156 }
3157 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3158 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3159 if (ainfo.applicationInfo.uid != callingUid) {
3160 throw new SecurityException(
3161 "Can't add task for another application: target uid="
3162 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3163 }
3164
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003165 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003167 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003169 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 // The app has too many tasks already and we can't add any more
3171 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3172 return INVALID_TASK_ID;
3173 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003174 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175
3176 // TODO: Send the thumbnail to WM to store it.
3177
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003178 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 } finally {
3181 Binder.restoreCallingIdentity(callingIdent);
3182 }
3183 }
3184
3185 @Override
3186 public Point getAppTaskThumbnailSize() {
3187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 }
3190 }
3191
3192 @Override
3193 public void setTaskResizeable(int taskId, int resizeableMode) {
3194 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003195 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3197 if (task == null) {
3198 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3199 return;
3200 }
3201 task.setResizeMode(resizeableMode);
3202 }
3203 }
3204
3205 @Override
3206 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003207 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 long ident = Binder.clearCallingIdentity();
3209 try {
3210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003211 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003212 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 if (task == null) {
3214 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3215 return;
3216 }
3217 // Place the task in the right stack if it isn't there already based on
3218 // the requested bounds.
3219 // The stack transition logic is:
3220 // - a null bounds on a freeform task moves that task to fullscreen
3221 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3222 // that task to freeform
3223 // - otherwise the task is not moved
3224 ActivityStack stack = task.getStack();
3225 if (!task.getWindowConfiguration().canResizeTask()) {
3226 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3227 }
3228 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3229 stack = stack.getDisplay().getOrCreateStack(
3230 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3231 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3232 stack = stack.getDisplay().getOrCreateStack(
3233 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3234 }
3235
3236 // Reparent the task to the right stack if necessary
3237 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3238 if (stack != task.getStack()) {
3239 // Defer resume until the task is resized below
3240 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3241 DEFER_RESUME, "resizeTask");
3242 preserveWindow = false;
3243 }
3244
3245 // After reparenting (which only resizes the task to the stack bounds), resize the
3246 // task to the actual bounds provided
3247 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3248 }
3249 } finally {
3250 Binder.restoreCallingIdentity(ident);
3251 }
3252 }
3253
Evan Roskyddedfd42019-10-04 13:38:38 -07003254 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3255 WindowContainerTransaction.Change change) {
3256 if (!(container instanceof TaskRecord)) {
3257 throw new RuntimeException("Invalid token in task transaction");
3258 }
3259 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3260 // masks here.
3261 int configMask = change.getConfigSetMask();
3262 int windowMask = change.getWindowSetMask();
3263 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3264 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3265 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3266 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3267 c.setTo(change.getConfiguration(), configMask, windowMask);
3268 container.onRequestedOverrideConfigurationChanged(c);
3269 }
3270
3271 @Override
3272 public void applyContainerTransaction(WindowContainerTransaction t) {
3273 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3274 long ident = Binder.clearCallingIdentity();
3275 try {
3276 if (t == null) {
3277 return;
3278 }
3279 synchronized (mGlobalLock) {
3280 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3281 t.getChanges().entrySet().iterator();
3282 while (entries.hasNext()) {
3283 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3284 entries.next();
3285 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3286 entry.getKey()).getContainer();
3287 sanitizeAndApplyConfigChange(cc, entry.getValue());
3288 }
3289 }
3290 } finally {
3291 Binder.restoreCallingIdentity(ident);
3292 }
3293 }
3294
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 @Override
3296 public boolean releaseActivityInstance(IBinder token) {
3297 synchronized (mGlobalLock) {
3298 final long origId = Binder.clearCallingIdentity();
3299 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003300 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3301 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 return false;
3303 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003304 r.destroyImmediately(true /* removeFromApp */, "app-req");
3305 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 } finally {
3307 Binder.restoreCallingIdentity(origId);
3308 }
3309 }
3310 }
3311
3312 @Override
3313 public void releaseSomeActivities(IApplicationThread appInt) {
3314 synchronized (mGlobalLock) {
3315 final long origId = Binder.clearCallingIdentity();
3316 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003317 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003318 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 } finally {
3320 Binder.restoreCallingIdentity(origId);
3321 }
3322 }
3323 }
3324
3325 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003326 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003327 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 != PackageManager.PERMISSION_GRANTED) {
3329 throw new SecurityException("Requires permission "
3330 + android.Manifest.permission.DEVICE_POWER);
3331 }
3332
3333 synchronized (mGlobalLock) {
3334 long ident = Binder.clearCallingIdentity();
3335 if (mKeyguardShown != keyguardShowing) {
3336 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003337 final Message msg = PooledLambda.obtainMessage(
3338 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3339 keyguardShowing);
3340 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 }
3342 try {
wilsonshih177261f2019-02-22 12:02:18 +08003343 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 } finally {
3345 Binder.restoreCallingIdentity(ident);
3346 }
3347 }
3348
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 mH.post(() -> {
3350 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3351 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3352 }
3353 });
3354 }
3355
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003356 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003357 mH.post(() -> {
3358 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3359 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3360 }
3361 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 }
3363
3364 @Override
3365 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3367 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 final File passedIconFile = new File(filePath);
3370 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3371 passedIconFile.getName());
3372 if (!legitIconFile.getPath().equals(filePath)
3373 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3374 throw new IllegalArgumentException("Bad file path: " + filePath
3375 + " passed for userId " + userId);
3376 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003377 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 }
3379
3380 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 synchronized (mGlobalLock) {
3384 final long ident = Binder.clearCallingIdentity();
3385 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003386 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 if (stack == null) {
3388 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3389 return;
3390 }
3391 if (!stack.isActivityTypeStandardOrUndefined()) {
3392 throw new IllegalArgumentException(
3393 "Removing non-standard stack is not allowed.");
3394 }
3395 mStackSupervisor.removeStack(stack);
3396 } finally {
3397 Binder.restoreCallingIdentity(ident);
3398 }
3399 }
3400 }
3401
3402 @Override
3403 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405
3406 synchronized (mGlobalLock) {
3407 final long ident = Binder.clearCallingIdentity();
3408 try {
3409 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3410 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003411 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
3415 }
3416 }
3417
3418 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003419 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 synchronized (mGlobalLock) {
3421 long ident = Binder.clearCallingIdentity();
3422 try {
3423 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3424 if (r == null) {
3425 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003426 "toggleFreeformWindowingMode: No activity record matching token="
3427 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 }
3429
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003430 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003431 if (stack == null) {
3432 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3433 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 }
3435
Yunfan Chend967af82019-01-17 18:30:18 +09003436 if (!stack.inFreeformWindowingMode()
3437 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3438 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3439 + "toggle between fullscreen and freeform.");
3440 }
3441
3442 if (stack.inFreeformWindowingMode()) {
3443 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003444 } else if (!mSizeCompatFreeform) {
3445 throw new IllegalStateException("Size-compat windows are currently not"
3446 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003447 } else if (stack.getParent().inFreeformWindowingMode()) {
3448 // If the window is on a freeform display, set it to undefined. It will be
3449 // resolved to freeform and it can adjust windowing mode when the display mode
3450 // changes in runtime.
3451 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003452 } else {
3453 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3454 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 } finally {
3456 Binder.restoreCallingIdentity(ident);
3457 }
3458 }
3459 }
3460
3461 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3462 @Override
3463 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003464 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003466 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 }
3468
3469 /** Unregister a task stack listener so that it stops receiving callbacks. */
3470 @Override
3471 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003474 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 }
3476
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003477 @Override
3478 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3479 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3480 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3481 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3482 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3483 }
3484
3485 @Override
3486 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3487 IBinder activityToken, int flags) {
3488 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3489 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3490 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3491 }
3492
3493 @Override
3494 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3495 Bundle args) {
3496 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3497 true /* focused */, true /* newSessionId */, userHandle, args,
3498 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3499 }
3500
3501 @Override
3502 public Bundle getAssistContextExtras(int requestType) {
3503 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3504 null, null, true /* focused */, true /* newSessionId */,
3505 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3506 if (pae == null) {
3507 return null;
3508 }
3509 synchronized (pae) {
3510 while (!pae.haveResult) {
3511 try {
3512 pae.wait();
3513 } catch (InterruptedException e) {
3514 }
3515 }
3516 }
3517 synchronized (mGlobalLock) {
3518 buildAssistBundleLocked(pae, pae.result);
3519 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003520 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 }
3522 return pae.extras;
3523 }
3524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003525 /**
3526 * Binder IPC calls go through the public entry point.
3527 * This can be called with or without the global lock held.
3528 */
3529 private static int checkCallingPermission(String permission) {
3530 return checkPermission(
3531 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3532 }
3533
3534 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003535 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003536 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3537 mAmInternal.enforceCallingPermission(permission, func);
3538 }
3539 }
3540
3541 @VisibleForTesting
3542 int checkGetTasksPermission(String permission, int pid, int uid) {
3543 return checkPermission(permission, pid, uid);
3544 }
3545
3546 static int checkPermission(String permission, int pid, int uid) {
3547 if (permission == null) {
3548 return PackageManager.PERMISSION_DENIED;
3549 }
3550 return checkComponentPermission(permission, pid, uid, -1, true);
3551 }
3552
Wale Ogunwale214f3482018-10-04 11:00:47 -07003553 public static int checkComponentPermission(String permission, int pid, int uid,
3554 int owningUid, boolean exported) {
3555 return ActivityManagerService.checkComponentPermission(
3556 permission, pid, uid, owningUid, exported);
3557 }
3558
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3560 if (getRecentTasks().isCallerRecents(callingUid)) {
3561 // Always allow the recents component to get tasks
3562 return true;
3563 }
3564
3565 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3566 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3567 if (!allowed) {
3568 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3569 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3570 // Temporary compatibility: some existing apps on the system image may
3571 // still be requesting the old permission and not switched to the new
3572 // one; if so, we'll still allow them full access. This means we need
3573 // to see if they are holding the old permission and are a system app.
3574 try {
3575 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3576 allowed = true;
3577 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3578 + " is using old GET_TASKS but privileged; allowing");
3579 }
3580 } catch (RemoteException e) {
3581 }
3582 }
3583 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3584 + " does not hold REAL_GET_TASKS; limiting output");
3585 }
3586 return allowed;
3587 }
3588
Nicholas Sauer0259e532019-08-30 08:24:55 -07003589 boolean isCrossUserAllowed(int pid, int uid) {
3590 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3591 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3592 }
3593
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3595 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3596 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3597 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003598 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 "enqueueAssistContext()");
3600
3601 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003602 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 if (activity == null) {
3604 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3605 return null;
3606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3609 return null;
3610 }
3611 if (focused) {
3612 if (activityToken != null) {
3613 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3614 if (activity != caller) {
3615 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3616 + " is not current top " + activity);
3617 return null;
3618 }
3619 }
3620 } else {
3621 activity = ActivityRecord.forTokenLocked(activityToken);
3622 if (activity == null) {
3623 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3624 + " couldn't be found");
3625 return null;
3626 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003627 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3629 return null;
3630 }
3631 }
3632
3633 PendingAssistExtras pae;
3634 Bundle extras = new Bundle();
3635 if (args != null) {
3636 extras.putAll(args);
3637 }
3638 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003639 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640
3641 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3642 userHandle);
3643 pae.isHome = activity.isActivityTypeHome();
3644
3645 // Increment the sessionId if necessary
3646 if (newSessionId) {
3647 mViSessionId++;
3648 }
3649 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003650 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3651 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003652 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 } catch (RemoteException e) {
3655 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3656 return null;
3657 }
3658 return pae;
3659 }
3660 }
3661
3662 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3663 if (result != null) {
3664 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3665 }
3666 if (pae.hint != null) {
3667 pae.extras.putBoolean(pae.hint, true);
3668 }
3669 }
3670
3671 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3672 IAssistDataReceiver receiver;
3673 synchronized (mGlobalLock) {
3674 mPendingAssistExtras.remove(pae);
3675 receiver = pae.receiver;
3676 }
3677 if (receiver != null) {
3678 // Caller wants result sent back to them.
3679 Bundle sendBundle = new Bundle();
3680 // At least return the receiver extras
3681 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3682 try {
3683 pae.receiver.onHandleAssistData(sendBundle);
3684 } catch (RemoteException e) {
3685 }
3686 }
3687 }
3688
3689 public class PendingAssistExtras extends Binder implements Runnable {
3690 public final ActivityRecord activity;
3691 public boolean isHome;
3692 public final Bundle extras;
3693 public final Intent intent;
3694 public final String hint;
3695 public final IAssistDataReceiver receiver;
3696 public final int userHandle;
3697 public boolean haveResult = false;
3698 public Bundle result = null;
3699 public AssistStructure structure = null;
3700 public AssistContent content = null;
3701 public Bundle receiverExtras;
3702
3703 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3704 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3705 int _userHandle) {
3706 activity = _activity;
3707 extras = _extras;
3708 intent = _intent;
3709 hint = _hint;
3710 receiver = _receiver;
3711 receiverExtras = _receiverExtras;
3712 userHandle = _userHandle;
3713 }
3714
3715 @Override
3716 public void run() {
3717 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3718 synchronized (this) {
3719 haveResult = true;
3720 notifyAll();
3721 }
3722 pendingAssistExtrasTimedOut(this);
3723 }
3724 }
3725
3726 @Override
3727 public boolean isAssistDataAllowedOnCurrentActivity() {
3728 int userId;
3729 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003730 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3732 return false;
3733 }
3734
3735 final ActivityRecord activity = focusedStack.getTopActivity();
3736 if (activity == null) {
3737 return false;
3738 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003739 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 }
3741 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3742 }
3743
3744 @Override
3745 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3746 long ident = Binder.clearCallingIdentity();
3747 try {
3748 synchronized (mGlobalLock) {
3749 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003750 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 if (top != caller) {
3752 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3753 + " is not current top " + top);
3754 return false;
3755 }
3756 if (!top.nowVisible) {
3757 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3758 + " is not visible");
3759 return false;
3760 }
3761 }
3762 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3763 token);
3764 } finally {
3765 Binder.restoreCallingIdentity(ident);
3766 }
3767 }
3768
3769 @Override
3770 public boolean isRootVoiceInteraction(IBinder token) {
3771 synchronized (mGlobalLock) {
3772 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3773 if (r == null) {
3774 return false;
3775 }
3776 return r.rootVoiceInteraction;
3777 }
3778 }
3779
Wale Ogunwalef6733932018-06-27 05:14:34 -07003780 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3781 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3782 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3783 if (activityToCallback == null) return;
3784 activityToCallback.setVoiceSessionLocked(voiceSession);
3785
3786 // Inform the activity
3787 try {
3788 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3789 voiceInteractor);
3790 long token = Binder.clearCallingIdentity();
3791 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003792 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003793 } finally {
3794 Binder.restoreCallingIdentity(token);
3795 }
3796 // TODO: VI Should we cache the activity so that it's easier to find later
3797 // rather than scan through all the stacks and activities?
3798 } catch (RemoteException re) {
3799 activityToCallback.clearVoiceSessionLocked();
3800 // TODO: VI Should this terminate the voice session?
3801 }
3802 }
3803
3804 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3805 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3806 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3807 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3808 boolean wasRunningVoice = mRunningVoice != null;
3809 mRunningVoice = session;
3810 if (!wasRunningVoice) {
3811 mVoiceWakeLock.acquire();
3812 updateSleepIfNeededLocked();
3813 }
3814 }
3815 }
3816
3817 void finishRunningVoiceLocked() {
3818 if (mRunningVoice != null) {
3819 mRunningVoice = null;
3820 mVoiceWakeLock.release();
3821 updateSleepIfNeededLocked();
3822 }
3823 }
3824
3825 @Override
3826 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3827 synchronized (mGlobalLock) {
3828 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3829 if (keepAwake) {
3830 mVoiceWakeLock.acquire();
3831 } else {
3832 mVoiceWakeLock.release();
3833 }
3834 }
3835 }
3836 }
3837
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 @Override
3839 public ComponentName getActivityClassForToken(IBinder token) {
3840 synchronized (mGlobalLock) {
3841 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3842 if (r == null) {
3843 return null;
3844 }
3845 return r.intent.getComponent();
3846 }
3847 }
3848
3849 @Override
3850 public String getPackageForToken(IBinder token) {
3851 synchronized (mGlobalLock) {
3852 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3853 if (r == null) {
3854 return null;
3855 }
3856 return r.packageName;
3857 }
3858 }
3859
3860 @Override
3861 public void showLockTaskEscapeMessage(IBinder token) {
3862 synchronized (mGlobalLock) {
3863 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3864 if (r == null) {
3865 return;
3866 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003867 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 }
3869 }
3870
3871 @Override
3872 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003873 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 final long token = Binder.clearCallingIdentity();
3875 try {
3876 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003877 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(token);
3881 }
3882 }
3883
3884 /**
3885 * Try to place task to provided position. The final position might be different depending on
3886 * current user and stacks state. The task will be moved to target stack if it's currently in
3887 * different stack.
3888 */
3889 @Override
3890 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003891 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003892 synchronized (mGlobalLock) {
3893 long ident = Binder.clearCallingIdentity();
3894 try {
3895 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3896 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003897 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 if (task == null) {
3899 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3900 + taskId);
3901 }
3902
Wale Ogunwaled32da472018-11-16 07:19:28 -08003903 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003904
3905 if (stack == null) {
3906 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3907 + stackId);
3908 }
3909 if (!stack.isActivityTypeStandardOrUndefined()) {
3910 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3911 + " the position of task " + taskId + " in/to non-standard stack");
3912 }
3913
3914 // TODO: Have the callers of this API call a separate reparent method if that is
3915 // what they intended to do vs. having this method also do reparenting.
3916 if (task.getStack() == stack) {
3917 // Change position in current stack.
3918 stack.positionChildAt(task, position);
3919 } else {
3920 // Reparent to new stack.
3921 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3922 !DEFER_RESUME, "positionTaskInStack");
3923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(ident);
3926 }
3927 }
3928 }
3929
3930 @Override
3931 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3932 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3933 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003934 + Arrays.toString(horizontalSizeConfiguration) + " "
3935 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 synchronized (mGlobalLock) {
3937 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3938 if (record == null) {
3939 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3940 + "found for: " + token);
3941 }
3942 record.setSizeConfigurations(horizontalSizeConfiguration,
3943 verticalSizeConfigurations, smallestSizeConfigurations);
3944 }
3945 }
3946
3947 /**
3948 * Dismisses split-screen multi-window mode.
3949 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3950 */
3951 @Override
3952 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003953 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3955 final long ident = Binder.clearCallingIdentity();
3956 try {
3957 synchronized (mGlobalLock) {
3958 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003959 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 if (stack == null) {
3961 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3962 return;
3963 }
3964
3965 if (toTop) {
3966 // Caller wants the current split-screen primary stack to be the top stack after
3967 // it goes fullscreen, so move it to the front.
3968 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003969 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003971 // stack after it goes fullscreen, so we move the focus to the top-most
3972 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3974 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3975 if (otherStack != null) {
3976 otherStack.moveToFront("dismissSplitScreenMode_other");
3977 }
3978 }
3979
Evan Rosky10475742018-09-05 19:02:48 -07003980 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 }
3982 } finally {
3983 Binder.restoreCallingIdentity(ident);
3984 }
3985 }
3986
3987 /**
3988 * Dismisses Pip
3989 * @param animate True if the dismissal should be animated.
3990 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3991 * default animation duration should be used.
3992 */
3993 @Override
3994 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 final long ident = Binder.clearCallingIdentity();
3997 try {
3998 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003999 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004000 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 if (stack == null) {
4002 Slog.w(TAG, "dismissPip: pinned stack not found.");
4003 return;
4004 }
4005 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4006 throw new IllegalArgumentException("Stack: " + stack
4007 + " doesn't support animated resize.");
4008 }
4009 if (animate) {
4010 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4011 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4012 } else {
4013 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4014 }
4015 }
4016 } finally {
4017 Binder.restoreCallingIdentity(ident);
4018 }
4019 }
4020
4021 @Override
4022 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004023 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 synchronized (mGlobalLock) {
4025 mSuppressResizeConfigChanges = suppress;
4026 }
4027 }
4028
4029 /**
4030 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4031 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4032 * activity and clearing the task at the same time.
4033 */
4034 @Override
4035 // TODO: API should just be about changing windowing modes...
4036 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 "moveTasksToFullscreenStack()");
4039 synchronized (mGlobalLock) {
4040 final long origId = Binder.clearCallingIdentity();
4041 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004042 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 if (stack != null){
4044 if (!stack.isActivityTypeStandardOrUndefined()) {
4045 throw new IllegalArgumentException(
4046 "You can't move tasks from non-standard stacks.");
4047 }
4048 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4049 }
4050 } finally {
4051 Binder.restoreCallingIdentity(origId);
4052 }
4053 }
4054 }
4055
4056 /**
4057 * Moves the top activity in the input stackId to the pinned stack.
4058 *
4059 * @param stackId Id of stack to move the top activity to pinned stack.
4060 * @param bounds Bounds to use for pinned stack.
4061 *
4062 * @return True if the top activity of the input stack was successfully moved to the pinned
4063 * stack.
4064 */
4065 @Override
4066 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004067 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 "moveTopActivityToPinnedStack()");
4069 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004070 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4072 + "Device doesn't support picture-in-picture mode");
4073 }
4074
4075 long ident = Binder.clearCallingIdentity();
4076 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004077 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 } finally {
4079 Binder.restoreCallingIdentity(ident);
4080 }
4081 }
4082 }
4083
4084 @Override
4085 public boolean isInMultiWindowMode(IBinder token) {
4086 final long origId = Binder.clearCallingIdentity();
4087 try {
4088 synchronized (mGlobalLock) {
4089 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4090 if (r == null) {
4091 return false;
4092 }
4093 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4094 return r.inMultiWindowMode();
4095 }
4096 } finally {
4097 Binder.restoreCallingIdentity(origId);
4098 }
4099 }
4100
4101 @Override
4102 public boolean isInPictureInPictureMode(IBinder token) {
4103 final long origId = Binder.clearCallingIdentity();
4104 try {
4105 synchronized (mGlobalLock) {
4106 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4107 }
4108 } finally {
4109 Binder.restoreCallingIdentity(origId);
4110 }
4111 }
4112
4113 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004114 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4115 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 return false;
4117 }
4118
4119 // If we are animating to fullscreen then we have already dispatched the PIP mode
4120 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004121 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4122 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 }
4124
4125 @Override
4126 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4127 final long origId = Binder.clearCallingIdentity();
4128 try {
4129 synchronized (mGlobalLock) {
4130 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4131 "enterPictureInPictureMode", token, params);
4132
4133 // If the activity is already in picture in picture mode, then just return early
4134 if (isInPictureInPictureMode(r)) {
4135 return true;
4136 }
4137
4138 // Activity supports picture-in-picture, now check that we can enter PiP at this
4139 // point, if it is
4140 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4141 false /* beforeStopping */)) {
4142 return false;
4143 }
4144
4145 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004146 synchronized (mGlobalLock) {
4147 // Only update the saved args from the args that are set
4148 r.pictureInPictureArgs.copyOnlySet(params);
4149 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4150 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4151 // Adjust the source bounds by the insets for the transition down
4152 final Rect sourceBounds = new Rect(
4153 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004154 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004155 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004156 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004157 stack.setPictureInPictureAspectRatio(aspectRatio);
4158 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004159 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4160 r.info.applicationInfo.uid, r.shortComponentName,
4161 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004162 logPictureInPictureArgs(params);
4163 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 };
4165
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004166 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 // If the keyguard is showing or occluded, then try and dismiss it before
4168 // entering picture-in-picture (this will prompt the user to authenticate if the
4169 // device is currently locked).
4170 dismissKeyguard(token, new KeyguardDismissCallback() {
4171 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 public void onDismissSucceeded() {
4173 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175 }, null /* message */);
4176 } else {
4177 // Enter picture in picture immediately otherwise
4178 enterPipRunnable.run();
4179 }
4180 return true;
4181 }
4182 } finally {
4183 Binder.restoreCallingIdentity(origId);
4184 }
4185 }
4186
4187 @Override
4188 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4189 final long origId = Binder.clearCallingIdentity();
4190 try {
4191 synchronized (mGlobalLock) {
4192 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4193 "setPictureInPictureParams", token, params);
4194
4195 // Only update the saved args from the args that are set
4196 r.pictureInPictureArgs.copyOnlySet(params);
4197 if (r.inPinnedWindowingMode()) {
4198 // If the activity is already in picture-in-picture, update the pinned stack now
4199 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4200 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004201 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 if (!stack.isAnimatingBoundsToFullscreen()) {
4203 stack.setPictureInPictureAspectRatio(
4204 r.pictureInPictureArgs.getAspectRatio());
4205 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4206 }
4207 }
4208 logPictureInPictureArgs(params);
4209 }
4210 } finally {
4211 Binder.restoreCallingIdentity(origId);
4212 }
4213 }
4214
4215 @Override
4216 public int getMaxNumPictureInPictureActions(IBinder token) {
4217 // Currently, this is a static constant, but later, we may change this to be dependent on
4218 // the context of the activity
4219 return 3;
4220 }
4221
4222 private void logPictureInPictureArgs(PictureInPictureParams params) {
4223 if (params.hasSetActions()) {
4224 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4225 params.getActions().size());
4226 }
4227 if (params.hasSetAspectRatio()) {
4228 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4229 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4230 MetricsLogger.action(lm);
4231 }
4232 }
4233
4234 /**
4235 * Checks the state of the system and the activity associated with the given {@param token} to
4236 * verify that picture-in-picture is supported for that activity.
4237 *
4238 * @return the activity record for the given {@param token} if all the checks pass.
4239 */
4240 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4241 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 throw new IllegalStateException(caller
4244 + ": Device doesn't support picture-in-picture mode.");
4245 }
4246
4247 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4248 if (r == null) {
4249 throw new IllegalStateException(caller
4250 + ": Can't find activity for token=" + token);
4251 }
4252
4253 if (!r.supportsPictureInPicture()) {
4254 throw new IllegalStateException(caller
4255 + ": Current activity does not support picture-in-picture.");
4256 }
4257
4258 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004259 && !mWindowManager.isValidPictureInPictureAspectRatio(
4260 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 final float minAspectRatio = mContext.getResources().getFloat(
4262 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4263 final float maxAspectRatio = mContext.getResources().getFloat(
4264 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4265 throw new IllegalArgumentException(String.format(caller
4266 + ": Aspect ratio is too extreme (must be between %f and %f).",
4267 minAspectRatio, maxAspectRatio));
4268 }
4269
4270 // Truncate the number of actions if necessary
4271 params.truncateActions(getMaxNumPictureInPictureActions(token));
4272
4273 return r;
4274 }
4275
4276 @Override
4277 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 synchronized (mGlobalLock) {
4280 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4281 if (r == null) {
4282 throw new IllegalArgumentException("Activity does not exist; token="
4283 + activityToken);
4284 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004285 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 }
4287 }
4288
4289 @Override
4290 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4291 Rect tempDockedTaskInsetBounds,
4292 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 long ident = Binder.clearCallingIdentity();
4295 try {
4296 synchronized (mGlobalLock) {
4297 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4298 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4299 PRESERVE_WINDOWS);
4300 }
4301 } finally {
4302 Binder.restoreCallingIdentity(ident);
4303 }
4304 }
4305
4306 @Override
4307 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 final long ident = Binder.clearCallingIdentity();
4310 try {
4311 synchronized (mGlobalLock) {
4312 mStackSupervisor.setSplitScreenResizing(resizing);
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004319 /**
4320 * Check that we have the features required for VR-related API calls, and throw an exception if
4321 * not.
4322 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004323 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 if (!mContext.getPackageManager().hasSystemFeature(
4325 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4326 throw new UnsupportedOperationException("VR mode not supported on this device!");
4327 }
4328 }
4329
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 @Override
4331 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333
4334 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4335
4336 ActivityRecord r;
4337 synchronized (mGlobalLock) {
4338 r = ActivityRecord.isInStackLocked(token);
4339 }
4340
4341 if (r == null) {
4342 throw new IllegalArgumentException();
4343 }
4344
4345 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004346 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 VrManagerInternal.NO_ERROR) {
4348 return err;
4349 }
4350
4351 // Clear the binder calling uid since this path may call moveToTask().
4352 final long callingId = Binder.clearCallingIdentity();
4353 try {
4354 synchronized (mGlobalLock) {
4355 r.requestedVrComponent = (enabled) ? packageName : null;
4356
4357 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004358 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004359 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 }
4361 return 0;
4362 }
4363 } finally {
4364 Binder.restoreCallingIdentity(callingId);
4365 }
4366 }
4367
4368 @Override
4369 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4370 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4371 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004372 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4374 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4375 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004376 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 || activity.voiceSession != null) {
4378 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4379 return;
4380 }
4381 if (activity.pendingVoiceInteractionStart) {
4382 Slog.w(TAG, "Pending start of voice interaction already.");
4383 return;
4384 }
4385 activity.pendingVoiceInteractionStart = true;
4386 }
4387 LocalServices.getService(VoiceInteractionManagerInternal.class)
4388 .startLocalVoiceInteraction(callingActivity, options);
4389 }
4390
4391 @Override
4392 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4393 LocalServices.getService(VoiceInteractionManagerInternal.class)
4394 .stopLocalVoiceInteraction(callingActivity);
4395 }
4396
4397 @Override
4398 public boolean supportsLocalVoiceInteraction() {
4399 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4400 .supportsLocalVoiceInteraction();
4401 }
4402
4403 /** Notifies all listeners when the pinned stack animation starts. */
4404 @Override
4405 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004406 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 }
4408
4409 /** Notifies all listeners when the pinned stack animation ends. */
4410 @Override
4411 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004412 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
4414
4415 @Override
4416 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004417 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 final long ident = Binder.clearCallingIdentity();
4419 try {
4420 synchronized (mGlobalLock) {
4421 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4422 }
4423 } finally {
4424 Binder.restoreCallingIdentity(ident);
4425 }
4426 }
4427
4428 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431
4432 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004433 if (mWindowManager == null) {
4434 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4435 return false;
4436 }
4437
4438 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 }
4442
Riddle Hsua0022cd2019-09-09 21:12:41 +08004443 mH.sendMessage(PooledLambda.obtainMessage(
4444 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4445 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446
4447 final long origId = Binder.clearCallingIdentity();
4448 try {
4449 if (values != null) {
4450 Settings.System.clearConfiguration(values);
4451 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 UserHandle.USER_NULL, false /* deferResume */,
4454 mTmpUpdateConfigurationResult);
4455 return mTmpUpdateConfigurationResult.changes != 0;
4456 } finally {
4457 Binder.restoreCallingIdentity(origId);
4458 }
4459 }
4460 }
4461
4462 @Override
4463 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4464 CharSequence message) {
4465 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004466 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4468 }
4469 final long callingId = Binder.clearCallingIdentity();
4470 try {
4471 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004472 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 }
4474 } finally {
4475 Binder.restoreCallingIdentity(callingId);
4476 }
4477 }
4478
4479 @Override
4480 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004481 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 "cancelTaskWindowTransition()");
4483 final long ident = Binder.clearCallingIdentity();
4484 try {
4485 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004486 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 MATCH_TASK_IN_STACKS_ONLY);
4488 if (task == null) {
4489 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4490 return;
4491 }
4492 task.cancelWindowTransition();
4493 }
4494 } finally {
4495 Binder.restoreCallingIdentity(ident);
4496 }
4497 }
4498
4499 @Override
4500 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004501 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 final long ident = Binder.clearCallingIdentity();
4503 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004504 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 } finally {
4506 Binder.restoreCallingIdentity(ident);
4507 }
4508 }
4509
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004510 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4511 boolean restoreFromDisk) {
4512 final TaskRecord task;
4513 synchronized (mGlobalLock) {
4514 task = mRootActivityContainer.anyTaskForId(taskId,
4515 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4516 if (task == null) {
4517 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4518 return null;
4519 }
4520 }
4521 // Don't call this while holding the lock as this operation might hit the disk.
4522 return task.getSnapshot(reducedResolution, restoreFromDisk);
4523 }
4524
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 @Override
4526 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4527 synchronized (mGlobalLock) {
4528 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4529 if (r == null) {
4530 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4531 + token);
4532 return;
4533 }
4534 final long origId = Binder.clearCallingIdentity();
4535 try {
4536 r.setDisablePreviewScreenshots(disable);
4537 } finally {
4538 Binder.restoreCallingIdentity(origId);
4539 }
4540 }
4541 }
4542
4543 /** Return the user id of the last resumed activity. */
4544 @Override
4545 public @UserIdInt
4546 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4549 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004550 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004551 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004553 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 }
4555 }
4556
4557 @Override
4558 public void updateLockTaskFeatures(int userId, int flags) {
4559 final int callingUid = Binder.getCallingUid();
4560 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004561 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004562 "updateLockTaskFeatures()");
4563 }
4564 synchronized (mGlobalLock) {
4565 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4566 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004567 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004568 }
4569 }
4570
4571 @Override
4572 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.setShowWhenLocked(showWhenLocked);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004588 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4589 synchronized (mGlobalLock) {
4590 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4591 if (r == null) {
4592 return;
4593 }
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
4596 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4597 } finally {
4598 Binder.restoreCallingIdentity(origId);
4599 }
4600 }
4601 }
4602
4603 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004604 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4605 synchronized (mGlobalLock) {
4606 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4607 if (r == null) {
4608 return;
4609 }
4610 final long origId = Binder.clearCallingIdentity();
4611 try {
4612 r.setTurnScreenOn(turnScreenOn);
4613 } finally {
4614 Binder.restoreCallingIdentity(origId);
4615 }
4616 }
4617 }
4618
4619 @Override
4620 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004621 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004622 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004623 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 synchronized (mGlobalLock) {
4625 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4626 if (r == null) {
4627 return;
4628 }
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
4631 r.registerRemoteAnimations(definition);
4632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
4637
4638 @Override
4639 public void registerRemoteAnimationForNextActivityStart(String packageName,
4640 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004641 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004642 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004643 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 synchronized (mGlobalLock) {
4645 final long origId = Binder.clearCallingIdentity();
4646 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004647 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 packageName, adapter);
4649 } finally {
4650 Binder.restoreCallingIdentity(origId);
4651 }
4652 }
4653 }
4654
Evan Rosky966759f2019-01-15 10:33:58 -08004655 @Override
4656 public void registerRemoteAnimationsForDisplay(int displayId,
4657 RemoteAnimationDefinition definition) {
4658 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4659 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004660 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004661 synchronized (mGlobalLock) {
4662 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4663 if (display == null) {
4664 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4665 return;
4666 }
4667 final long origId = Binder.clearCallingIdentity();
4668 try {
4669 display.mDisplayContent.registerRemoteAnimations(definition);
4670 } finally {
4671 Binder.restoreCallingIdentity(origId);
4672 }
4673 }
4674 }
4675
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004676 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4677 @Override
4678 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4679 synchronized (mGlobalLock) {
4680 final long origId = Binder.clearCallingIdentity();
4681 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004682 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004683 } finally {
4684 Binder.restoreCallingIdentity(origId);
4685 }
4686 }
4687 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004688
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004689 @Override
4690 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004691 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004692 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004693 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004694 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004695 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004696 }
4697 }
4698
4699 @Override
4700 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004701 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 != PERMISSION_GRANTED) {
4703 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4704 + Binder.getCallingPid()
4705 + ", uid=" + Binder.getCallingUid()
4706 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4707 Slog.w(TAG, msg);
4708 throw new SecurityException(msg);
4709 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004710 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004712 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004713 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004714 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 }
4716 }
4717
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004718 @Override
4719 public void stopAppSwitches() {
4720 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4721 synchronized (mGlobalLock) {
4722 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004723 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 mDidAppSwitch = false;
4725 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4726 }
4727 }
4728
4729 @Override
4730 public void resumeAppSwitches() {
4731 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4732 synchronized (mGlobalLock) {
4733 // Note that we don't execute any pending app switches... we will
4734 // let those wait until either the timeout, or the next start
4735 // activity request.
4736 mAppSwitchesAllowedTime = 0;
4737 }
4738 }
4739
Ricky Wai906af482019-06-03 17:25:28 +01004740 long getLastStopAppSwitchesTime() {
4741 return mLastStopAppSwitchesTime;
4742 }
4743
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004744 void onStartActivitySetDidAppSwitch() {
4745 if (mDidAppSwitch) {
4746 // This is the second allowed switch since we stopped switches, so now just generally
4747 // allow switches. Use case:
4748 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4749 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4750 // anyone to switch again).
4751 mAppSwitchesAllowedTime = 0;
4752 } else {
4753 mDidAppSwitch = true;
4754 }
4755 }
4756
4757 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004758 boolean shouldDisableNonVrUiLocked() {
4759 return mVrController.shouldDisableNonVrUiLocked();
4760 }
4761
Wale Ogunwale53783742018-09-16 10:21:51 -07004762 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004763 // 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 +00004764 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004765 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004766 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4767 + " to main display for VR");
4768 mRootActivityContainer.moveStackToDisplay(
4769 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004770 }
4771 mH.post(() -> {
4772 if (!mVrController.onVrModeChanged(r)) {
4773 return;
4774 }
4775 synchronized (mGlobalLock) {
4776 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4777 mWindowManager.disableNonVrUi(disableNonVrUi);
4778 if (disableNonVrUi) {
4779 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4780 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004781 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 }
4783 }
4784 });
4785 }
4786
Wale Ogunwale53783742018-09-16 10:21:51 -07004787 @Override
4788 public int getPackageScreenCompatMode(String packageName) {
4789 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4790 synchronized (mGlobalLock) {
4791 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4792 }
4793 }
4794
4795 @Override
4796 public void setPackageScreenCompatMode(String packageName, int mode) {
4797 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4798 "setPackageScreenCompatMode");
4799 synchronized (mGlobalLock) {
4800 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4801 }
4802 }
4803
4804 @Override
4805 public boolean getPackageAskScreenCompat(String packageName) {
4806 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4807 synchronized (mGlobalLock) {
4808 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4809 }
4810 }
4811
4812 @Override
4813 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4814 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4815 "setPackageAskScreenCompat");
4816 synchronized (mGlobalLock) {
4817 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4818 }
4819 }
4820
Wale Ogunwale64258362018-10-16 15:13:37 -07004821 public static String relaunchReasonToString(int relaunchReason) {
4822 switch (relaunchReason) {
4823 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4824 return "window_resize";
4825 case RELAUNCH_REASON_FREE_RESIZE:
4826 return "free_resize";
4827 default:
4828 return null;
4829 }
4830 }
4831
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004832 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004833 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004834 }
4835
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004836 /** Pokes the task persister. */
4837 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4838 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4839 }
4840
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004841 boolean isKeyguardLocked() {
4842 return mKeyguardController.isKeyguardLocked();
4843 }
4844
Garfield Tan01548632018-11-27 10:15:48 -08004845 /**
4846 * Clears launch params for the given package.
4847 * @param packageNames the names of the packages of which the launch params are to be cleared
4848 */
4849 @Override
4850 public void clearLaunchParamsForPackages(List<String> packageNames) {
4851 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4852 "clearLaunchParamsForPackages");
4853 synchronized (mGlobalLock) {
4854 for (int i = 0; i < packageNames.size(); ++i) {
4855 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4856 }
4857 }
4858 }
4859
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004860 /**
4861 * Makes the display with the given id a single task instance display. I.e the display can only
4862 * contain one task.
4863 */
4864 @Override
4865 public void setDisplayToSingleTaskInstance(int displayId) {
4866 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4867 "setDisplayToSingleTaskInstance");
4868 final long origId = Binder.clearCallingIdentity();
4869 try {
4870 final ActivityDisplay display =
4871 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4872 if (display != null) {
4873 display.setDisplayToSingleTaskInstance();
4874 }
4875 } finally {
4876 Binder.restoreCallingIdentity(origId);
4877 }
4878 }
4879
Wale Ogunwale31913b52018-10-13 08:29:31 -07004880 void dumpLastANRLocked(PrintWriter pw) {
4881 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4882 if (mLastANRState == null) {
4883 pw.println(" <no ANR has occurred since boot>");
4884 } else {
4885 pw.println(mLastANRState);
4886 }
4887 }
4888
4889 void dumpLastANRTracesLocked(PrintWriter pw) {
4890 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4891
4892 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4893 if (ArrayUtils.isEmpty(files)) {
4894 pw.println(" <no ANR has occurred since boot>");
4895 return;
4896 }
4897 // Find the latest file.
4898 File latest = null;
4899 for (File f : files) {
4900 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4901 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004902 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004903 }
4904 pw.print("File: ");
4905 pw.print(latest.getName());
4906 pw.println();
4907 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4908 String line;
4909 while ((line = in.readLine()) != null) {
4910 pw.println(line);
4911 }
4912 } catch (IOException e) {
4913 pw.print("Unable to read: ");
4914 pw.print(e);
4915 pw.println();
4916 }
4917 }
4918
4919 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4920 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4921 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4922 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4923 }
4924
4925 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4926 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4927 pw.println(header);
4928
Wale Ogunwaled32da472018-11-16 07:19:28 -08004929 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 dumpPackage);
4931 boolean needSep = printedAnything;
4932
4933 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004934 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 " ResumedActivity: ");
4936 if (printed) {
4937 printedAnything = true;
4938 needSep = false;
4939 }
4940
4941 if (dumpPackage == null) {
4942 if (needSep) {
4943 pw.println();
4944 }
4945 printedAnything = true;
4946 mStackSupervisor.dump(pw, " ");
4947 }
4948
4949 if (!printedAnything) {
4950 pw.println(" (nothing)");
4951 }
4952 }
4953
4954 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004955 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004956 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004957 pw.println(" ");
4958 }
4959
4960 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4961 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4962 getActivityStartController().dump(pw, "", dumpPackage);
4963 }
4964
4965 /**
4966 * There are three things that cmd can be:
4967 * - a flattened component name that matches an existing activity
4968 * - the cmd arg isn't the flattened component name of an existing activity:
4969 * dump all activity whose component contains the cmd as a substring
4970 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004971 * <p>
4972 * The caller should not hold lock when calling this method because it will wait for the
4973 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004974 *
4975 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4976 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4977 */
4978 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4979 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4980 ArrayList<ActivityRecord> activities;
4981
4982 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004983 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 dumpFocusedStackOnly);
4985 }
4986
4987 if (activities.size() <= 0) {
4988 return false;
4989 }
4990
4991 String[] newArgs = new String[args.length - opti];
4992 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4993
4994 TaskRecord lastTask = null;
4995 boolean needSep = false;
4996 for (int i = activities.size() - 1; i >= 0; i--) {
4997 ActivityRecord r = activities.get(i);
4998 if (needSep) {
4999 pw.println();
5000 }
5001 needSep = true;
5002 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005003 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 if (lastTask != task) {
5005 lastTask = task;
5006 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005007 pw.print(" id="); pw.print(lastTask.mTaskId);
5008 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 if (dumpAll) {
5010 lastTask.dump(pw, " ");
5011 }
5012 }
5013 }
5014 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5015 }
5016 return true;
5017 }
5018
5019 /**
5020 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5021 * there is a thread associated with the activity.
5022 */
5023 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5024 final ActivityRecord r, String[] args, boolean dumpAll) {
5025 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005026 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005027 synchronized (mGlobalLock) {
5028 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5029 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5030 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005031 if (r.hasProcess()) {
5032 pw.println(r.app.getPid());
5033 appThread = r.app.getThread();
5034 } else {
5035 pw.println("(not running)");
5036 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005037 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005038 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 }
5040 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005041 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 // flush anything that is already in the PrintWriter since the thread is going
5043 // to write to the file descriptor directly
5044 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005045 try (TransferPipe tp = new TransferPipe()) {
5046 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5047 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005048 } catch (IOException e) {
5049 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5050 } catch (RemoteException e) {
5051 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5052 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005053 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005054 }
5055
sanryhuang498e77e2018-12-06 14:57:01 +08005056 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5057 boolean testPssMode) {
5058 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5059 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5060 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005061 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005062 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5063 st.toString());
5064 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005065 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5066 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5067 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005068 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5069 testPssMode);
5070 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005071 }
5072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 int getCurrentUserId() {
5074 return mAmInternal.getCurrentUserId();
5075 }
5076
5077 private void enforceNotIsolatedCaller(String caller) {
5078 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5079 throw new SecurityException("Isolated process not allowed to call " + caller);
5080 }
5081 }
5082
Wale Ogunwalef6733932018-06-27 05:14:34 -07005083 public Configuration getConfiguration() {
5084 Configuration ci;
5085 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005086 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005087 ci.userSetLocale = false;
5088 }
5089 return ci;
5090 }
5091
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005092 /**
5093 * Current global configuration information. Contains general settings for the entire system,
5094 * also corresponds to the merged configuration of the default display.
5095 */
5096 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005097 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005098 }
5099
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale) {
5102 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5103 }
5104
5105 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5106 boolean initLocale, boolean deferResume) {
5107 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5108 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5109 UserHandle.USER_NULL, deferResume);
5110 }
5111
Wale Ogunwale59507092018-10-29 09:00:30 -07005112 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005113 final long origId = Binder.clearCallingIdentity();
5114 try {
5115 synchronized (mGlobalLock) {
5116 updateConfigurationLocked(values, null, false, true, userId,
5117 false /* deferResume */);
5118 }
5119 } finally {
5120 Binder.restoreCallingIdentity(origId);
5121 }
5122 }
5123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5125 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5126 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5127 deferResume, null /* result */);
5128 }
5129
5130 /**
5131 * Do either or both things: (1) change the current configuration, and (2)
5132 * make sure the given activity is running with the (now) current
5133 * configuration. Returns true if the activity has been left running, or
5134 * false if <var>starting</var> is being destroyed to match the new
5135 * configuration.
5136 *
5137 * @param userId is only used when persistent parameter is set to true to persist configuration
5138 * for that particular user
5139 */
5140 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5141 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5142 ActivityTaskManagerService.UpdateConfigurationResult result) {
5143 int changes = 0;
5144 boolean kept = true;
5145
Riddle Hsua0022cd2019-09-09 21:12:41 +08005146 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 try {
5148 if (values != null) {
5149 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5150 deferResume);
5151 }
5152
5153 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5154 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005155 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005156 }
5157
5158 if (result != null) {
5159 result.changes = changes;
5160 result.activityRelaunched = !kept;
5161 }
5162 return kept;
5163 }
5164
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005165 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005166 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005167 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005168
5169 final ActivityDisplay defaultDisplay =
5170 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5171
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 mTempConfig.setTo(getGlobalConfiguration());
5173 final int changes = mTempConfig.updateFrom(values);
5174 if (changes == 0) {
5175 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5176 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5177 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5178 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005179 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 return 0;
5181 }
5182
5183 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5184 "Updating global configuration to: " + values);
5185
5186 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5187 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5188 values.colorMode,
5189 values.densityDpi,
5190 values.fontScale,
5191 values.hardKeyboardHidden,
5192 values.keyboard,
5193 values.keyboardHidden,
5194 values.mcc,
5195 values.mnc,
5196 values.navigation,
5197 values.navigationHidden,
5198 values.orientation,
5199 values.screenHeightDp,
5200 values.screenLayout,
5201 values.screenWidthDp,
5202 values.smallestScreenWidthDp,
5203 values.touchscreen,
5204 values.uiMode);
5205
5206
5207 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5208 final LocaleList locales = values.getLocales();
5209 int bestLocaleIndex = 0;
5210 if (locales.size() > 1) {
5211 if (mSupportedSystemLocales == null) {
5212 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5213 }
5214 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5215 }
5216 SystemProperties.set("persist.sys.locale",
5217 locales.get(bestLocaleIndex).toLanguageTag());
5218 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005219
5220 final Message m = PooledLambda.obtainMessage(
5221 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5222 locales.get(bestLocaleIndex));
5223 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 }
5225
Yunfan Chen75157d72018-07-27 14:47:21 +09005226 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227
5228 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005229 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5232 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005233 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234
5235 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005236 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237
5238 AttributeCache ac = AttributeCache.instance();
5239 if (ac != null) {
5240 ac.updateConfiguration(mTempConfig);
5241 }
5242
5243 // Make sure all resources in our process are updated right now, so that anyone who is going
5244 // to retrieve resource values after we return will be sure to get the new ones. This is
5245 // especially important during boot, where the first config change needs to guarantee all
5246 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248
5249 // We need another copy of global config because we're scheduling some calls instead of
5250 // running them in place. We need to be sure that object we send will be handled unchanged.
5251 final Configuration configCopy = new Configuration(mTempConfig);
5252 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005253 final Message msg = PooledLambda.obtainMessage(
5254 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5255 this, userId, configCopy);
5256 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005257 }
5258
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005259 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5260 for (int i = pidMap.size() - 1; i >= 0; i--) {
5261 final int pid = pidMap.keyAt(i);
5262 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005263 if (DEBUG_CONFIGURATION) {
5264 Slog.v(TAG_CONFIGURATION, "Update process config of "
5265 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005267 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268 }
5269
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005270 final Message msg = PooledLambda.obtainMessage(
5271 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5272 mAmInternal, changes, initLocale);
5273 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 // Override configuration of the default display duplicates global config, so we need to
5276 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005277 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5278 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005279
5280 return changes;
5281 }
5282
Riddle Hsua0022cd2019-09-09 21:12:41 +08005283 /** @see WindowSurfacePlacer#deferLayout */
5284 void deferWindowLayout() {
5285 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5286 // Reset the reasons at the first entrance because we only care about the changes in the
5287 // deferred scope.
5288 mLayoutReasons = 0;
5289 }
5290
5291 mWindowManager.mWindowPlacerLocked.deferLayout();
5292 }
5293
5294 /** @see WindowSurfacePlacer#continueLayout */
5295 void continueWindowLayout() {
5296 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5297 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5298 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5299 }
5300 }
5301
5302 /**
5303 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5304 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5305 * defer count is gone.
5306 */
5307 void addWindowLayoutReasons(@LayoutReason int reasons) {
5308 mLayoutReasons |= reasons;
5309 }
5310
Wale Ogunwalef6733932018-06-27 05:14:34 -07005311 private void updateEventDispatchingLocked(boolean booted) {
5312 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5313 }
5314
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005315 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5316 final ContentResolver resolver = mContext.getContentResolver();
5317 Settings.System.putConfigurationForUser(resolver, config, userId);
5318 }
5319
5320 private void sendLocaleToMountDaemonMsg(Locale l) {
5321 try {
5322 IBinder service = ServiceManager.getService("mount");
5323 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5324 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5325 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5326 } catch (RemoteException e) {
5327 Log.e(TAG, "Error storing locale for decryption UI", e);
5328 }
5329 }
5330
Alison Cichowlas3e340502018-08-07 17:15:01 -04005331 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5332 mStartActivitySources.remove(permissionToken);
5333 mExpiredStartAsCallerTokens.add(permissionToken);
5334 }
5335
5336 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5337 mExpiredStartAsCallerTokens.remove(permissionToken);
5338 }
5339
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005340 boolean isActivityStartsLoggingEnabled() {
5341 return mAmInternal.isActivityStartsLoggingEnabled();
5342 }
5343
Michal Karpinski8596ded2018-11-14 14:43:48 +00005344 boolean isBackgroundActivityStartsEnabled() {
5345 return mAmInternal.isBackgroundActivityStartsEnabled();
5346 }
5347
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 void enableScreenAfterBoot(boolean booted) {
5349 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5350 SystemClock.uptimeMillis());
5351 mWindowManager.enableScreenAfterBoot();
5352
5353 synchronized (mGlobalLock) {
5354 updateEventDispatchingLocked(booted);
5355 }
5356 }
5357
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005358 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5359 if (r == null || !r.hasProcess()) {
5360 return KEY_DISPATCHING_TIMEOUT_MS;
5361 }
5362 return getInputDispatchingTimeoutLocked(r.app);
5363 }
5364
5365 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005366 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005367 }
5368
Wale Ogunwalef6733932018-06-27 05:14:34 -07005369 /**
5370 * Decide based on the configuration whether we should show the ANR,
5371 * crash, etc dialogs. The idea is that if there is no affordance to
5372 * press the on-screen buttons, or the user experience would be more
5373 * greatly impacted than the crash itself, we shouldn't show the dialog.
5374 *
5375 * A thought: SystemUI might also want to get told about this, the Power
5376 * dialog / global actions also might want different behaviors.
5377 */
5378 private void updateShouldShowDialogsLocked(Configuration config) {
5379 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5380 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5381 && config.navigation == Configuration.NAVIGATION_NONAV);
5382 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5383 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5384 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5385 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5386 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5387 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5388 HIDE_ERROR_DIALOGS, 0) != 0;
5389 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5390 }
5391
5392 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5393 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5394 FONT_SCALE, 1.0f, userId);
5395
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005396 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005397 if (getGlobalConfiguration().fontScale == scaleFactor) {
5398 return;
5399 }
5400
5401 final Configuration configuration
5402 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5403 configuration.fontScale = scaleFactor;
5404 updatePersistentConfiguration(configuration, userId);
5405 }
5406 }
5407
5408 // Actually is sleeping or shutting down or whatever else in the future
5409 // is an inactive state.
5410 boolean isSleepingOrShuttingDownLocked() {
5411 return isSleepingLocked() || mShuttingDown;
5412 }
5413
5414 boolean isSleepingLocked() {
5415 return mSleeping;
5416 }
5417
Riddle Hsu16567132018-08-16 21:37:47 +08005418 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005419 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005420 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005421 if (task.isActivityTypeStandard()) {
5422 if (mCurAppTimeTracker != r.appTimeTracker) {
5423 // We are switching app tracking. Complete the current one.
5424 if (mCurAppTimeTracker != null) {
5425 mCurAppTimeTracker.stop();
5426 mH.obtainMessage(
5427 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005428 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 mCurAppTimeTracker = null;
5430 }
5431 if (r.appTimeTracker != null) {
5432 mCurAppTimeTracker = r.appTimeTracker;
5433 startTimeTrackingFocusedActivityLocked();
5434 }
5435 } else {
5436 startTimeTrackingFocusedActivityLocked();
5437 }
5438 } else {
5439 r.appTimeTracker = null;
5440 }
5441 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5442 // TODO: Probably not, because we don't want to resume voice on switching
5443 // back to this activity
5444 if (task.voiceInteractor != null) {
5445 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5446 } else {
5447 finishRunningVoiceLocked();
5448
5449 if (mLastResumedActivity != null) {
5450 final IVoiceInteractionSession session;
5451
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005452 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005453 if (lastResumedActivityTask != null
5454 && lastResumedActivityTask.voiceSession != null) {
5455 session = lastResumedActivityTask.voiceSession;
5456 } else {
5457 session = mLastResumedActivity.voiceSession;
5458 }
5459
5460 if (session != null) {
5461 // We had been in a voice interaction session, but now focused has
5462 // move to something different. Just finish the session, we can't
5463 // return to it and retain the proper state and synchronization with
5464 // the voice interaction service.
5465 finishVoiceTask(session);
5466 }
5467 }
5468 }
5469
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005470 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5471 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 }
5473 updateResumedAppTrace(r);
5474 mLastResumedActivity = r;
5475
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005476 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005477
5478 applyUpdateLockStateLocked(r);
5479 applyUpdateVrModeLocked(r);
5480
5481 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005482 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 r == null ? "NULL" : r.shortComponentName,
5484 reason);
5485 }
5486
5487 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5488 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005489 final ActivityTaskManagerInternal.SleepToken token =
5490 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005491 updateSleepIfNeededLocked();
5492 return token;
5493 }
5494 }
5495
5496 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005497 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005498 final boolean wasSleeping = mSleeping;
5499 boolean updateOomAdj = false;
5500
5501 if (!shouldSleep) {
5502 // If wasSleeping is true, we need to wake up activity manager state from when
5503 // we started sleeping. In either case, we need to apply the sleep tokens, which
5504 // will wake up stacks or put them to sleep as appropriate.
5505 if (wasSleeping) {
5506 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005507 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5508 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 startTimeTrackingFocusedActivityLocked();
5510 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005511 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005512 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5513 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005514 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 if (wasSleeping) {
5516 updateOomAdj = true;
5517 }
5518 } else if (!mSleeping && shouldSleep) {
5519 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005520 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5521 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 if (mCurAppTimeTracker != null) {
5523 mCurAppTimeTracker.stop();
5524 }
5525 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005526 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 mStackSupervisor.goingToSleepLocked();
5528 updateResumedAppTrace(null /* resumed */);
5529 updateOomAdj = true;
5530 }
5531 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005532 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005533 }
5534 }
5535
5536 void updateOomAdj() {
5537 mH.post(mAmInternal::updateOomAdj);
5538 }
5539
Wale Ogunwale53783742018-09-16 10:21:51 -07005540 void updateCpuStats() {
5541 mH.post(mAmInternal::updateCpuStats);
5542 }
5543
Hui Yu03d12402018-12-06 18:00:37 -08005544 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5545 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005546 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5547 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 mH.sendMessage(m);
5549 }
5550
Hui Yu03d12402018-12-06 18:00:37 -08005551 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005552 ComponentName taskRoot = null;
5553 final TaskRecord task = activity.getTaskRecord();
5554 if (task != null) {
5555 final ActivityRecord rootActivity = task.getRootActivity();
5556 if (rootActivity != null) {
5557 taskRoot = rootActivity.mActivityComponent;
5558 }
5559 }
5560
Hui Yu03d12402018-12-06 18:00:37 -08005561 final Message m = PooledLambda.obtainMessage(
5562 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005563 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005564 mH.sendMessage(m);
5565 }
5566
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005567 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5568 String hostingType) {
5569 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005570 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5571 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005572 + activity.processName);
5573 }
5574 // Post message to start process to avoid possible deadlock of calling into AMS with the
5575 // ATMS lock held.
5576 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5577 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5578 isTop, hostingType, activity.intent.getComponent());
5579 mH.sendMessage(m);
5580 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005581 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005582 }
5583 }
5584
Wale Ogunwale53783742018-09-16 10:21:51 -07005585 void setBooting(boolean booting) {
5586 mAmInternal.setBooting(booting);
5587 }
5588
5589 boolean isBooting() {
5590 return mAmInternal.isBooting();
5591 }
5592
5593 void setBooted(boolean booted) {
5594 mAmInternal.setBooted(booted);
5595 }
5596
5597 boolean isBooted() {
5598 return mAmInternal.isBooted();
5599 }
5600
5601 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5602 mH.post(() -> {
5603 if (finishBooting) {
5604 mAmInternal.finishBooting();
5605 }
5606 if (enableScreen) {
5607 mInternal.enableScreenAfterBoot(isBooted());
5608 }
5609 });
5610 }
5611
5612 void setHeavyWeightProcess(ActivityRecord root) {
5613 mHeavyWeightProcess = root.app;
5614 final Message m = PooledLambda.obtainMessage(
5615 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005616 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 mH.sendMessage(m);
5618 }
5619
5620 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5621 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5622 return;
5623 }
5624
5625 mHeavyWeightProcess = null;
5626 final Message m = PooledLambda.obtainMessage(
5627 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5628 proc.mUserId);
5629 mH.sendMessage(m);
5630 }
5631
5632 private void cancelHeavyWeightProcessNotification(int userId) {
5633 final INotificationManager inm = NotificationManager.getService();
5634 if (inm == null) {
5635 return;
5636 }
5637 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005638 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005639 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5640 } catch (RuntimeException e) {
5641 Slog.w(TAG, "Error canceling notification for service", e);
5642 } catch (RemoteException e) {
5643 }
5644
5645 }
5646
5647 private void postHeavyWeightProcessNotification(
5648 WindowProcessController proc, Intent intent, int userId) {
5649 if (proc == null) {
5650 return;
5651 }
5652
5653 final INotificationManager inm = NotificationManager.getService();
5654 if (inm == null) {
5655 return;
5656 }
5657
5658 try {
5659 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5660 String text = mContext.getString(R.string.heavy_weight_notification,
5661 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5662 Notification notification =
5663 new Notification.Builder(context,
5664 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5665 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5666 .setWhen(0)
5667 .setOngoing(true)
5668 .setTicker(text)
5669 .setColor(mContext.getColor(
5670 com.android.internal.R.color.system_notification_accent_color))
5671 .setContentTitle(text)
5672 .setContentText(
5673 mContext.getText(R.string.heavy_weight_notification_detail))
5674 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5675 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5676 new UserHandle(userId)))
5677 .build();
5678 try {
5679 inm.enqueueNotificationWithTag("android", "android", null,
5680 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5681 } catch (RuntimeException e) {
5682 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5683 } catch (RemoteException e) {
5684 }
5685 } catch (PackageManager.NameNotFoundException e) {
5686 Slog.w(TAG, "Unable to create context for heavy notification", e);
5687 }
5688
5689 }
5690
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005691 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5692 IBinder token, String resultWho, int requestCode, Intent[] intents,
5693 String[] resolvedTypes, int flags, Bundle bOptions) {
5694
5695 ActivityRecord activity = null;
5696 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5697 activity = ActivityRecord.isInStackLocked(token);
5698 if (activity == null) {
5699 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5700 return null;
5701 }
5702 if (activity.finishing) {
5703 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5704 return null;
5705 }
5706 }
5707
5708 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5709 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5710 bOptions);
5711 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5712 if (noCreate) {
5713 return rec;
5714 }
5715 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5716 if (activity.pendingResults == null) {
5717 activity.pendingResults = new HashSet<>();
5718 }
5719 activity.pendingResults.add(rec.ref);
5720 }
5721 return rec;
5722 }
5723
Andrii Kulian52d255c2018-07-13 11:32:19 -07005724 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005725 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005726 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005727 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5728 mCurAppTimeTracker.start(resumedActivity.packageName);
5729 }
5730 }
5731
5732 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5733 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005734 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005735 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5736 }
5737 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005738 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005739 constructResumedTraceName(resumed.packageName), 0);
5740 }
5741 mTracedResumedActivity = resumed;
5742 }
5743
5744 private String constructResumedTraceName(String packageName) {
5745 return "focused app: " + packageName;
5746 }
5747
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005748 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005749 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005750 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005751 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005752 // mainStack is null during startup.
5753 if (mainStack != null) {
5754 if (changes != 0 && starting == null) {
5755 // If the configuration changed, and the caller is not already
5756 // in the process of starting an activity, then find the top
5757 // activity to check if its configuration needs to change.
5758 starting = mainStack.topRunningActivityLocked();
5759 }
5760
5761 if (starting != null) {
5762 kept = starting.ensureActivityConfiguration(changes,
5763 false /* preserveWindow */);
5764 // And we need to make sure at this point that all other activities
5765 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005766 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005767 !PRESERVE_WINDOWS);
5768 }
5769 }
5770
5771 return kept;
5772 }
5773
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005774 void scheduleAppGcsLocked() {
5775 mH.post(() -> mAmInternal.scheduleAppGcs());
5776 }
5777
Wale Ogunwale53783742018-09-16 10:21:51 -07005778 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5779 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5780 }
5781
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005782 /**
5783 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5784 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5785 * on demand.
5786 */
5787 IPackageManager getPackageManager() {
5788 return AppGlobals.getPackageManager();
5789 }
5790
5791 PackageManagerInternal getPackageManagerInternalLocked() {
5792 if (mPmInternal == null) {
5793 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5794 }
5795 return mPmInternal;
5796 }
5797
Hai Zhangf4da9be2019-05-01 13:46:06 +08005798 PermissionPolicyInternal getPermissionPolicyInternal() {
5799 if (mPermissionPolicyInternal == null) {
5800 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5801 }
5802 return mPermissionPolicyInternal;
5803 }
5804
Wale Ogunwale008163e2018-07-23 23:11:08 -07005805 AppWarnings getAppWarningsLocked() {
5806 return mAppWarnings;
5807 }
5808
Wale Ogunwale214f3482018-10-04 11:00:47 -07005809 Intent getHomeIntent() {
5810 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5811 intent.setComponent(mTopComponent);
5812 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5813 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5814 intent.addCategory(Intent.CATEGORY_HOME);
5815 }
5816 return intent;
5817 }
5818
Chilun2ef71f72018-11-16 17:57:15 +08005819 /**
5820 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5821 * activities.
5822 *
5823 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5824 * component defined in config_secondaryHomeComponent.
5825 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5826 */
5827 Intent getSecondaryHomeIntent(String preferredPackage) {
5828 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005829 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5830 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5831 if (preferredPackage == null || useSystemProvidedLauncher) {
5832 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005833 final String secondaryHomeComponent = mContext.getResources().getString(
5834 com.android.internal.R.string.config_secondaryHomeComponent);
5835 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5836 } else {
5837 intent.setPackage(preferredPackage);
5838 }
5839 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5840 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5841 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5842 }
5843 return intent;
5844 }
5845
Wale Ogunwale214f3482018-10-04 11:00:47 -07005846 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5847 if (info == null) return null;
5848 ApplicationInfo newInfo = new ApplicationInfo(info);
5849 newInfo.initForUser(userId);
5850 return newInfo;
5851 }
5852
Wale Ogunwale9c103022018-10-18 07:44:54 -07005853 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005854 if (uid == SYSTEM_UID) {
5855 // The system gets to run in any process. If there are multiple processes with the same
5856 // uid, just pick the first (this should never happen).
5857 final SparseArray<WindowProcessController> procs =
5858 mProcessNames.getMap().get(processName);
5859 if (procs == null) return null;
5860 final int procCount = procs.size();
5861 for (int i = 0; i < procCount; i++) {
5862 final int procUid = procs.keyAt(i);
5863 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5864 // Don't use an app process or different user process for system component.
5865 continue;
5866 }
5867 return procs.valueAt(i);
5868 }
5869 }
5870
5871 return mProcessNames.get(processName, uid);
5872 }
5873
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005874 WindowProcessController getProcessController(IApplicationThread thread) {
5875 if (thread == null) {
5876 return null;
5877 }
5878
5879 final IBinder threadBinder = thread.asBinder();
5880 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5881 for (int i = pmap.size()-1; i >= 0; i--) {
5882 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5883 for (int j = procs.size() - 1; j >= 0; j--) {
5884 final WindowProcessController proc = procs.valueAt(j);
5885 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5886 return proc;
5887 }
5888 }
5889 }
5890
5891 return null;
5892 }
5893
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005894 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005895 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005896 if (proc == null) return null;
5897 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5898 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005899 }
5900 return null;
5901 }
5902
Riddle Hsua0536432019-02-16 00:38:59 +08005903 int getUidState(int uid) {
5904 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005905 }
5906
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005907 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005908 // A uid is considered to be foreground if it has a visible non-toast window.
5909 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005910 }
5911
Ricky Wai96f5c352019-04-10 18:40:17 +01005912 boolean isDeviceOwner(int uid) {
5913 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005914 }
5915
Ricky Wai96f5c352019-04-10 18:40:17 +01005916 void setDeviceOwnerUid(int uid) {
5917 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005918 }
5919
Wale Ogunwale9de19442018-10-18 19:05:03 -07005920 /**
5921 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5922 * the whitelist
5923 */
5924 String getPendingTempWhitelistTagForUidLocked(int uid) {
5925 return mPendingTempWhitelist.get(uid);
5926 }
5927
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005928 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5929 if (true || Build.IS_USER) {
5930 return;
5931 }
5932
5933 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5934 StrictMode.allowThreadDiskWrites();
5935 try {
5936 File tracesDir = new File("/data/anr");
5937 File tracesFile = null;
5938 try {
5939 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5940
5941 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005942 String timeString =
5943 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5944 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005945 sb.append(": ");
5946 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5947 sb.append(" since ");
5948 sb.append(msg);
5949 FileOutputStream fos = new FileOutputStream(tracesFile);
5950 fos.write(sb.toString().getBytes());
5951 if (app == null) {
5952 fos.write("\n*** No application process!".getBytes());
5953 }
5954 fos.close();
5955 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5956 } catch (IOException e) {
5957 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5958 return;
5959 }
5960
5961 if (app != null && app.getPid() > 0) {
5962 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5963 firstPids.add(app.getPid());
5964 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5965 }
5966
5967 File lastTracesFile = null;
5968 File curTracesFile = null;
5969 for (int i=9; i>=0; i--) {
5970 String name = String.format(Locale.US, "slow%02d.txt", i);
5971 curTracesFile = new File(tracesDir, name);
5972 if (curTracesFile.exists()) {
5973 if (lastTracesFile != null) {
5974 curTracesFile.renameTo(lastTracesFile);
5975 } else {
5976 curTracesFile.delete();
5977 }
5978 }
5979 lastTracesFile = curTracesFile;
5980 }
5981 tracesFile.renameTo(curTracesFile);
5982 } finally {
5983 StrictMode.setThreadPolicy(oldPolicy);
5984 }
5985 }
5986
Michal Karpinskida34cd42019-04-02 19:46:52 +01005987 boolean isAssociatedCompanionApp(int userId, int uid) {
5988 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5989 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005990 return false;
5991 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005992 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005993 }
5994
Issei Suzuki734bc942019-06-05 13:59:52 +02005995 void notifySingleTaskDisplayEmpty(int displayId) {
5996 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5997 }
5998
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005999 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006000 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006001
6002
Wale Ogunwale98875612018-10-12 07:53:02 -07006003 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6004 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006005
Riddle Hsud93a6c42018-11-29 21:50:06 +08006006 H(Looper looper) {
6007 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006008 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006009
6010 @Override
6011 public void handleMessage(Message msg) {
6012 switch (msg.what) {
6013 case REPORT_TIME_TRACKER_MSG: {
6014 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6015 tracker.deliverResult(mContext);
6016 } break;
6017 }
6018 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006019 }
6020
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006021 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006023
6024 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006025 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006026 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006027
6028 @Override
6029 public void handleMessage(Message msg) {
6030 switch (msg.what) {
6031 case DISMISS_DIALOG_UI_MSG: {
6032 final Dialog d = (Dialog) msg.obj;
6033 d.dismiss();
6034 break;
6035 }
6036 }
6037 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006038 }
6039
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006040 final class LocalService extends ActivityTaskManagerInternal {
6041 @Override
6042 public SleepToken acquireSleepToken(String tag, int displayId) {
6043 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046
6047 @Override
6048 public ComponentName getHomeActivityForUser(int userId) {
6049 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006050 final ActivityRecord homeActivity =
6051 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006052 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054 }
6055
6056 @Override
6057 public void onLocalVoiceInteractionStarted(IBinder activity,
6058 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6059 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006060 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062 }
6063
6064 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006065 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006066 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006067 synchronized (mGlobalLock) {
6068 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006069 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 }
6071 }
6072
6073 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006074 public void notifySingleTaskDisplayDrawn(int displayId) {
6075 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6076 }
6077
6078 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006079 public void notifyAppTransitionFinished() {
6080 synchronized (mGlobalLock) {
6081 mStackSupervisor.notifyAppTransitionDone();
6082 }
6083 }
6084
6085 @Override
6086 public void notifyAppTransitionCancelled() {
6087 synchronized (mGlobalLock) {
6088 mStackSupervisor.notifyAppTransitionDone();
6089 }
6090 }
6091
6092 @Override
6093 public List<IBinder> getTopVisibleActivities() {
6094 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006095 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006096 }
6097 }
6098
6099 @Override
6100 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6101 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006102 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 }
6104 }
6105
6106 @Override
6107 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6108 Bundle bOptions) {
6109 Preconditions.checkNotNull(intents, "intents");
6110 final String[] resolvedTypes = new String[intents.length];
6111
6112 // UID of the package on user userId.
6113 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6114 // packageUid may not be initialized.
6115 int packageUid = 0;
6116 final long ident = Binder.clearCallingIdentity();
6117
6118 try {
6119 for (int i = 0; i < intents.length; i++) {
6120 resolvedTypes[i] =
6121 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6122 }
6123
6124 packageUid = AppGlobals.getPackageManager().getPackageUid(
6125 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6126 } catch (RemoteException e) {
6127 // Shouldn't happen.
6128 } finally {
6129 Binder.restoreCallingIdentity(ident);
6130 }
6131
Riddle Hsu591bf612019-02-14 17:55:31 +08006132 return getActivityStartController().startActivitiesInPackage(
6133 packageUid, packageName,
6134 intents, resolvedTypes, null /* resultTo */,
6135 SafeActivityOptions.fromBundle(bOptions), userId,
6136 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6137 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 }
6139
6140 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006141 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6142 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6143 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6144 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006145 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006146 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006147 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6148 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6149 userId, validateIncomingUser, originatingPendingIntent,
6150 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006151 }
6152 }
6153
6154 @Override
6155 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6156 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6157 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6158 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006159 PendingIntentRecord originatingPendingIntent,
6160 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006161 synchronized (mGlobalLock) {
6162 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6163 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6164 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006165 validateIncomingUser, originatingPendingIntent,
6166 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006167 }
6168 }
6169
6170 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6172 Intent intent, Bundle options, int userId) {
6173 return ActivityTaskManagerService.this.startActivityAsUser(
6174 caller, callerPacakge, intent,
6175 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6176 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6177 false /*validateIncomingUser*/);
6178 }
6179
6180 @Override
lumark588a3e82018-07-20 18:53:54 +08006181 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 synchronized (mGlobalLock) {
6183
6184 // We might change the visibilities here, so prepare an empty app transition which
6185 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006186 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006187 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006188 if (activityDisplay == null) {
6189 return;
6190 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006191 final DisplayContent dc = activityDisplay.mDisplayContent;
6192 final boolean wasTransitionSet =
6193 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006195 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006197 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198
6199 // If there was a transition set already we don't want to interfere with it as we
6200 // might be starting it too early.
6201 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006202 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006203 }
6204 }
6205 if (callback != null) {
6206 callback.run();
6207 }
6208 }
6209
6210 @Override
6211 public void notifyKeyguardTrustedChanged() {
6212 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006213 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006214 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 }
6216 }
6217 }
6218
6219 /**
6220 * Called after virtual display Id is updated by
6221 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6222 * {@param vrVr2dDisplayId}.
6223 */
6224 @Override
6225 public void setVr2dDisplayId(int vr2dDisplayId) {
6226 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6227 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006228 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 }
6230 }
6231
6232 @Override
6233 public void setFocusedActivity(IBinder token) {
6234 synchronized (mGlobalLock) {
6235 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6236 if (r == null) {
6237 throw new IllegalArgumentException(
6238 "setFocusedActivity: No activity record matching token=" + token);
6239 }
Louis Chang19443452018-10-09 12:10:21 +08006240 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006241 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 }
6243 }
6244 }
6245
6246 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006247 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006248 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250
6251 @Override
6252 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006253 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255
6256 @Override
6257 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006258 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 }
6260
6261 @Override
6262 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6263 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6264 }
6265
6266 @Override
6267 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006268 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006270
6271 @Override
6272 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6273 synchronized (mGlobalLock) {
6274 mActiveVoiceInteractionServiceComponent = component;
6275 }
6276 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006277
6278 @Override
6279 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6280 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6281 return;
6282 }
6283 synchronized (mGlobalLock) {
6284 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6285 if (types == null) {
6286 if (uid < 0) {
6287 return;
6288 }
6289 types = new ArrayMap<>();
6290 mAllowAppSwitchUids.put(userId, types);
6291 }
6292 if (uid < 0) {
6293 types.remove(type);
6294 } else {
6295 types.put(type, uid);
6296 }
6297 }
6298 }
6299
6300 @Override
6301 public void onUserStopped(int userId) {
6302 synchronized (mGlobalLock) {
6303 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6304 mAllowAppSwitchUids.remove(userId);
6305 }
6306 }
6307
6308 @Override
6309 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6310 synchronized (mGlobalLock) {
6311 return ActivityTaskManagerService.this.isGetTasksAllowed(
6312 caller, callingPid, callingUid);
6313 }
6314 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006315
Riddle Hsua0536432019-02-16 00:38:59 +08006316 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006317 @Override
6318 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006319 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006320 mProcessNames.put(proc.mName, proc.mUid, proc);
6321 }
6322 }
6323
Riddle Hsua0536432019-02-16 00:38:59 +08006324 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006325 @Override
6326 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006328 mProcessNames.remove(name, uid);
6329 }
6330 }
6331
Riddle Hsua0536432019-02-16 00:38:59 +08006332 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006333 @Override
6334 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006336 if (proc == mHomeProcess) {
6337 mHomeProcess = null;
6338 }
6339 if (proc == mPreviousProcess) {
6340 mPreviousProcess = null;
6341 }
6342 }
6343 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006344
Riddle Hsua0536432019-02-16 00:38:59 +08006345 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006346 @Override
6347 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006348 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006349 return mTopProcessState;
6350 }
6351 }
6352
Riddle Hsua0536432019-02-16 00:38:59 +08006353 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006355 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006356 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006357 return proc == mHeavyWeightProcess;
6358 }
6359 }
6360
Riddle Hsua0536432019-02-16 00:38:59 +08006361 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006362 @Override
6363 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006365 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6366 }
6367 }
6368
6369 @Override
6370 public void finishHeavyWeightApp() {
6371 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006372 if (mHeavyWeightProcess != null) {
6373 mHeavyWeightProcess.finishActivities();
6374 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006375 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6376 mHeavyWeightProcess);
6377 }
6378 }
6379
Riddle Hsua0536432019-02-16 00:38:59 +08006380 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006381 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006382 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006383 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006384 return isSleepingLocked();
6385 }
6386 }
6387
6388 @Override
6389 public boolean isShuttingDown() {
6390 synchronized (mGlobalLock) {
6391 return mShuttingDown;
6392 }
6393 }
6394
6395 @Override
6396 public boolean shuttingDown(boolean booted, int timeout) {
6397 synchronized (mGlobalLock) {
6398 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006399 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006401 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006402 return mStackSupervisor.shutdownLocked(timeout);
6403 }
6404 }
6405
6406 @Override
6407 public void enableScreenAfterBoot(boolean booted) {
6408 synchronized (mGlobalLock) {
6409 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6410 SystemClock.uptimeMillis());
6411 mWindowManager.enableScreenAfterBoot();
6412 updateEventDispatchingLocked(booted);
6413 }
6414 }
6415
6416 @Override
6417 public boolean showStrictModeViolationDialog() {
6418 synchronized (mGlobalLock) {
6419 return mShowDialogs && !mSleeping && !mShuttingDown;
6420 }
6421 }
6422
6423 @Override
6424 public void showSystemReadyErrorDialogsIfNeeded() {
6425 synchronized (mGlobalLock) {
6426 try {
6427 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6428 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6429 + " data partition or your device will be unstable.");
6430 mUiHandler.post(() -> {
6431 if (mShowDialogs) {
6432 AlertDialog d = new BaseErrorDialog(mUiContext);
6433 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6434 d.setCancelable(false);
6435 d.setTitle(mUiContext.getText(R.string.android_system_label));
6436 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6437 d.setButton(DialogInterface.BUTTON_POSITIVE,
6438 mUiContext.getText(R.string.ok),
6439 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6440 d.show();
6441 }
6442 });
6443 }
6444 } catch (RemoteException e) {
6445 }
6446
6447 if (!Build.isBuildConsistent()) {
6448 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6449 mUiHandler.post(() -> {
6450 if (mShowDialogs) {
6451 AlertDialog d = new BaseErrorDialog(mUiContext);
6452 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6453 d.setCancelable(false);
6454 d.setTitle(mUiContext.getText(R.string.android_system_label));
6455 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6456 d.setButton(DialogInterface.BUTTON_POSITIVE,
6457 mUiContext.getText(R.string.ok),
6458 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6459 d.show();
6460 }
6461 });
6462 }
6463 }
6464 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006465
6466 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006467 public void onProcessMapped(int pid, WindowProcessController proc) {
6468 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006469 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006470 }
6471 }
6472
6473 @Override
6474 public void onProcessUnMapped(int pid) {
6475 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006476 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006477 }
6478 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006479
6480 @Override
6481 public void onPackageDataCleared(String name) {
6482 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006483 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006484 mAppWarnings.onPackageDataCleared(name);
6485 }
6486 }
6487
6488 @Override
6489 public void onPackageUninstalled(String name) {
6490 synchronized (mGlobalLock) {
6491 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006492 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006493 }
6494 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006495
6496 @Override
6497 public void onPackageAdded(String name, boolean replacing) {
6498 synchronized (mGlobalLock) {
6499 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6500 }
6501 }
6502
6503 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006504 public void onPackageReplaced(ApplicationInfo aInfo) {
6505 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006506 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006507 }
6508 }
6509
6510 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006511 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6512 synchronized (mGlobalLock) {
6513 return compatibilityInfoForPackageLocked(ai);
6514 }
6515 }
6516
Yunfan Chen75157d72018-07-27 14:47:21 +09006517 /**
6518 * Set the corresponding display information for the process global configuration. To be
6519 * called when we need to show IME on a different display.
6520 *
6521 * @param pid The process id associated with the IME window.
6522 * @param displayId The ID of the display showing the IME.
6523 */
6524 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006525 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006526 // Don't update process-level configuration for Multi-Client IME process since other
6527 // IMEs on other displays will also receive this configuration change due to IME
6528 // services use the same application config/context.
6529 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006530
Yunfan Chen75157d72018-07-27 14:47:21 +09006531 if (pid == MY_PID || pid < 0) {
6532 if (DEBUG_CONFIGURATION) {
6533 Slog.w(TAG,
6534 "Trying to update display configuration for system/invalid process.");
6535 }
6536 return;
6537 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006538 synchronized (mGlobalLock) {
6539 final ActivityDisplay activityDisplay =
6540 mRootActivityContainer.getActivityDisplay(displayId);
6541 if (activityDisplay == null) {
6542 // Call might come when display is not yet added or has been removed.
6543 if (DEBUG_CONFIGURATION) {
6544 Slog.w(TAG, "Trying to update display configuration for non-existing "
6545 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006546 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006547 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006548 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006549 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006550 if (process == null) {
6551 if (DEBUG_CONFIGURATION) {
6552 Slog.w(TAG, "Trying to update display configuration for invalid "
6553 + "process, pid=" + pid);
6554 }
6555 return;
6556 }
lumarkddc77fb2019-06-27 22:22:23 +08006557 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006558 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6559 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006560 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006561
6562 @Override
6563 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006564 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006565 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006566 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6567 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006568 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006569 }
6570 }
6571 }
6572
6573 @Override
6574 public void clearPendingResultForActivity(IBinder activityToken,
6575 WeakReference<PendingIntentRecord> pir) {
6576 synchronized (mGlobalLock) {
6577 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6578 if (r != null && r.pendingResults != null) {
6579 r.pendingResults.remove(pir);
6580 }
6581 }
6582 }
6583
6584 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006585 public ActivityTokens getTopActivityForTask(int taskId) {
6586 synchronized (mGlobalLock) {
6587 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6588 if (taskRecord == null) {
6589 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6590 + " Requested task not found");
6591 return null;
6592 }
6593 final ActivityRecord activity = taskRecord.getTopActivity();
6594 if (activity == null) {
6595 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6596 + " Requested activity not found");
6597 return null;
6598 }
6599 if (!activity.attachedToProcess()) {
6600 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6601 + activity);
6602 return null;
6603 }
6604 return new ActivityTokens(activity.appToken, activity.assistToken,
6605 activity.app.getThread());
6606 }
6607 }
6608
6609 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006610 public IIntentSender getIntentSender(int type, String packageName,
6611 int callingUid, int userId, IBinder token, String resultWho,
6612 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6613 Bundle bOptions) {
6614 synchronized (mGlobalLock) {
6615 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6616 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6617 }
6618 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006619
6620 @Override
6621 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6622 synchronized (mGlobalLock) {
6623 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6624 if (r == null) {
6625 return null;
6626 }
6627 if (r.mServiceConnectionsHolder == null) {
6628 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6629 ActivityTaskManagerService.this, r);
6630 }
6631
6632 return r.mServiceConnectionsHolder;
6633 }
6634 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006635
6636 @Override
6637 public Intent getHomeIntent() {
6638 synchronized (mGlobalLock) {
6639 return ActivityTaskManagerService.this.getHomeIntent();
6640 }
6641 }
6642
6643 @Override
6644 public boolean startHomeActivity(int userId, String reason) {
6645 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006646 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006647 }
6648 }
6649
6650 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006651 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006652 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006653 synchronized (mGlobalLock) {
6654 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006655 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006656 }
Chilun8b1f1be2019-03-13 17:14:36 +08006657 }
6658
6659 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006660 public boolean startHomeOnAllDisplays(int userId, String reason) {
6661 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006662 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006663 }
6664 }
6665
Riddle Hsua0536432019-02-16 00:38:59 +08006666 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006667 @Override
6668 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006669 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006670 if (mFactoryTest == FACTORY_TEST_OFF) {
6671 return false;
6672 }
6673 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6674 && wpc.mName.equals(mTopComponent.getPackageName())) {
6675 return true;
6676 }
6677 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6678 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6679 }
6680 }
6681
6682 @Override
6683 public void updateTopComponentForFactoryTest() {
6684 synchronized (mGlobalLock) {
6685 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6686 return;
6687 }
6688 final ResolveInfo ri = mContext.getPackageManager()
6689 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6690 final CharSequence errorMsg;
6691 if (ri != null) {
6692 final ActivityInfo ai = ri.activityInfo;
6693 final ApplicationInfo app = ai.applicationInfo;
6694 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6695 mTopAction = Intent.ACTION_FACTORY_TEST;
6696 mTopData = null;
6697 mTopComponent = new ComponentName(app.packageName, ai.name);
6698 errorMsg = null;
6699 } else {
6700 errorMsg = mContext.getResources().getText(
6701 com.android.internal.R.string.factorytest_not_system);
6702 }
6703 } else {
6704 errorMsg = mContext.getResources().getText(
6705 com.android.internal.R.string.factorytest_no_action);
6706 }
6707 if (errorMsg == null) {
6708 return;
6709 }
6710
6711 mTopAction = null;
6712 mTopData = null;
6713 mTopComponent = null;
6714 mUiHandler.post(() -> {
6715 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6716 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006717 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006718 });
6719 }
6720 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006721
Riddle Hsua0536432019-02-16 00:38:59 +08006722 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 @Override
6724 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6725 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006726 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006727 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006728 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729
6730 wpc.clearRecentTasks();
6731 wpc.clearActivities();
6732
6733 if (wpc.isInstrumenting()) {
6734 finishInstrumentationCallback.run();
6735 }
6736
Jorim Jaggid0752812018-10-16 16:07:20 +02006737 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006738 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006739 try {
6740 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6741 // If there was nothing to resume, and we are not already restarting
6742 // this process, but there is a visible activity that is hosted by the
6743 // process...then make sure all visible activities are running, taking
6744 // care of restarting this process.
6745 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6746 !PRESERVE_WINDOWS);
6747 }
6748 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006749 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 }
6752 }
6753 }
6754
6755 @Override
6756 public void closeSystemDialogs(String reason) {
6757 enforceNotIsolatedCaller("closeSystemDialogs");
6758
6759 final int pid = Binder.getCallingPid();
6760 final int uid = Binder.getCallingUid();
6761 final long origId = Binder.clearCallingIdentity();
6762 try {
6763 synchronized (mGlobalLock) {
6764 // Only allow this from foreground processes, so that background
6765 // applications can't abuse it to prevent system UI from being shown.
6766 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006767 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 if (!proc.isPerceptible()) {
6769 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6770 + " from background process " + proc);
6771 return;
6772 }
6773 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 mWindowManager.closeSystemDialogs(reason);
6775
Wale Ogunwaled32da472018-11-16 07:19:28 -08006776 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006778 // Call into AM outside the synchronized block.
6779 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 } finally {
6781 Binder.restoreCallingIdentity(origId);
6782 }
6783 }
6784
6785 @Override
6786 public void cleanupDisabledPackageComponents(
6787 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6788 synchronized (mGlobalLock) {
6789 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006790 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006792 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 mStackSupervisor.scheduleIdleLocked();
6794 }
6795
6796 // Clean-up disabled tasks
6797 getRecentTasks().cleanupDisabledPackageTasksLocked(
6798 packageName, disabledClasses, userId);
6799 }
6800 }
6801
6802 @Override
6803 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6804 int userId) {
6805 synchronized (mGlobalLock) {
6806
6807 boolean didSomething =
6808 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 null, doit, evenPersistent, userId);
6811 return didSomething;
6812 }
6813 }
6814
6815 @Override
6816 public void resumeTopActivities(boolean scheduleIdle) {
6817 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006818 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 if (scheduleIdle) {
6820 mStackSupervisor.scheduleIdleLocked();
6821 }
6822 }
6823 }
6824
Riddle Hsua0536432019-02-16 00:38:59 +08006825 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 @Override
6827 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006828 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6830 }
6831 }
6832
Riddle Hsua0536432019-02-16 00:38:59 +08006833 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 @Override
6835 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006836 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006837 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6838 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6839 }
6840 try {
6841 return mRootActivityContainer.attachApplication(wpc);
6842 } finally {
6843 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6844 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 }
6846 }
6847
6848 @Override
6849 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6850 try {
6851 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6852 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6853 }
6854 } catch (RemoteException ex) {
6855 throw new SecurityException("Fail to check is caller a privileged app", ex);
6856 }
6857
6858 synchronized (mGlobalLock) {
6859 final long ident = Binder.clearCallingIdentity();
6860 try {
6861 if (mAmInternal.shouldConfirmCredentials(userId)) {
6862 if (mKeyguardController.isKeyguardLocked()) {
6863 // Showing launcher to avoid user entering credential twice.
6864 startHomeActivity(currentUserId, "notifyLockedProfile");
6865 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006866 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 } finally {
6869 Binder.restoreCallingIdentity(ident);
6870 }
6871 }
6872 }
6873
6874 @Override
6875 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6876 mAmInternal.enforceCallingPermission(
6877 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6878
6879 synchronized (mGlobalLock) {
6880 final long ident = Binder.clearCallingIdentity();
6881 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006882 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6883 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6886 UserHandle.CURRENT);
6887 } finally {
6888 Binder.restoreCallingIdentity(ident);
6889 }
6890 }
6891 }
6892
6893 @Override
6894 public void writeActivitiesToProto(ProtoOutputStream proto) {
6895 synchronized (mGlobalLock) {
6896 // The output proto of "activity --proto activities"
6897 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006898 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006899 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6900 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 }
6902 }
6903
6904 @Override
6905 public void saveANRState(String reason) {
6906 synchronized (mGlobalLock) {
6907 final StringWriter sw = new StringWriter();
6908 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6909 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6910 if (reason != null) {
6911 pw.println(" Reason: " + reason);
6912 }
6913 pw.println();
6914 getActivityStartController().dump(pw, " ", null);
6915 pw.println();
6916 pw.println("-------------------------------------------------------------------------------");
6917 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6918 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6919 "" /* header */);
6920 pw.println();
6921 pw.close();
6922
6923 mLastANRState = sw.toString();
6924 }
6925 }
6926
6927 @Override
6928 public void clearSavedANRState() {
6929 synchronized (mGlobalLock) {
6930 mLastANRState = null;
6931 }
6932 }
6933
6934 @Override
6935 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6936 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6937 synchronized (mGlobalLock) {
6938 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6939 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6940 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6941 dumpLastANRLocked(pw);
6942 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6943 dumpLastANRTracesLocked(pw);
6944 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6945 dumpActivityStarterLocked(pw, dumpPackage);
6946 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6947 dumpActivityContainersLocked(pw);
6948 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6949 if (getRecentTasks() != null) {
6950 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6951 }
6952 }
6953 }
6954 }
6955
6956 @Override
6957 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6958 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6959 int wakefulness) {
6960 synchronized (mGlobalLock) {
6961 if (mHomeProcess != null && (dumpPackage == null
6962 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6963 if (needSep) {
6964 pw.println();
6965 needSep = false;
6966 }
6967 pw.println(" mHomeProcess: " + mHomeProcess);
6968 }
6969 if (mPreviousProcess != null && (dumpPackage == null
6970 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6971 if (needSep) {
6972 pw.println();
6973 needSep = false;
6974 }
6975 pw.println(" mPreviousProcess: " + mPreviousProcess);
6976 }
6977 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6978 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6979 StringBuilder sb = new StringBuilder(128);
6980 sb.append(" mPreviousProcessVisibleTime: ");
6981 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6982 pw.println(sb);
6983 }
6984 if (mHeavyWeightProcess != null && (dumpPackage == null
6985 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6986 if (needSep) {
6987 pw.println();
6988 needSep = false;
6989 }
6990 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6991 }
6992 if (dumpPackage == null) {
6993 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006994 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 }
6996 if (dumpAll) {
6997 if (dumpPackage == null) {
6998 pw.println(" mConfigWillChange: "
6999 + getTopDisplayFocusedStack().mConfigWillChange);
7000 }
7001 if (mCompatModePackages.getPackages().size() > 0) {
7002 boolean printed = false;
7003 for (Map.Entry<String, Integer> entry
7004 : mCompatModePackages.getPackages().entrySet()) {
7005 String pkg = entry.getKey();
7006 int mode = entry.getValue();
7007 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7008 continue;
7009 }
7010 if (!printed) {
7011 pw.println(" mScreenCompatPackages:");
7012 printed = true;
7013 }
7014 pw.println(" " + pkg + ": " + mode);
7015 }
7016 }
7017 }
7018
7019 if (dumpPackage == null) {
7020 pw.println(" mWakefulness="
7021 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007022 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007023 if (mRunningVoice != null) {
7024 pw.println(" mRunningVoice=" + mRunningVoice);
7025 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7026 }
7027 pw.println(" mSleeping=" + mSleeping);
7028 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7029 pw.println(" mVrController=" + mVrController);
7030 }
7031 if (mCurAppTimeTracker != null) {
7032 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7033 }
7034 if (mAllowAppSwitchUids.size() > 0) {
7035 boolean printed = false;
7036 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7037 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7038 for (int j = 0; j < types.size(); j++) {
7039 if (dumpPackage == null ||
7040 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7041 if (needSep) {
7042 pw.println();
7043 needSep = false;
7044 }
7045 if (!printed) {
7046 pw.println(" mAllowAppSwitchUids:");
7047 printed = true;
7048 }
7049 pw.print(" User ");
7050 pw.print(mAllowAppSwitchUids.keyAt(i));
7051 pw.print(": Type ");
7052 pw.print(types.keyAt(j));
7053 pw.print(" = ");
7054 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7055 pw.println();
7056 }
7057 }
7058 }
7059 }
7060 if (dumpPackage == null) {
7061 if (mController != null) {
7062 pw.println(" mController=" + mController
7063 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7064 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007065 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7066 pw.println(" mLaunchingActivityWakeLock="
7067 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 }
7069
7070 return needSep;
7071 }
7072 }
7073
7074 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007075 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7076 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 synchronized (mGlobalLock) {
7078 if (dumpPackage == null) {
7079 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7080 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007081 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7082 if (mRunningVoice != null) {
7083 final long vrToken = proto.start(
7084 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7085 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7086 mRunningVoice.toString());
7087 mVoiceWakeLock.writeToProto(
7088 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7089 proto.end(vrToken);
7090 }
7091 mVrController.writeToProto(proto,
7092 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 if (mController != null) {
7094 final long token = proto.start(CONTROLLER);
7095 proto.write(CONTROLLER, mController.toString());
7096 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7097 proto.end(token);
7098 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007099 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7100 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7101 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 }
7103
7104 if (mHomeProcess != null && (dumpPackage == null
7105 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007106 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 }
7108
7109 if (mPreviousProcess != null && (dumpPackage == null
7110 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007111 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7113 }
7114
7115 if (mHeavyWeightProcess != null && (dumpPackage == null
7116 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007117 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 }
7119
7120 for (Map.Entry<String, Integer> entry
7121 : mCompatModePackages.getPackages().entrySet()) {
7122 String pkg = entry.getKey();
7123 int mode = entry.getValue();
7124 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7125 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7126 proto.write(PACKAGE, pkg);
7127 proto.write(MODE, mode);
7128 proto.end(compatToken);
7129 }
7130 }
7131
7132 if (mCurAppTimeTracker != null) {
7133 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7134 }
7135
7136 }
7137 }
7138
7139 @Override
7140 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7141 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7142 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007143 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7144 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146
7147 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007148 public void dumpForOom(PrintWriter pw) {
7149 synchronized (mGlobalLock) {
7150 pw.println(" mHomeProcess: " + mHomeProcess);
7151 pw.println(" mPreviousProcess: " + mPreviousProcess);
7152 if (mHeavyWeightProcess != null) {
7153 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7154 }
7155 }
7156 }
7157
7158 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007159 public boolean canGcNow() {
7160 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007161 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 }
7163 }
7164
Riddle Hsua0536432019-02-16 00:38:59 +08007165 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 @Override
7167 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007168 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007169 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 return top != null ? top.app : null;
7171 }
7172 }
7173
Riddle Hsua0536432019-02-16 00:38:59 +08007174 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 @Override
7176 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007177 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007178 if (mRootActivityContainer != null) {
7179 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181 }
7182 }
7183
7184 @Override
7185 public void scheduleDestroyAllActivities(String reason) {
7186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007187 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189 }
7190
7191 @Override
7192 public void removeUser(int userId) {
7193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007194 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 }
7196 }
7197
7198 @Override
7199 public boolean switchUser(int userId, UserState userState) {
7200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007201 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203 }
7204
7205 @Override
7206 public void onHandleAppCrash(WindowProcessController wpc) {
7207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007208 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007211
7212 @Override
7213 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7214 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007215 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007216 }
7217 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007218
Riddle Hsua0536432019-02-16 00:38:59 +08007219 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007220 @Override
7221 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007222 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007223 }
7224
Riddle Hsua0536432019-02-16 00:38:59 +08007225 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007226 @Override
7227 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007228 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007229 }
7230
Riddle Hsua0536432019-02-16 00:38:59 +08007231 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007232 @Override
7233 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007234 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007235 }
7236
Riddle Hsua0536432019-02-16 00:38:59 +08007237 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007238 @Override
7239 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007240 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007241 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007242
7243 @Override
7244 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007245 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007246 mPendingTempWhitelist.put(uid, tag);
7247 }
7248 }
7249
7250 @Override
7251 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007252 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007253 mPendingTempWhitelist.remove(uid);
7254 }
7255 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007256
7257 @Override
7258 public boolean handleAppCrashInActivityController(String processName, int pid,
7259 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7260 Runnable killCrashingAppCallback) {
7261 synchronized (mGlobalLock) {
7262 if (mController == null) {
7263 return false;
7264 }
7265
7266 try {
7267 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7268 stackTrace)) {
7269 killCrashingAppCallback.run();
7270 return true;
7271 }
7272 } catch (RemoteException e) {
7273 mController = null;
7274 Watchdog.getInstance().setActivityController(null);
7275 }
7276 return false;
7277 }
7278 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007279
7280 @Override
7281 public void removeRecentTasksByPackageName(String packageName, int userId) {
7282 synchronized (mGlobalLock) {
7283 mRecentTasks.removeTasksByPackageName(packageName, userId);
7284 }
7285 }
7286
7287 @Override
7288 public void cleanupRecentTasksForUser(int userId) {
7289 synchronized (mGlobalLock) {
7290 mRecentTasks.cleanupLocked(userId);
7291 }
7292 }
7293
7294 @Override
7295 public void loadRecentTasksForUser(int userId) {
7296 synchronized (mGlobalLock) {
7297 mRecentTasks.loadUserRecentsLocked(userId);
7298 }
7299 }
7300
7301 @Override
7302 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7303 synchronized (mGlobalLock) {
7304 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7305 }
7306 }
7307
7308 @Override
7309 public void flushRecentTasks() {
7310 mRecentTasks.flush();
7311 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007312
7313 @Override
7314 public WindowProcessController getHomeProcess() {
7315 synchronized (mGlobalLock) {
7316 return mHomeProcess;
7317 }
7318 }
7319
7320 @Override
7321 public WindowProcessController getPreviousProcess() {
7322 synchronized (mGlobalLock) {
7323 return mPreviousProcess;
7324 }
7325 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007326
7327 @Override
7328 public void clearLockedTasks(String reason) {
7329 synchronized (mGlobalLock) {
7330 getLockTaskController().clearLockedTasks(reason);
7331 }
7332 }
7333
7334 @Override
7335 public void updateUserConfiguration() {
7336 synchronized (mGlobalLock) {
7337 final Configuration configuration = new Configuration(getGlobalConfiguration());
7338 final int currentUserId = mAmInternal.getCurrentUserId();
7339 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7340 configuration, currentUserId, Settings.System.canWrite(mContext));
7341 updateConfigurationLocked(configuration, null /* starting */,
7342 false /* initLocale */, false /* persistent */, currentUserId,
7343 false /* deferResume */);
7344 }
7345 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007346
7347 @Override
7348 public boolean canShowErrorDialogs() {
7349 synchronized (mGlobalLock) {
7350 return mShowDialogs && !mSleeping && !mShuttingDown
7351 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7352 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7353 mAmInternal.getCurrentUserId())
7354 && !(UserManager.isDeviceInDemoMode(mContext)
7355 && mAmInternal.getCurrentUser().isDemo());
7356 }
7357 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007358
7359 @Override
7360 public void setProfileApp(String profileApp) {
7361 synchronized (mGlobalLock) {
7362 mProfileApp = profileApp;
7363 }
7364 }
7365
7366 @Override
7367 public void setProfileProc(WindowProcessController wpc) {
7368 synchronized (mGlobalLock) {
7369 mProfileProc = wpc;
7370 }
7371 }
7372
7373 @Override
7374 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7375 synchronized (mGlobalLock) {
7376 mProfilerInfo = profilerInfo;
7377 }
7378 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007379
7380 @Override
7381 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7382 synchronized (mGlobalLock) {
7383 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7384 }
7385 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007386
7387 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007388 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7389 boolean reducedResolution) {
7390 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7391 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007392 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007393
7394 @Override
7395 public boolean isUidForeground(int uid) {
7396 synchronized (mGlobalLock) {
7397 return ActivityTaskManagerService.this.isUidForeground(uid);
7398 }
7399 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007400
7401 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007402 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007403 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007404 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007405 }
7406 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007407
7408 @Override
7409 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007410 // Translate package names into UIDs
7411 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007412 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007413 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7414 if (uid >= 0) {
7415 result.add(uid);
7416 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007417 }
7418 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007419 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007420 }
7421 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007422 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007423}