blob: 3c5947a51e11420a941c945e564081eb2ecd015b [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;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070054import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
56import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
59import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070060import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040061import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.view.Display.DEFAULT_DISPLAY;
63import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070064import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070071import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
72import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080081import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070085import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
86import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
Andrii Kulian7dd39bb2019-07-22 13:11:10 -070088import static com.android.server.wm.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
90import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
91import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700109import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800113import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
114import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700115import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
116import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800117import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800119import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
120import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
121import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700122
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700123import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700124import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.annotation.Nullable;
126import android.annotation.UserIdInt;
127import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700129import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700130import android.app.ActivityOptions;
131import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700132import android.app.ActivityThread;
133import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100135import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700136import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700137import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700138import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.IApplicationThread;
140import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700141import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400142import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100213import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700263import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800265import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800277import java.lang.annotation.ElementType;
278import java.lang.annotation.Retention;
279import java.lang.annotation.RetentionPolicy;
280import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700284import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400286import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700289import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Map;
291import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292
293/**
294 * System service for managing activities and their containers (task, stacks, displays,... ).
295 *
296 * {@hide}
297 */
298public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700299 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700301 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
302 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
303 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
304 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
305 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700306 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700307
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700309 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100312 // How long we permit background activity starts after an activity in the process
313 // started or finished.
314 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315
Wale Ogunwale98875612018-10-12 07:53:02 -0700316 /** Used to indicate that an app transition should be animated. */
317 static final boolean ANIMATE = true;
318
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700319 /** Hardware-reported OpenGLES version. */
320 final int GL_ES_VERSION;
321
Wale Ogunwale31913b52018-10-13 08:29:31 -0700322 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
323 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
324 public static final String DUMP_LASTANR_CMD = "lastanr" ;
325 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
326 public static final String DUMP_STARTER_CMD = "starter" ;
327 public static final String DUMP_CONTAINERS_CMD = "containers" ;
328 public static final String DUMP_RECENTS_CMD = "recents" ;
329 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
330
Wale Ogunwale64258362018-10-16 15:13:37 -0700331 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
332 public static final int RELAUNCH_REASON_NONE = 0;
333 /** This activity is being relaunched due to windowing mode change. */
334 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
335 /** This activity is being relaunched due to a free-resize operation. */
336 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
337
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700338 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700339
Wale Ogunwalef6733932018-06-27 05:14:34 -0700340 /**
341 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
342 * change at runtime. Use mContext for non-UI purposes.
343 */
344 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700346 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700349 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700350 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800351 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800352 @VisibleForTesting
353 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 PowerManagerInternal mPowerManagerInternal;
355 private UsageStatsManagerInternal mUsageStatsInternal;
356
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700357 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 IntentFirewall mIntentFirewall;
359
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700360 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800361 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800362 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700363 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
365 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
366 *
367 * @see WindowManagerThreadPriorityBooster
368 */
369 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700370 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800371 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700372 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700373 private UserManagerService mUserManager;
374 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700375 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800376 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700377 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700378 /** All processes currently running that might have a window organized by name. */
379 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100380 /** All processes we currently have running mapped by pid and uid */
381 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** This is the process holding what we currently consider to be the "home" activity. */
383 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700384 /** The currently running heavy-weight process, if any. */
385 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700386 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /**
388 * This is the process holding the activity the user last visited that is in a different process
389 * from the one they are currently in.
390 */
391 WindowProcessController mPreviousProcess;
392 /** The time at which the previous process was last visible. */
393 long mPreviousProcessVisibleTime;
394
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700395 /** List of intents that were used to start the most recent tasks. */
396 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700397 /** State of external calls telling us if the device is awake or asleep. */
398 private boolean mKeyguardShown = false;
399
400 // Wrapper around VoiceInteractionServiceManager
401 private AssistUtils mAssistUtils;
402
403 // VoiceInteraction session ID that changes for each new request except when
404 // being called for multi-window assist in a single session.
405 private int mViSessionId = 1000;
406
407 // How long to wait in getAssistContextExtras for the activity and foreground services
408 // to respond with the result.
409 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
410
411 // How long top wait when going through the modern assist (which doesn't need to block
412 // on getting this result before starting to launch its UI).
413 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
414
415 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
416 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
417
Alison Cichowlas3e340502018-08-07 17:15:01 -0400418 // Permission tokens are used to temporarily granted a trusted app the ability to call
419 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
420 // showing any appropriate error messages to the user.
421 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
422 10 * MINUTE_IN_MILLIS;
423
424 // How long before the service actually expires a token. This is slightly longer than
425 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
426 // expiration exception.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
428 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
429
430 // How long the service will remember expired tokens, for the purpose of providing error
431 // messaging when a client uses an expired token.
432 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
433 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
434
435 // Activity tokens of system activities that are delegating their call to
436 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
437 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
438
439 // Permission tokens that have expired, but we remember for error reporting.
440 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700442 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
443
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700444 // Keeps track of the active voice interaction service component, notified from
445 // VoiceInteractionManagerService
446 ComponentName mActiveVoiceInteractionServiceComponent;
447
Michal Karpinskida34cd42019-04-02 19:46:52 +0100448 // A map userId and all its companion app uids
449 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000450
Wale Ogunwalee2172292018-10-25 10:11:10 -0700451 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 KeyguardController mKeyguardController;
453 private final ClientLifecycleManager mLifecycleManager;
454 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700455 /** The controller for all operations related to locktask. */
456 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700457 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700459 boolean mSuppressResizeConfigChanges;
460
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700461 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 new UpdateConfigurationResult();
463
464 static final class UpdateConfigurationResult {
465 // Configuration changes that were updated.
466 int changes;
467 // If the activity was relaunched to match the new configuration.
468 boolean activityRelaunched;
469
470 void reset() {
471 changes = 0;
472 activityRelaunched = false;
473 }
474 }
475
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700476 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700477 private int mConfigurationSeq;
478 // To cache the list of supported system locales
479 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480
481 /**
482 * Temp object used when global and/or display override configuration is updated. It is also
483 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
484 * anyone...
485 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private Configuration mTempConfig = new Configuration();
487
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 /** Temporary to avoid allocations. */
489 final StringBuilder mStringBuilder = new StringBuilder(256);
490
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 // Amount of time after a call to stopAppSwitches() during which we will
492 // prevent further untrusted switches from happening.
493 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
494
495 /**
496 * The time at which we will allow normal application switches again,
497 * after a call to {@link #stopAppSwitches()}.
498 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
501 * This is set to true after the first switch after mAppSwitchesAllowedTime
502 * is set; any switches after that will clear the time.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505
Ricky Wai906af482019-06-03 17:25:28 +0100506 /**
507 * Last stop app switches time, apps finished before this time cannot start background activity
508 * even if they are in grace period.
509 */
510 private long mLastStopAppSwitchesTime;
511
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512 IActivityController mController = null;
513 boolean mControllerIsAMonkey = false;
514
Wale Ogunwale214f3482018-10-04 11:00:47 -0700515 final int mFactoryTest;
516
517 /** Used to control how we initialize the service. */
518 ComponentName mTopComponent;
519 String mTopAction = Intent.ACTION_MAIN;
520 String mTopData;
521
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800522 /** Profiling app information. */
523 String mProfileApp = null;
524 WindowProcessController mProfileProc = null;
525 ProfilerInfo mProfilerInfo = null;
526
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700528 * Dump of the activity state at the time of the last ANR. Cleared after
529 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
530 */
531 String mLastANRState;
532
533 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 * Used to retain an update lock when the foreground activity is in
535 * immersive mode.
536 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700537 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538
539 /**
540 * Packages that are being allowed to perform unrestricted app switches. Mapping is
541 * User -> Type -> uid.
542 */
543 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
544
545 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private int mThumbnailWidth;
547 private int mThumbnailHeight;
548 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Flag that indicates if multi-window is enabled.
552 *
553 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
554 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
555 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
556 * At least one of the forms of multi-window must be enabled in order for this flag to be
557 * initialized to 'true'.
558 *
559 * @see #mSupportsSplitScreenMultiWindow
560 * @see #mSupportsFreeformWindowManagement
561 * @see #mSupportsPictureInPicture
562 * @see #mSupportsMultiDisplay
563 */
564 boolean mSupportsMultiWindow;
565 boolean mSupportsSplitScreenMultiWindow;
566 boolean mSupportsFreeformWindowManagement;
567 boolean mSupportsPictureInPicture;
568 boolean mSupportsMultiDisplay;
569 boolean mForceResizableActivities;
570
571 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
572
573 // VR Vr2d Display Id.
574 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700575
Wale Ogunwalef6733932018-06-27 05:14:34 -0700576 /**
577 * Set while we are wanting to sleep, to prevent any
578 * activities from being started/resumed.
579 *
580 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
581 *
582 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
583 * while in the sleep state until there is a pending transition out of sleep, in which case
584 * mSleeping is set to false, and remains false while awake.
585 *
586 * Whether mSleeping can quickly toggled between true/false without the device actually
587 * display changing states is undefined.
588 */
589 private boolean mSleeping = false;
590
591 /**
592 * The process state used for processes that are running the top activities.
593 * This changes between TOP and TOP_SLEEPING to following mSleeping.
594 */
595 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
596
597 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
598 // automatically. Important for devices without direct input devices.
599 private boolean mShowDialogs = true;
600
601 /** Set if we are shutting down the system, similar to sleeping. */
602 boolean mShuttingDown = false;
603
604 /**
605 * We want to hold a wake lock while running a voice interaction session, since
606 * this may happen with the screen off and we need to keep the CPU running to
607 * be able to continue to interact with the user.
608 */
609 PowerManager.WakeLock mVoiceWakeLock;
610
611 /**
612 * Set while we are running a voice interaction. This overrides sleeping while it is active.
613 */
614 IVoiceInteractionSession mRunningVoice;
615
616 /**
617 * The last resumed activity. This is identical to the current resumed activity most
618 * of the time but could be different when we're pausing one activity before we resume
619 * another activity.
620 */
621 ActivityRecord mLastResumedActivity;
622
623 /**
624 * The activity that is currently being traced as the active resumed activity.
625 *
626 * @see #updateResumedAppTrace
627 */
628 private @Nullable ActivityRecord mTracedResumedActivity;
629
630 /** If non-null, we are tracking the time the user spends in the currently focused app. */
631 AppTimeTracker mCurAppTimeTracker;
632
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700633 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700634
Wale Ogunwale53783742018-09-16 10:21:51 -0700635 /**
636 * Packages that the user has asked to have run in screen size
637 * compatibility mode instead of filling the screen.
638 */
639 CompatModePackages mCompatModePackages;
640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private FontScaleSettingObserver mFontScaleSettingObserver;
642
Ricky Wai96f5c352019-04-10 18:40:17 +0100643 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000644
Wale Ogunwalef6733932018-06-27 05:14:34 -0700645 private final class FontScaleSettingObserver extends ContentObserver {
646 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
647 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
648
649 public FontScaleSettingObserver() {
650 super(mH);
651 final ContentResolver resolver = mContext.getContentResolver();
652 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
653 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
654 UserHandle.USER_ALL);
655 }
656
657 @Override
658 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
659 if (mFontScaleUri.equals(uri)) {
660 updateFontScaleIfNeeded(userId);
661 } else if (mHideErrorDialogsUri.equals(uri)) {
662 synchronized (mGlobalLock) {
663 updateShouldShowDialogsLocked(getGlobalConfiguration());
664 }
665 }
666 }
667 }
668
Riddle Hsua0536432019-02-16 00:38:59 +0800669 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
670 @Target(ElementType.METHOD)
671 @Retention(RetentionPolicy.SOURCE)
672 @interface HotPath {
673 int NONE = 0;
674 int OOM_ADJUSTMENT = 1;
675 int LRU_UPDATE = 2;
676 int PROCESS_CHANGE = 3;
677 int caller() default NONE;
678 }
679
Charles Chen8d98dd22018-12-26 17:36:54 +0800680 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
681 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700682 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700683 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 mSystemThread = ActivityThread.currentActivityThread();
685 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700686 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800687 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700688 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700689 }
690
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 public void onSystemReady() {
692 synchronized (mGlobalLock) {
693 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
694 PackageManager.FEATURE_CANT_SAVE_STATE);
695 mAssistUtils = new AssistUtils(mContext);
696 mVrController.onSystemReady();
697 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700698 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700699 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700700 }
701
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700702 public void onInitPowerManagement() {
703 synchronized (mGlobalLock) {
704 mStackSupervisor.initPowerManagement();
705 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
706 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
707 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
708 mVoiceWakeLock.setReferenceCounted(false);
709 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700710 }
711
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700712 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700713 mFontScaleSettingObserver = new FontScaleSettingObserver();
714 }
715
Wale Ogunwale59507092018-10-29 09:00:30 -0700716 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717 final boolean freeformWindowManagement =
718 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
719 || Settings.Global.getInt(
720 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
721
722 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
723 final boolean supportsPictureInPicture = supportsMultiWindow &&
724 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
725 final boolean supportsSplitScreenMultiWindow =
726 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
727 final boolean supportsMultiDisplay = mContext.getPackageManager()
728 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
730 final boolean forceResizable = Settings.Global.getInt(
731 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
732
733 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900734 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735
736 final Configuration configuration = new Configuration();
737 Settings.System.getConfiguration(resolver, configuration);
738 if (forceRtl) {
739 // This will take care of setting the correct layout direction flags
740 configuration.setLayoutDirection(configuration.locale);
741 }
742
743 synchronized (mGlobalLock) {
744 mForceResizableActivities = forceResizable;
745 final boolean multiWindowFormEnabled = freeformWindowManagement
746 || supportsSplitScreenMultiWindow
747 || supportsPictureInPicture
748 || supportsMultiDisplay;
749 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
750 mSupportsMultiWindow = true;
751 mSupportsFreeformWindowManagement = freeformWindowManagement;
752 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
753 mSupportsPictureInPicture = supportsPictureInPicture;
754 mSupportsMultiDisplay = supportsMultiDisplay;
755 } else {
756 mSupportsMultiWindow = false;
757 mSupportsFreeformWindowManagement = false;
758 mSupportsSplitScreenMultiWindow = false;
759 mSupportsPictureInPicture = false;
760 mSupportsMultiDisplay = false;
761 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700818 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700819 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mKeyguardController = mStackSupervisor.getKeyguardController();
821 }
822
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700823 public void onActivityManagerInternalAdded() {
824 synchronized (mGlobalLock) {
825 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
826 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
827 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700828 }
829
Yunfan Chen75157d72018-07-27 14:47:21 +0900830 int increaseConfigurationSeqLocked() {
831 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
832 return mConfigurationSeq;
833 }
834
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 protected ActivityStackSupervisor createStackSupervisor() {
836 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
837 supervisor.initialize();
838 return supervisor;
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void setWindowManager(WindowManagerService wm) {
842 synchronized (mGlobalLock) {
843 mWindowManager = wm;
844 mLockTaskController.setWindowManager(wm);
845 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800846 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
851 synchronized (mGlobalLock) {
852 mUsageStatsInternal = usageStatsManager;
853 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700854 }
855
Wale Ogunwalef6733932018-06-27 05:14:34 -0700856 UserManagerService getUserManager() {
857 if (mUserManager == null) {
858 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
859 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
860 }
861 return mUserManager;
862 }
863
864 AppOpsService getAppOpsService() {
865 if (mAppOpsService == null) {
866 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
867 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
868 }
869 return mAppOpsService;
870 }
871
872 boolean hasUserRestriction(String restriction, int userId) {
873 return getUserManager().hasUserRestriction(restriction, userId);
874 }
875
Michal Karpinski15486842019-04-25 17:33:42 +0100876 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
877 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
878 callingUid, callingPackage);
879 if (mode == AppOpsManager.MODE_DEFAULT) {
880 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
881 == PERMISSION_GRANTED;
882 }
883 return mode == AppOpsManager.MODE_ALLOWED;
884 }
885
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700886 @VisibleForTesting
887 protected void setRecentTasks(RecentTasks recentTasks) {
888 mRecentTasks = recentTasks;
889 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700890 }
891
892 RecentTasks getRecentTasks() {
893 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700894 }
895
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700896 ClientLifecycleManager getLifecycleManager() {
897 return mLifecycleManager;
898 }
899
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700900 ActivityStartController getActivityStartController() {
901 return mActivityStartController;
902 }
903
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700904 TaskChangeNotificationController getTaskChangeNotificationController() {
905 return mTaskChangeNotificationController;
906 }
907
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700908 LockTaskController getLockTaskController() {
909 return mLockTaskController;
910 }
911
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 /**
913 * Return the global configuration used by the process corresponding to the input pid. This is
914 * usually the global configuration with some overrides specific to that process.
915 */
916 Configuration getGlobalConfigurationForCallingPid() {
917 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800918 return getGlobalConfigurationForPid(pid);
919 }
920
921 /**
922 * Return the global configuration used by the process corresponding to the given pid.
923 */
924 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900925 if (pid == MY_PID || pid < 0) {
926 return getGlobalConfiguration();
927 }
928 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100929 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 return app != null ? app.getConfiguration() : getGlobalConfiguration();
931 }
932 }
933
934 /**
935 * Return the device configuration info used by the process corresponding to the input pid.
936 * The value is consistent with the global configuration for the process.
937 */
938 @Override
939 public ConfigurationInfo getDeviceConfigurationInfo() {
940 ConfigurationInfo config = new ConfigurationInfo();
941 synchronized (mGlobalLock) {
942 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
943 config.reqTouchScreen = globalConfig.touchscreen;
944 config.reqKeyboardType = globalConfig.keyboard;
945 config.reqNavigation = globalConfig.navigation;
946 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
947 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
948 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
949 }
950 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
951 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
953 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700954 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 }
956 return config;
957 }
958
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700959 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700960 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 }
962
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700963 public static final class Lifecycle extends SystemService {
964 private final ActivityTaskManagerService mService;
965
966 public Lifecycle(Context context) {
967 super(context);
968 mService = new ActivityTaskManagerService(context);
969 }
970
971 @Override
972 public void onStart() {
973 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700974 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700975 }
976
Garfield Tan891146c2018-10-09 12:14:00 -0700977 @Override
978 public void onUnlockUser(int userId) {
979 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800980 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700981 }
982 }
983
984 @Override
985 public void onCleanupUser(int userId) {
986 synchronized (mService.getGlobalLock()) {
987 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
988 }
989 }
990
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 public ActivityTaskManagerService getService() {
992 return mService;
993 }
994 }
995
996 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997 public final int startActivity(IApplicationThread caller, String callingPackage,
998 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
999 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1000 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1001 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1002 UserHandle.getCallingUserId());
1003 }
1004
1005 @Override
1006 public final int startActivities(IApplicationThread caller, String callingPackage,
1007 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1008 int userId) {
1009 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001010 enforceNotIsolatedCaller(reason);
1011 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001013 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1014 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1015 reason, null /* originatingPendingIntent */,
1016 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1021 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1022 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1023 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1024 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1025 true /*validateIncomingUser*/);
1026 }
1027
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001028 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1030 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1031 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001034 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1036
1037 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 .setCaller(caller)
1040 .setCallingPackage(callingPackage)
1041 .setResolvedType(resolvedType)
1042 .setResultTo(resultTo)
1043 .setResultWho(resultWho)
1044 .setRequestCode(requestCode)
1045 .setStartFlags(startFlags)
1046 .setProfilerInfo(profilerInfo)
1047 .setActivityOptions(bOptions)
1048 .setMayWait(userId)
1049 .execute();
1050
1051 }
1052
1053 @Override
1054 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1055 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001056 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1057 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058 // Refuse possible leaked file descriptors
1059 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1060 throw new IllegalArgumentException("File descriptors passed in Intent");
1061 }
1062
1063 if (!(target instanceof PendingIntentRecord)) {
1064 throw new IllegalArgumentException("Bad PendingIntent object");
1065 }
1066
1067 PendingIntentRecord pir = (PendingIntentRecord)target;
1068
1069 synchronized (mGlobalLock) {
1070 // If this is coming from the currently resumed activity, it is
1071 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001072 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 if (stack.mResumedActivity != null &&
1074 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001075 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 }
1077 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081
1082 @Override
1083 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1084 Bundle bOptions) {
1085 // Refuse possible leaked file descriptors
1086 if (intent != null && intent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1090
1091 synchronized (mGlobalLock) {
1092 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1093 if (r == null) {
1094 SafeActivityOptions.abort(options);
1095 return false;
1096 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001097 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 // The caller is not running... d'oh!
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
1102 intent = new Intent(intent);
1103 // The caller is not allowed to change the data.
1104 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1105 // And we are resetting to find the next component...
1106 intent.setComponent(null);
1107
1108 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1109
1110 ActivityInfo aInfo = null;
1111 try {
1112 List<ResolveInfo> resolves =
1113 AppGlobals.getPackageManager().queryIntentActivities(
1114 intent, r.resolvedType,
1115 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1116 UserHandle.getCallingUserId()).getList();
1117
1118 // Look for the original activity in the list...
1119 final int N = resolves != null ? resolves.size() : 0;
1120 for (int i=0; i<N; i++) {
1121 ResolveInfo rInfo = resolves.get(i);
1122 if (rInfo.activityInfo.packageName.equals(r.packageName)
1123 && rInfo.activityInfo.name.equals(r.info.name)) {
1124 // We found the current one... the next matching is
1125 // after it.
1126 i++;
1127 if (i<N) {
1128 aInfo = resolves.get(i).activityInfo;
1129 }
1130 if (debug) {
1131 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1132 + "/" + r.info.name);
1133 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1134 ? "null" : aInfo.packageName + "/" + aInfo.name));
1135 }
1136 break;
1137 }
1138 }
1139 } catch (RemoteException e) {
1140 }
1141
1142 if (aInfo == null) {
1143 // Nobody who is next!
1144 SafeActivityOptions.abort(options);
1145 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1146 return false;
1147 }
1148
1149 intent.setComponent(new ComponentName(
1150 aInfo.applicationInfo.packageName, aInfo.name));
1151 intent.setFlags(intent.getFlags()&~(
1152 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1153 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1154 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1155 FLAG_ACTIVITY_NEW_TASK));
1156
1157 // Okay now we need to start the new activity, replacing the currently running activity.
1158 // This is a little tricky because we want to start the new one as if the current one is
1159 // finished, but not finish the current one first so that there is no flicker.
1160 // And thus...
1161 final boolean wasFinishing = r.finishing;
1162 r.finishing = true;
1163
1164 // Propagate reply information over to the new activity.
1165 final ActivityRecord resultTo = r.resultTo;
1166 final String resultWho = r.resultWho;
1167 final int requestCode = r.requestCode;
1168 r.resultTo = null;
1169 if (resultTo != null) {
1170 resultTo.removeResultsLocked(r, resultWho, requestCode);
1171 }
1172
1173 final long origId = Binder.clearCallingIdentity();
1174 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001175 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001177 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001178 .setResolvedType(r.resolvedType)
1179 .setActivityInfo(aInfo)
1180 .setResultTo(resultTo != null ? resultTo.appToken : null)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setCallingPid(-1)
1184 .setCallingUid(r.launchedFromUid)
1185 .setCallingPackage(r.launchedFromPackage)
1186 .setRealCallingPid(-1)
1187 .setRealCallingUid(r.launchedFromUid)
1188 .setActivityOptions(options)
1189 .execute();
1190 Binder.restoreCallingIdentity(origId);
1191
1192 r.finishing = wasFinishing;
1193 if (res != ActivityManager.START_SUCCESS) {
1194 return false;
1195 }
1196 return true;
1197 }
1198 }
1199
1200 @Override
1201 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1202 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1203 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1204 final WaitResult res = new WaitResult();
1205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001206 enforceNotIsolatedCaller("startActivityAndWait");
1207 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1208 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001210 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setCaller(caller)
1212 .setCallingPackage(callingPackage)
1213 .setResolvedType(resolvedType)
1214 .setResultTo(resultTo)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setStartFlags(startFlags)
1218 .setActivityOptions(bOptions)
1219 .setMayWait(userId)
1220 .setProfilerInfo(profilerInfo)
1221 .setWaitResult(res)
1222 .execute();
1223 }
1224 return res;
1225 }
1226
1227 @Override
1228 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, Configuration config, Bundle bOptions, int userId) {
1231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001232 enforceNotIsolatedCaller("startActivityWithConfig");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1234 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001236 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setGlobalConfiguration(config)
1245 .setActivityOptions(bOptions)
1246 .setMayWait(userId)
1247 .execute();
1248 }
1249 }
1250
Alison Cichowlas3e340502018-08-07 17:15:01 -04001251
1252 @Override
1253 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1254 int callingUid = Binder.getCallingUid();
1255 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1256 throw new SecurityException("Only the system process can request a permission token, "
1257 + "received request from uid: " + callingUid);
1258 }
1259 IBinder permissionToken = new Binder();
1260 synchronized (mGlobalLock) {
1261 mStartActivitySources.put(permissionToken, delegatorToken);
1262 }
1263
1264 Message expireMsg = PooledLambda.obtainMessage(
1265 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1266 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1267
1268 Message forgetMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1271
1272 return permissionToken;
1273 }
1274
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 @Override
1276 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1277 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001278 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1279 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 // permission grants) as any app that may launch one of your own activities. So we only
1282 // allow this in two cases:
1283 // 1) The caller is an activity that is part of the core framework, and then only when it
1284 // is running as the system.
1285 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1286 // can only be requested by a system activity, which may then delegate this call to
1287 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 final ActivityRecord sourceRecord;
1289 final int targetUid;
1290 final String targetPackage;
1291 final boolean isResolver;
1292 synchronized (mGlobalLock) {
1293 if (resultTo == null) {
1294 throw new SecurityException("Must be called from an activity");
1295 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 final IBinder sourceToken;
1297 if (permissionToken != null) {
1298 // To even attempt to use a permissionToken, an app must also have this signature
1299 // permission.
1300 mAmInternal.enforceCallingPermission(
1301 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1302 "startActivityAsCaller");
1303 // If called with a permissionToken, we want the sourceRecord from the delegator
1304 // activity that requested this token.
1305 sourceToken = mStartActivitySources.remove(permissionToken);
1306 if (sourceToken == null) {
1307 // Invalid permissionToken, check if it recently expired.
1308 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1309 throw new SecurityException("Called with expired permission token: "
1310 + permissionToken);
1311 } else {
1312 throw new SecurityException("Called with invalid permission token: "
1313 + permissionToken);
1314 }
1315 }
1316 } else {
1317 // This method was called directly by the source.
1318 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001320
Wale Ogunwaled32da472018-11-16 07:19:28 -08001321 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 if (sourceRecord == null) {
1323 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
1325 if (sourceRecord.app == null) {
1326 throw new SecurityException("Called without a process attached to activity");
1327 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001328
1329 // Whether called directly or from a delegate, the source activity must be from the
1330 // android package.
1331 if (!sourceRecord.info.packageName.equals("android")) {
1332 throw new SecurityException("Must be called from an activity that is "
1333 + "declared in the android package");
1334 }
1335
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001336 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 // This is still okay, as long as this activity is running under the
1338 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 + " must be system uid or original calling uid "
1343 + sourceRecord.launchedFromUid);
1344 }
1345 }
1346 if (ignoreTargetSecurity) {
1347 if (intent.getComponent() == null) {
1348 throw new SecurityException(
1349 "Component must be specified with ignoreTargetSecurity");
1350 }
1351 if (intent.getSelector() != null) {
1352 throw new SecurityException(
1353 "Selector not allowed with ignoreTargetSecurity");
1354 }
1355 }
1356 targetUid = sourceRecord.launchedFromUid;
1357 targetPackage = sourceRecord.launchedFromPackage;
1358 isResolver = sourceRecord.isResolverOrChildActivity();
1359 }
1360
1361 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 }
1364
1365 // TODO: Switch to user app stacks here.
1366 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(targetUid)
1369 .setCallingPackage(targetPackage)
1370 .setResolvedType(resolvedType)
1371 .setResultTo(resultTo)
1372 .setResultWho(resultWho)
1373 .setRequestCode(requestCode)
1374 .setStartFlags(startFlags)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1378 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001379 // The target may well be in the background, which would normally prevent it
1380 // from starting an activity. Here we definitely want the start to succeed.
1381 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 .execute();
1383 } catch (SecurityException e) {
1384 // XXX need to figure out how to propagate to original app.
1385 // A SecurityException here is generally actually a fault of the original
1386 // calling activity (such as a fairly granting permissions), so propagate it
1387 // back to them.
1388 /*
1389 StringBuilder msg = new StringBuilder();
1390 msg.append("While launching");
1391 msg.append(intent.toString());
1392 msg.append(": ");
1393 msg.append(e.getMessage());
1394 */
1395 throw e;
1396 }
1397 }
1398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1400 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1401 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1402 }
1403
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 @Override
1405 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1406 Intent intent, String resolvedType, IVoiceInteractionSession session,
1407 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1408 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 if (session == null || interactor == null) {
1411 throw new NullPointerException("null session or interactor");
1412 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001415 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 .setCallingUid(callingUid)
1417 .setCallingPackage(callingPackage)
1418 .setResolvedType(resolvedType)
1419 .setVoiceSession(session)
1420 .setVoiceInteractor(interactor)
1421 .setStartFlags(startFlags)
1422 .setProfilerInfo(profilerInfo)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1431 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1433 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001435 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .setCallingUid(callingUid)
1437 .setCallingPackage(callingPackage)
1438 .setResolvedType(resolvedType)
1439 .setActivityOptions(bOptions)
1440 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001441 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .execute();
1443 }
1444
Riddle Hsu609a8e22019-06-27 16:46:29 -06001445 /**
1446 * Start the recents activity to perform the recents animation.
1447 *
1448 * @param intent The intent to start the recents activity.
1449 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1450 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001452 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1453 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001456 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 final long origId = Binder.clearCallingIdentity();
1458 try {
1459 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001460 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1461 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001462 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463
1464 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001466 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001467 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 if (recentsAnimationRunner == null) {
1469 anim.preloadRecentsActivity();
1470 } else {
1471 anim.startRecentsActivity(recentsAnimationRunner);
1472 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 }
1474 } finally {
1475 Binder.restoreCallingIdentity(origId);
1476 }
1477 }
1478
1479 @Override
1480 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001481 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 "startActivityFromRecents()");
1483
1484 final int callingPid = Binder.getCallingPid();
1485 final int callingUid = Binder.getCallingUid();
1486 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1487 final long origId = Binder.clearCallingIdentity();
1488 try {
1489 synchronized (mGlobalLock) {
1490 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1491 safeOptions);
1492 }
1493 } finally {
1494 Binder.restoreCallingIdentity(origId);
1495 }
1496 }
1497
1498 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001499 * Public API to check if the client is allowed to start an activity on specified display.
1500 *
1501 * If the target display is private or virtual, some restrictions will apply.
1502 *
1503 * @param displayId Target display id.
1504 * @param intent Intent used to launch the activity.
1505 * @param resolvedType The MIME type of the intent.
1506 * @param userId The id of the user for whom the call is made.
1507 * @return {@code true} if a call to start an activity on the target display should succeed and
1508 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1509 */
1510 @Override
1511 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1512 String resolvedType, int userId) {
1513 final int callingUid = Binder.getCallingUid();
1514 final int callingPid = Binder.getCallingPid();
1515 final long origId = Binder.clearCallingIdentity();
1516
1517 try {
1518 // Collect information about the target of the Intent.
1519 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1520 0 /* startFlags */, null /* profilerInfo */, userId,
1521 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1522 UserHandle.USER_NULL));
1523 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1524
1525 synchronized (mGlobalLock) {
1526 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1527 aInfo);
1528 }
1529 } finally {
1530 Binder.restoreCallingIdentity(origId);
1531 }
1532 }
1533
1534 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 * This is the internal entry point for handling Activity.finish().
1536 *
1537 * @param token The Binder token referencing the Activity we want to finish.
1538 * @param resultCode Result code, if any, from this Activity.
1539 * @param resultData Result data (Intent), if any, from this Activity.
1540 * @param finishTask Whether to finish the task associated with this Activity.
1541 *
1542 * @return Returns true if the activity successfully finished, or false if it is still running.
1543 */
1544 @Override
1545 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1546 int finishTask) {
1547 // Refuse possible leaked file descriptors
1548 if (resultData != null && resultData.hasFileDescriptors()) {
1549 throw new IllegalArgumentException("File descriptors passed in Intent");
1550 }
1551
1552 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 if (r == null) {
1555 return true;
1556 }
1557 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001558 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001559 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 if (rootR == null) {
1561 Slog.w(TAG, "Finishing task with all activities already finished");
1562 }
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1564 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001565 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 return false;
1567 }
1568
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1570 // We should consolidate.
1571 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001573 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 if (next != null) {
1575 // ask watcher if this is allowed
1576 boolean resumeOK = true;
1577 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001578 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 Watchdog.getInstance().setActivityController(null);
1582 }
1583
1584 if (!resumeOK) {
1585 Slog.i(TAG, "Not finishing activity because controller resumed");
1586 return false;
1587 }
1588 }
1589 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001590
1591 // note down that the process has finished an activity and is in background activity
1592 // starts grace period
1593 if (r.app != null) {
1594 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1595 }
1596
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 final long origId = Binder.clearCallingIdentity();
1598 try {
1599 boolean res;
1600 final boolean finishWithRootActivity =
1601 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1602 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1603 || (finishWithRootActivity && r == rootR)) {
1604 // If requested, remove the task that is associated to this activity only if it
1605 // was the root activity in the task. The result code and data is ignored
1606 // because we don't support returning them across task boundaries. Also, to
1607 // keep backwards compatibility we remove the task from recents when finishing
1608 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001609 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 finishWithRootActivity, "finish-activity");
1611 if (!res) {
1612 Slog.i(TAG, "Removing task failed to finish activity");
1613 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001614 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001615 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 } else {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07001617 r.finishIfPossible(resultCode, resultData, "app-request",
1618 true /* oomAdj */, !PAUSE_IMMEDIATELY);
Andrii Kulian40eda672019-07-30 15:05:57 -07001619 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 if (!res) {
1621 Slog.i(TAG, "Failed to finish by app-request");
1622 }
1623 }
1624 return res;
1625 } finally {
1626 Binder.restoreCallingIdentity(origId);
1627 }
1628 }
1629 }
1630
1631 @Override
1632 public boolean finishActivityAffinity(IBinder token) {
1633 synchronized (mGlobalLock) {
1634 final long origId = Binder.clearCallingIdentity();
1635 try {
1636 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1637 if (r == null) {
1638 return false;
1639 }
1640
1641 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1642 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001643 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 return false;
1645 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001646 r.finishActivityAffinity();
1647 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1656 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001657 try {
1658 WindowProcessController proc = null;
1659 synchronized (mGlobalLock) {
1660 ActivityStack stack = ActivityRecord.getStackLocked(token);
1661 if (stack == null) {
1662 return;
1663 }
1664 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1665 false /* fromTimeout */, false /* processPausingActivities */, config);
1666 if (r != null) {
1667 proc = r.app;
1668 }
1669 if (stopProfiling && proc != null) {
1670 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 }
1672 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001673 } finally {
1674 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677
1678 @Override
1679 public final void activityResumed(IBinder token) {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001683 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 Binder.restoreCallingIdentity(origId);
1686 }
1687
1688 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001689 public final void activityTopResumedStateLost() {
1690 final long origId = Binder.clearCallingIdentity();
1691 synchronized (mGlobalLock) {
1692 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1693 }
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696
1697 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 public final void activityPaused(IBinder token) {
1699 final long origId = Binder.clearCallingIdentity();
1700 synchronized (mGlobalLock) {
1701 ActivityStack stack = ActivityRecord.getStackLocked(token);
1702 if (stack != null) {
1703 stack.activityPausedLocked(token, false);
1704 }
1705 }
1706 Binder.restoreCallingIdentity(origId);
1707 }
1708
1709 @Override
1710 public final void activityStopped(IBinder token, Bundle icicle,
1711 PersistableBundle persistentState, CharSequence description) {
1712 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1713
1714 // Refuse possible leaked file descriptors
1715 if (icicle != null && icicle.hasFileDescriptors()) {
1716 throw new IllegalArgumentException("File descriptors passed in Bundle");
1717 }
1718
1719 final long origId = Binder.clearCallingIdentity();
1720
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001721 String restartingName = null;
1722 int restartingUid = 0;
1723 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001725 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001727 if (r.attachedToProcess()
1728 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1729 // The activity was requested to restart from
1730 // {@link #restartActivityProcessIfVisible}.
1731 restartingName = r.app.mName;
1732 restartingUid = r.app.mUid;
1733 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 r.activityStoppedLocked(icicle, persistentState, description);
1735 }
1736 }
1737
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001738 if (restartingName != null) {
1739 // In order to let the foreground activity can be restarted with its saved state from
1740 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1741 // until the activity reports stopped with the state. And the activity record will be
1742 // kept because the record state is restarting, then the activity will be restarted
1743 // immediately if it is still the top one.
1744 mStackSupervisor.removeRestartTimeouts(r);
1745 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1746 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001747 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 @Override
1753 public final void activityDestroyed(IBinder token) {
1754 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1755 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001756 final long origId = Binder.clearCallingIdentity();
1757 try {
1758 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1759 if (activity != null) {
1760 activity.destroyed("activityDestroyed");
1761 }
1762 } finally {
1763 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 }
1765 }
1766 }
1767
1768 @Override
1769 public final void activityRelaunched(IBinder token) {
1770 final long origId = Binder.clearCallingIdentity();
1771 synchronized (mGlobalLock) {
1772 mStackSupervisor.activityRelaunchedLocked(token);
1773 }
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776
1777 public final void activitySlept(IBinder token) {
1778 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1779
1780 final long origId = Binder.clearCallingIdentity();
1781
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r != null) {
1785 mStackSupervisor.activitySleptLocked(r);
1786 }
1787 }
1788
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
1793 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1794 synchronized (mGlobalLock) {
1795 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return;
1798 }
1799 final long origId = Binder.clearCallingIdentity();
1800 try {
1801 r.setRequestedOrientation(requestedOrientation);
1802 } finally {
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805 }
1806 }
1807
1808 @Override
1809 public int getRequestedOrientation(IBinder token) {
1810 synchronized (mGlobalLock) {
1811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1812 if (r == null) {
1813 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1814 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001815 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 }
1817 }
1818
1819 @Override
1820 public void setImmersive(IBinder token, boolean immersive) {
1821 synchronized (mGlobalLock) {
1822 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1823 if (r == null) {
1824 throw new IllegalArgumentException();
1825 }
1826 r.immersive = immersive;
1827
1828 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001829 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 }
1833 }
1834 }
1835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 void applyUpdateLockStateLocked(ActivityRecord r) {
1837 // Modifications to the UpdateLock state are done on our handler, outside
1838 // the activity manager's locks. The new state is determined based on the
1839 // state *now* of the relevant activity record. The object is passed to
1840 // the handler solely for logging detail, not to be consulted/modified.
1841 final boolean nextState = r != null && r.immersive;
1842 mH.post(() -> {
1843 if (mUpdateLock.isHeld() != nextState) {
1844 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1845 "Applying new update lock state '" + nextState + "' for " + r);
1846 if (nextState) {
1847 mUpdateLock.acquire();
1848 } else {
1849 mUpdateLock.release();
1850 }
1851 }
1852 });
1853 }
1854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 @Override
1856 public boolean isImmersive(IBinder token) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 return r.immersive;
1863 }
1864 }
1865
1866 @Override
1867 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001870 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 return (r != null) ? r.immersive : false;
1872 }
1873 }
1874
1875 @Override
1876 public void overridePendingTransition(IBinder token, String packageName,
1877 int enterAnim, int exitAnim) {
1878 synchronized (mGlobalLock) {
1879 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1880 if (self == null) {
1881 return;
1882 }
1883
1884 final long origId = Binder.clearCallingIdentity();
1885
1886 if (self.isState(
1887 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001888 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001889 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 }
1891
1892 Binder.restoreCallingIdentity(origId);
1893 }
1894 }
1895
1896 @Override
1897 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001900 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 if (r == null) {
1902 return ActivityManager.COMPAT_MODE_UNKNOWN;
1903 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001904 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907
1908 @Override
1909 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001914 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 if (r == null) {
1916 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1917 return;
1918 }
1919 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001920 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
1922 }
1923
1924 @Override
1925 public int getLaunchedFromUid(IBinder activityToken) {
1926 ActivityRecord srec;
1927 synchronized (mGlobalLock) {
1928 srec = ActivityRecord.forTokenLocked(activityToken);
1929 }
1930 if (srec == null) {
1931 return -1;
1932 }
1933 return srec.launchedFromUid;
1934 }
1935
1936 @Override
1937 public String getLaunchedFromPackage(IBinder activityToken) {
1938 ActivityRecord srec;
1939 synchronized (mGlobalLock) {
1940 srec = ActivityRecord.forTokenLocked(activityToken);
1941 }
1942 if (srec == null) {
1943 return null;
1944 }
1945 return srec.launchedFromPackage;
1946 }
1947
1948 @Override
1949 public boolean convertFromTranslucent(IBinder token) {
1950 final long origId = Binder.clearCallingIdentity();
1951 try {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 return false;
1956 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001957 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 }
1959 } finally {
1960 Binder.restoreCallingIdentity(origId);
1961 }
1962 }
1963
1964 @Override
1965 public boolean convertToTranslucent(IBinder token, Bundle options) {
1966 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1967 final long origId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return false;
1973 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001974 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 int index = task.mActivities.lastIndexOf(r);
1976 if (index > 0) {
1977 ActivityRecord under = task.mActivities.get(index - 1);
1978 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1979 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001980 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(origId);
1984 }
1985 }
1986
1987 @Override
1988 public void notifyActivityDrawn(IBinder token) {
1989 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1990 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001991 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001993 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 }
1995 }
1996 }
1997
1998 @Override
1999 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2000 synchronized (mGlobalLock) {
2001 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2002 if (r == null) {
2003 return;
2004 }
2005 r.reportFullyDrawnLocked(restoredFromBundle);
2006 }
2007 }
2008
2009 @Override
2010 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2011 synchronized (mGlobalLock) {
2012 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2013 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2014 return stack.mDisplayId;
2015 }
2016 return DEFAULT_DISPLAY;
2017 }
2018 }
2019
2020 @Override
2021 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 long ident = Binder.clearCallingIdentity();
2024 try {
2025 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002026 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002028 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 }
2030 return null;
2031 }
2032 } finally {
2033 Binder.restoreCallingIdentity(ident);
2034 }
2035 }
2036
2037 @Override
2038 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002039 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2041 final long callingId = Binder.clearCallingIdentity();
2042 try {
2043 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002044 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 if (stack == null) {
2046 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2047 return;
2048 }
2049 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002050 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 }
2054 } finally {
2055 Binder.restoreCallingIdentity(callingId);
2056 }
2057 }
2058
2059 @Override
2060 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002061 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2063 final long callingId = Binder.clearCallingIdentity();
2064 try {
2065 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002066 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002067 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (task == null) {
2069 return;
2070 }
2071 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002072 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002073 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 }
2075 }
2076 } finally {
2077 Binder.restoreCallingIdentity(callingId);
2078 }
2079 }
2080
2081 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002082 public void restartActivityProcessIfVisible(IBinder activityToken) {
2083 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2084 final long callingId = Binder.clearCallingIdentity();
2085 try {
2086 synchronized (mGlobalLock) {
2087 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2088 if (r == null) {
2089 return;
2090 }
2091 r.restartProcessIfVisible();
2092 }
2093 } finally {
2094 Binder.restoreCallingIdentity(callingId);
2095 }
2096 }
2097
2098 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002100 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 synchronized (mGlobalLock) {
2102 final long ident = Binder.clearCallingIdentity();
2103 try {
2104 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2105 "remove-task");
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
2109 }
2110 }
2111
2112 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002113 public void removeAllVisibleRecentTasks() {
2114 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2115 synchronized (mGlobalLock) {
2116 final long ident = Binder.clearCallingIdentity();
2117 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002118 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002119 } finally {
2120 Binder.restoreCallingIdentity(ident);
2121 }
2122 }
2123 }
2124
2125 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2127 synchronized (mGlobalLock) {
2128 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2129 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002130 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 }
2132 }
2133 return false;
2134 }
2135
2136 @Override
2137 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2138 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002139
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002140 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2142 if (r != null) {
2143 return r.getActivityStack().navigateUpToLocked(
2144 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002145 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002146 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 }
2149
2150 /**
2151 * Attempts to move a task backwards in z-order (the order of activities within the task is
2152 * unchanged).
2153 *
2154 * There are several possible results of this call:
2155 * - if the task is locked, then we will show the lock toast
2156 * - if there is a task behind the provided task, then that task is made visible and resumed as
2157 * this task is moved to the back
2158 * - otherwise, if there are no other tasks in the stack:
2159 * - if this task is in the pinned stack, then we remove the stack completely, which will
2160 * have the effect of moving the task to the top or bottom of the fullscreen stack
2161 * (depending on whether it is visible)
2162 * - otherwise, we simply return home and hide this task
2163 *
2164 * @param token A reference to the activity we wish to move
2165 * @param nonRoot If false then this only works if the activity is the root
2166 * of a task; if true it will work for any activity in a task.
2167 * @return Returns true if the move completed, false if not.
2168 */
2169 @Override
2170 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002171 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 synchronized (mGlobalLock) {
2173 final long origId = Binder.clearCallingIdentity();
2174 try {
2175 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002176 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 if (task != null) {
2178 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2179 }
2180 } finally {
2181 Binder.restoreCallingIdentity(origId);
2182 }
2183 }
2184 return false;
2185 }
2186
2187 @Override
2188 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002189 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 long ident = Binder.clearCallingIdentity();
2191 Rect rect = new Rect();
2192 try {
2193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002194 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2196 if (task == null) {
2197 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2198 return rect;
2199 }
2200 if (task.getStack() != null) {
2201 // Return the bounds from window manager since it will be adjusted for various
2202 // things like the presense of a docked stack for tasks that aren't resizeable.
2203 task.getWindowContainerBounds(rect);
2204 } else {
2205 // Task isn't in window manager yet since it isn't associated with a stack.
2206 // Return the persist value from activity manager
2207 if (!task.matchParentBounds()) {
2208 rect.set(task.getBounds());
2209 } else if (task.mLastNonFullscreenBounds != null) {
2210 rect.set(task.mLastNonFullscreenBounds);
2211 }
2212 }
2213 }
2214 } finally {
2215 Binder.restoreCallingIdentity(ident);
2216 }
2217 return rect;
2218 }
2219
2220 @Override
2221 public ActivityManager.TaskDescription getTaskDescription(int id) {
2222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002223 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002225 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2227 if (tr != null) {
2228 return tr.lastTaskDescription;
2229 }
2230 }
2231 return null;
2232 }
2233
2234 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002235 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2236 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2237 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2238 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2239 return;
2240 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002241 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002242 synchronized (mGlobalLock) {
2243 final long ident = Binder.clearCallingIdentity();
2244 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002245 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002246 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002247 if (task == null) {
2248 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2249 return;
2250 }
2251
2252 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2253 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2254
2255 if (!task.isActivityTypeStandardOrUndefined()) {
2256 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2257 + " non-standard task " + taskId + " to windowing mode="
2258 + windowingMode);
2259 }
2260
2261 final ActivityStack stack = task.getStack();
2262 if (toTop) {
2263 stack.moveToFront("setTaskWindowingMode", task);
2264 }
2265 stack.setWindowingMode(windowingMode);
2266 } finally {
2267 Binder.restoreCallingIdentity(ident);
2268 }
2269 }
2270 }
2271
2272 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002274 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 ActivityRecord r = getCallingRecordLocked(token);
2276 return r != null ? r.info.packageName : null;
2277 }
2278 }
2279
2280 @Override
2281 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002282 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002283 ActivityRecord r = getCallingRecordLocked(token);
2284 return r != null ? r.intent.getComponent() : null;
2285 }
2286 }
2287
2288 private ActivityRecord getCallingRecordLocked(IBinder token) {
2289 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2290 if (r == null) {
2291 return null;
2292 }
2293 return r.resultTo;
2294 }
2295
2296 @Override
2297 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299
2300 synchronized (mGlobalLock) {
2301 final long origId = Binder.clearCallingIdentity();
2302 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002303 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 } finally {
2305 Binder.restoreCallingIdentity(origId);
2306 }
2307 }
2308 }
2309
Mark Renouf446251d2019-04-26 10:22:41 -04002310 @Override
2311 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2312 synchronized (mGlobalLock) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return;
2316 }
2317 ActivityStack stack = r.getActivityStack();
2318 if (stack != null && stack.isSingleTaskInstance()) {
2319 // Single-task stacks are used for activities which are presented in floating
2320 // windows above full screen activities. Instead of directly finishing the
2321 // task, a task change listener is used to notify SystemUI so the action can be
2322 // handled specially.
2323 final TaskRecord task = r.getTaskRecord();
2324 mTaskChangeNotificationController
2325 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2326 } else {
2327 try {
2328 callback.requestFinish();
2329 } catch (RemoteException e) {
2330 Slog.e(TAG, "Failed to invoke request finish callback", e);
2331 }
2332 }
2333 }
2334 }
2335
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 /**
2337 * TODO: Add mController hook
2338 */
2339 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002340 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2341 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002342 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343
2344 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2345 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002346 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2347 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 }
2349 }
2350
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2352 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002353 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002354
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 final int callingPid = Binder.getCallingPid();
2356 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002357 if (!isSameApp(callingUid, callingPackage)) {
2358 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2359 + Binder.getCallingPid() + " as package " + callingPackage;
2360 Slog.w(TAG, msg);
2361 throw new SecurityException(msg);
2362 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 SafeActivityOptions.abort(options);
2365 return;
2366 }
2367 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 WindowProcessController callerApp = null;
2369 if (appThread != null) {
2370 callerApp = getProcessController(appThread);
2371 }
2372 final ActivityStarter starter = getActivityStartController().obtainStarter(
2373 null /* intent */, "moveTaskToFront");
2374 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2375 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002376 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 return;
2378 }
2379 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002381 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 if (task == null) {
2383 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002384 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 return;
2386 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002387 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002389 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 return;
2391 }
2392 ActivityOptions realOptions = options != null
2393 ? options.getOptions(mStackSupervisor)
2394 : null;
2395 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2396 false /* forceNonResizable */);
2397
2398 final ActivityRecord topActivity = task.getTopActivity();
2399 if (topActivity != null) {
2400
2401 // We are reshowing a task, use a starting window to hide the initial draw delay
2402 // so the transition can start earlier.
2403 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2404 true /* taskSwitch */, fromRecents);
2405 }
2406 } finally {
2407 Binder.restoreCallingIdentity(origId);
2408 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 }
2410
Ricky Waiaca8a772019-04-04 16:01:06 +01002411 /**
2412 * Return true if callingUid is system, or packageName belongs to that callingUid.
2413 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002414 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002415 try {
2416 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2417 if (packageName == null) {
2418 return false;
2419 }
2420 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2421 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2422 UserHandle.getUserId(callingUid));
2423 return UserHandle.isSameApp(callingUid, uid);
2424 }
2425 } catch (RemoteException e) {
2426 // Should not happen
2427 }
2428 return true;
2429 }
2430
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002431 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2432 int callingPid, int callingUid, String name) {
2433 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2434 return true;
2435 }
2436
2437 if (getRecentTasks().isCallerRecents(sourceUid)) {
2438 return true;
2439 }
2440
2441 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2442 if (perm == PackageManager.PERMISSION_GRANTED) {
2443 return true;
2444 }
2445 if (checkAllowAppSwitchUid(sourceUid)) {
2446 return true;
2447 }
2448
2449 // If the actual IPC caller is different from the logical source, then
2450 // also see if they are allowed to control app switches.
2451 if (callingUid != -1 && callingUid != sourceUid) {
2452 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2453 if (perm == PackageManager.PERMISSION_GRANTED) {
2454 return true;
2455 }
2456 if (checkAllowAppSwitchUid(callingUid)) {
2457 return true;
2458 }
2459 }
2460
2461 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2462 return false;
2463 }
2464
2465 private boolean checkAllowAppSwitchUid(int uid) {
2466 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2467 if (types != null) {
2468 for (int i = types.size() - 1; i >= 0; i--) {
2469 if (types.valueAt(i).intValue() == uid) {
2470 return true;
2471 }
2472 }
2473 }
2474 return false;
2475 }
2476
2477 @Override
2478 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2479 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2480 "setActivityController()");
2481 synchronized (mGlobalLock) {
2482 mController = controller;
2483 mControllerIsAMonkey = imAMonkey;
2484 Watchdog.getInstance().setActivityController(controller);
2485 }
2486 }
2487
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002488 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002489 synchronized (mGlobalLock) {
2490 return mController != null && mControllerIsAMonkey;
2491 }
2492 }
2493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 @Override
2495 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2496 synchronized (mGlobalLock) {
2497 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2498 }
2499 }
2500
2501 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2503 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2504 }
2505
2506 @Override
2507 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2508 @WindowConfiguration.ActivityType int ignoreActivityType,
2509 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2510 final int callingUid = Binder.getCallingUid();
2511 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2512
2513 synchronized (mGlobalLock) {
2514 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002516 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002518 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 ignoreWindowingMode, callingUid, allowed);
2520 }
2521
2522 return list;
2523 }
2524
2525 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002526 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2527 synchronized (mGlobalLock) {
2528 final long origId = Binder.clearCallingIdentity();
2529 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2530 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002531 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002532 }
2533 Binder.restoreCallingIdentity(origId);
2534 }
2535 }
2536
2537 @Override
2538 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002539 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 ActivityStack stack = ActivityRecord.getStackLocked(token);
2541 if (stack != null) {
2542 return stack.willActivityBeVisibleLocked(token);
2543 }
2544 return false;
2545 }
2546 }
2547
2548 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002550 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 synchronized (mGlobalLock) {
2552 final long ident = Binder.clearCallingIdentity();
2553 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002554 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 if (task == null) {
2556 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2557 return;
2558 }
2559
2560 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2561 + " to stackId=" + stackId + " toTop=" + toTop);
2562
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 if (stack == null) {
2565 throw new IllegalStateException(
2566 "moveTaskToStack: No stack for stackId=" + stackId);
2567 }
2568 if (!stack.isActivityTypeStandardOrUndefined()) {
2569 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2570 + taskId + " to stack " + stackId);
2571 }
2572 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002573 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002574 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2575 }
2576 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2577 "moveTaskToStack");
2578 } finally {
2579 Binder.restoreCallingIdentity(ident);
2580 }
2581 }
2582 }
2583
2584 @Override
2585 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2586 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002587 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588
2589 final long ident = Binder.clearCallingIdentity();
2590 try {
2591 synchronized (mGlobalLock) {
2592 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002593 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 if (stack == null) {
2595 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2596 return;
2597 }
2598 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2599 throw new IllegalArgumentException("Stack: " + stackId
2600 + " doesn't support animated resize.");
2601 }
2602 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2603 animationDuration, false /* fromFullscreen */);
2604 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002605 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 if (stack == null) {
2607 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2608 return;
2609 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002610 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2612 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2613 }
2614 }
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
wilsonshih5c4cf522019-01-25 09:03:47 +08002620 @Override
2621 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2622 int animationDuration) {
2623 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2624
2625 final long ident = Binder.clearCallingIdentity();
2626 try {
2627 synchronized (mGlobalLock) {
2628 if (xOffset == 0 && yOffset == 0) {
2629 return;
2630 }
2631 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2632 if (stack == null) {
2633 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2634 return;
2635 }
2636 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2637 throw new IllegalArgumentException("Stack: " + stackId
2638 + " doesn't support animated resize.");
2639 }
2640 final Rect destBounds = new Rect();
2641 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002642 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002643 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2644 return;
2645 }
2646 destBounds.offset(xOffset, yOffset);
2647 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2648 animationDuration, false /* fromFullscreen */);
2649 }
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002654 /**
2655 * Moves the specified task to the primary-split-screen stack.
2656 *
2657 * @param taskId Id of task to move.
2658 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2659 * exist already. See
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2661 * and
2662 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2663 * @param toTop If the task and stack should be moved to the top.
2664 * @param animate Whether we should play an animation for the moving the task.
2665 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2666 * stack. Pass {@code null} to use default bounds.
2667 * @param showRecents If the recents activity should be shown on the other side of the task
2668 * going into split-screen mode.
2669 */
2670 @Override
2671 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2672 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 "setTaskWindowingModeSplitScreenPrimary()");
2675 synchronized (mGlobalLock) {
2676 final long ident = Binder.clearCallingIdentity();
2677 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002678 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002679 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 if (task == null) {
2681 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2682 return false;
2683 }
2684 if (DEBUG_STACK) Slog.d(TAG_STACK,
2685 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2686 + " to createMode=" + createMode + " toTop=" + toTop);
2687 if (!task.isActivityTypeStandardOrUndefined()) {
2688 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2689 + " non-standard task " + taskId + " to split-screen windowing mode");
2690 }
2691
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002692 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 final int windowingMode = task.getWindowingMode();
2694 final ActivityStack stack = task.getStack();
2695 if (toTop) {
2696 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2697 }
2698 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002699 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2700 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 return windowingMode != task.getWindowingMode();
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706 }
2707
2708 /**
2709 * Removes stacks in the input windowing modes from the system if they are of activity type
2710 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2711 */
2712 @Override
2713 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 "removeStacksInWindowingModes()");
2716
2717 synchronized (mGlobalLock) {
2718 final long ident = Binder.clearCallingIdentity();
2719 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 } finally {
2722 Binder.restoreCallingIdentity(ident);
2723 }
2724 }
2725 }
2726
2727 @Override
2728 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002729 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 "removeStacksWithActivityTypes()");
2731
2732 synchronized (mGlobalLock) {
2733 final long ident = Binder.clearCallingIdentity();
2734 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002735 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 } finally {
2737 Binder.restoreCallingIdentity(ident);
2738 }
2739 }
2740 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741
2742 @Override
2743 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2744 int userId) {
2745 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2747 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 final boolean detailed = checkGetTasksPermission(
2750 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2751 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 == PackageManager.PERMISSION_GRANTED;
2753
2754 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002755 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 callingUid);
2757 }
2758 }
2759
2760 @Override
2761 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 long ident = Binder.clearCallingIdentity();
2764 try {
2765 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772
2773 @Override
2774 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 long ident = Binder.clearCallingIdentity();
2777 try {
2778 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002779 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 }
2781 } finally {
2782 Binder.restoreCallingIdentity(ident);
2783 }
2784 }
2785
2786 @Override
2787 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 final long callingUid = Binder.getCallingUid();
2790 final long origId = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
2793 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002794 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2796 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(origId);
2800 }
2801 }
2802
2803 @Override
2804 public void startLockTaskModeByToken(IBinder token) {
2805 synchronized (mGlobalLock) {
2806 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2807 if (r == null) {
2808 return;
2809 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002810 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 }
2812 }
2813
2814 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002815 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 // This makes inner call to look as if it was initiated by system.
2818 long ident = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002821 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002822 MATCH_TASK_IN_STACKS_ONLY);
2823 if (task == null) {
2824 return;
2825 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826
2827 // When starting lock task mode the stack must be in front and focused
2828 task.getStack().moveToFront("startSystemLockTaskMode");
2829 startLockTaskModeLocked(task, true /* isSystemCaller */);
2830 }
2831 } finally {
2832 Binder.restoreCallingIdentity(ident);
2833 }
2834 }
2835
2836 @Override
2837 public void stopLockTaskModeByToken(IBinder token) {
2838 synchronized (mGlobalLock) {
2839 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2840 if (r == null) {
2841 return;
2842 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002843 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 }
2845 }
2846
2847 /**
2848 * This API should be called by SystemUI only when user perform certain action to dismiss
2849 * lock task mode. We should only dismiss pinned lock task mode in this case.
2850 */
2851 @Override
2852 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2855 }
2856
2857 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2858 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2859 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2860 return;
2861 }
2862
Wale Ogunwaled32da472018-11-16 07:19:28 -08002863 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 if (stack == null || task != stack.topTask()) {
2865 throw new IllegalArgumentException("Invalid task, not in foreground");
2866 }
2867
2868 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2869 // system or a specific app.
2870 // * System-initiated requests will only start the pinned mode (screen pinning)
2871 // * App-initiated requests
2872 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2873 // - will start the pinned mode, otherwise
2874 final int callingUid = Binder.getCallingUid();
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002878 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002880 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 } finally {
2882 Binder.restoreCallingIdentity(ident);
2883 }
2884 }
2885
2886 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2887 final int callingUid = Binder.getCallingUid();
2888 long ident = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002891 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 }
2893 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2894 // task and jumping straight into a call in the case of emergency call back.
2895 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2896 if (tm != null) {
2897 tm.showInCallScreen(false);
2898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(ident);
2901 }
2902 }
2903
2904 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002905 public void updateLockTaskPackages(int userId, String[] packages) {
2906 final int callingUid = Binder.getCallingUid();
2907 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2908 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2909 "updateLockTaskPackages()");
2910 }
2911 synchronized (this) {
2912 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2913 + Arrays.toString(packages));
2914 getLockTaskController().updateLockTaskPackages(userId, packages);
2915 }
2916 }
2917
2918 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 public boolean isInLockTaskMode() {
2920 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2921 }
2922
2923 @Override
2924 public int getLockTaskModeState() {
2925 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002926 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929
2930 @Override
2931 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2932 synchronized (mGlobalLock) {
2933 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2934 if (r != null) {
2935 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002936 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002938 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941 }
2942
2943 @Override
2944 public Bundle getActivityOptions(IBinder token) {
2945 final long origId = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
2948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2949 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002950 final ActivityOptions activityOptions = r.takeOptionsLocked(
2951 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 return activityOptions == null ? null : activityOptions.toBundle();
2953 }
2954 return null;
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(origId);
2958 }
2959 }
2960
2961 @Override
2962 public List<IBinder> getAppTasks(String callingPackage) {
2963 int callingUid = Binder.getCallingUid();
2964 long ident = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002967 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 }
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
2974 @Override
2975 public void finishVoiceTask(IVoiceInteractionSession session) {
2976 synchronized (mGlobalLock) {
2977 final long origId = Binder.clearCallingIdentity();
2978 try {
2979 // TODO: VI Consider treating local voice interactions and voice tasks
2980 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002981 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 } finally {
2983 Binder.restoreCallingIdentity(origId);
2984 }
2985 }
2986
2987 }
2988
2989 @Override
2990 public boolean isTopOfTask(IBinder token) {
2991 synchronized (mGlobalLock) {
2992 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002993 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 }
2996
2997 @Override
2998 public void notifyLaunchTaskBehindComplete(IBinder token) {
2999 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3000 }
3001
3002 @Override
3003 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003004 mH.post(() -> {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003009 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 } catch (RemoteException e) {
3011 }
3012 }
3013 }
3014
3015 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 }
3017
3018 /** Called from an app when assist data is ready. */
3019 @Override
3020 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3021 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003022 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 synchronized (pae) {
3024 pae.result = extras;
3025 pae.structure = structure;
3026 pae.content = content;
3027 if (referrer != null) {
3028 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3029 }
3030 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003031 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003032 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3033 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 structure.setHomeActivity(pae.isHome);
3035 }
3036 pae.haveResult = true;
3037 pae.notifyAll();
3038 if (pae.intent == null && pae.receiver == null) {
3039 // Caller is just waiting for the result.
3040 return;
3041 }
3042 }
3043 // We are now ready to launch the assist activity.
3044 IAssistDataReceiver sendReceiver = null;
3045 Bundle sendBundle = null;
3046 synchronized (mGlobalLock) {
3047 buildAssistBundleLocked(pae, extras);
3048 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003049 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 if (!exists) {
3051 // Timed out.
3052 return;
3053 }
3054
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 // Caller wants result sent back to them.
3057 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003058 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3059 pae.activity.getTaskRecord().taskId);
3060 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3061 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3063 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3064 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3065 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3066 }
3067 }
3068 if (sendReceiver != null) {
3069 try {
3070 sendReceiver.onHandleAssistData(sendBundle);
3071 } catch (RemoteException e) {
3072 }
3073 return;
3074 }
3075
3076 final long ident = Binder.clearCallingIdentity();
3077 try {
3078 if (TextUtils.equals(pae.intent.getAction(),
3079 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003080 // Start voice interaction through VoiceInteractionManagerService.
3081 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3082 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 } else {
3084 pae.intent.replaceExtras(pae.extras);
3085 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3086 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3087 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003088 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089
3090 try {
3091 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3092 } catch (ActivityNotFoundException e) {
3093 Slog.w(TAG, "No activity to handle assist action.", e);
3094 }
3095 }
3096 } finally {
3097 Binder.restoreCallingIdentity(ident);
3098 }
3099 }
3100
3101 @Override
3102 public int addAppTask(IBinder activityToken, Intent intent,
3103 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3104 final int callingUid = Binder.getCallingUid();
3105 final long callingIdent = Binder.clearCallingIdentity();
3106
3107 try {
3108 synchronized (mGlobalLock) {
3109 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3110 if (r == null) {
3111 throw new IllegalArgumentException("Activity does not exist; token="
3112 + activityToken);
3113 }
3114 ComponentName comp = intent.getComponent();
3115 if (comp == null) {
3116 throw new IllegalArgumentException("Intent " + intent
3117 + " must specify explicit component");
3118 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003119 if (thumbnail.getWidth() != mThumbnailWidth
3120 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 throw new IllegalArgumentException("Bad thumbnail size: got "
3122 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 }
3125 if (intent.getSelector() != null) {
3126 intent.setSelector(null);
3127 }
3128 if (intent.getSourceBounds() != null) {
3129 intent.setSourceBounds(null);
3130 }
3131 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3132 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3133 // The caller has added this as an auto-remove task... that makes no
3134 // sense, so turn off auto-remove.
3135 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3136 }
3137 }
3138 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3139 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3140 if (ainfo.applicationInfo.uid != callingUid) {
3141 throw new SecurityException(
3142 "Can't add task for another application: target uid="
3143 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3144 }
3145
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003146 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003148 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003150 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 // The app has too many tasks already and we can't add any more
3152 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3153 return INVALID_TASK_ID;
3154 }
3155 task.lastTaskDescription.copyFrom(description);
3156
3157 // TODO: Send the thumbnail to WM to store it.
3158
3159 return task.taskId;
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(callingIdent);
3163 }
3164 }
3165
3166 @Override
3167 public Point getAppTaskThumbnailSize() {
3168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003169 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 }
3171 }
3172
3173 @Override
3174 public void setTaskResizeable(int taskId, int resizeableMode) {
3175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003176 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3178 if (task == null) {
3179 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3180 return;
3181 }
3182 task.setResizeMode(resizeableMode);
3183 }
3184 }
3185
3186 @Override
3187 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 long ident = Binder.clearCallingIdentity();
3190 try {
3191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003192 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003193 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 if (task == null) {
3195 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3196 return;
3197 }
3198 // Place the task in the right stack if it isn't there already based on
3199 // the requested bounds.
3200 // The stack transition logic is:
3201 // - a null bounds on a freeform task moves that task to fullscreen
3202 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3203 // that task to freeform
3204 // - otherwise the task is not moved
3205 ActivityStack stack = task.getStack();
3206 if (!task.getWindowConfiguration().canResizeTask()) {
3207 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3208 }
3209 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3210 stack = stack.getDisplay().getOrCreateStack(
3211 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3212 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3213 stack = stack.getDisplay().getOrCreateStack(
3214 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3215 }
3216
3217 // Reparent the task to the right stack if necessary
3218 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3219 if (stack != task.getStack()) {
3220 // Defer resume until the task is resized below
3221 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3222 DEFER_RESUME, "resizeTask");
3223 preserveWindow = false;
3224 }
3225
3226 // After reparenting (which only resizes the task to the stack bounds), resize the
3227 // task to the actual bounds provided
3228 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3229 }
3230 } finally {
3231 Binder.restoreCallingIdentity(ident);
3232 }
3233 }
3234
3235 @Override
3236 public boolean releaseActivityInstance(IBinder token) {
3237 synchronized (mGlobalLock) {
3238 final long origId = Binder.clearCallingIdentity();
3239 try {
3240 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3241 if (r == null) {
3242 return false;
3243 }
Andrii Kulian79d67982019-08-19 11:56:16 -07003244 return r.safelyDestroy("app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 } finally {
3246 Binder.restoreCallingIdentity(origId);
3247 }
3248 }
3249 }
3250
3251 @Override
3252 public void releaseSomeActivities(IApplicationThread appInt) {
3253 synchronized (mGlobalLock) {
3254 final long origId = Binder.clearCallingIdentity();
3255 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003256 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003257 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 } finally {
3259 Binder.restoreCallingIdentity(origId);
3260 }
3261 }
3262 }
3263
3264 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003265 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003266 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 != PackageManager.PERMISSION_GRANTED) {
3268 throw new SecurityException("Requires permission "
3269 + android.Manifest.permission.DEVICE_POWER);
3270 }
3271
3272 synchronized (mGlobalLock) {
3273 long ident = Binder.clearCallingIdentity();
3274 if (mKeyguardShown != keyguardShowing) {
3275 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003276 final Message msg = PooledLambda.obtainMessage(
3277 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3278 keyguardShowing);
3279 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 }
3281 try {
wilsonshih177261f2019-02-22 12:02:18 +08003282 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 } finally {
3284 Binder.restoreCallingIdentity(ident);
3285 }
3286 }
3287
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003288 mH.post(() -> {
3289 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3290 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3291 }
3292 });
3293 }
3294
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003295 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003296 mH.post(() -> {
3297 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3298 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3299 }
3300 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 }
3302
3303 @Override
3304 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003305 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3306 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003307
3308 final File passedIconFile = new File(filePath);
3309 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3310 passedIconFile.getName());
3311 if (!legitIconFile.getPath().equals(filePath)
3312 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3313 throw new IllegalArgumentException("Bad file path: " + filePath
3314 + " passed for userId " + userId);
3315 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003316 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 }
3318
3319 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003320 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3322 final ActivityOptions activityOptions = safeOptions != null
3323 ? safeOptions.getOptions(mStackSupervisor)
3324 : null;
3325 if (activityOptions == null
3326 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3327 || activityOptions.getCustomInPlaceResId() == 0) {
3328 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3329 "with valid animation");
3330 }
lumark588a3e82018-07-20 18:53:54 +08003331 // Get top display of front most application.
3332 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3333 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003334 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3335 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3336 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003337 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003338 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003339 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 }
3341
3342 @Override
3343 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 synchronized (mGlobalLock) {
3346 final long ident = Binder.clearCallingIdentity();
3347 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003348 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 if (stack == null) {
3350 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3351 return;
3352 }
3353 if (!stack.isActivityTypeStandardOrUndefined()) {
3354 throw new IllegalArgumentException(
3355 "Removing non-standard stack is not allowed.");
3356 }
3357 mStackSupervisor.removeStack(stack);
3358 } finally {
3359 Binder.restoreCallingIdentity(ident);
3360 }
3361 }
3362 }
3363
3364 @Override
3365 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367
3368 synchronized (mGlobalLock) {
3369 final long ident = Binder.clearCallingIdentity();
3370 try {
3371 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3372 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003373 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 } finally {
3375 Binder.restoreCallingIdentity(ident);
3376 }
3377 }
3378 }
3379
3380 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003381 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 synchronized (mGlobalLock) {
3383 long ident = Binder.clearCallingIdentity();
3384 try {
3385 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3386 if (r == null) {
3387 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003388 "toggleFreeformWindowingMode: No activity record matching token="
3389 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 }
3391
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003392 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003393 if (stack == null) {
3394 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3395 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397
Yunfan Chend967af82019-01-17 18:30:18 +09003398 if (!stack.inFreeformWindowingMode()
3399 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3400 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3401 + "toggle between fullscreen and freeform.");
3402 }
3403
3404 if (stack.inFreeformWindowingMode()) {
3405 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003406 } else if (stack.getParent().inFreeformWindowingMode()) {
3407 // If the window is on a freeform display, set it to undefined. It will be
3408 // resolved to freeform and it can adjust windowing mode when the display mode
3409 // changes in runtime.
3410 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003411 } else {
3412 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3413 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
3417 }
3418 }
3419
3420 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3421 @Override
3422 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003423 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003425 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427
3428 /** Unregister a task stack listener so that it stops receiving callbacks. */
3429 @Override
3430 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003431 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003433 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 }
3435
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 @Override
3437 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3438 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3439 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3440 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3441 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3442 }
3443
3444 @Override
3445 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3446 IBinder activityToken, int flags) {
3447 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3448 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3449 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3450 }
3451
3452 @Override
3453 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3454 Bundle args) {
3455 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3456 true /* focused */, true /* newSessionId */, userHandle, args,
3457 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3458 }
3459
3460 @Override
3461 public Bundle getAssistContextExtras(int requestType) {
3462 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3463 null, null, true /* focused */, true /* newSessionId */,
3464 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3465 if (pae == null) {
3466 return null;
3467 }
3468 synchronized (pae) {
3469 while (!pae.haveResult) {
3470 try {
3471 pae.wait();
3472 } catch (InterruptedException e) {
3473 }
3474 }
3475 }
3476 synchronized (mGlobalLock) {
3477 buildAssistBundleLocked(pae, pae.result);
3478 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003479 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003480 }
3481 return pae.extras;
3482 }
3483
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003484 /**
3485 * Binder IPC calls go through the public entry point.
3486 * This can be called with or without the global lock held.
3487 */
3488 private static int checkCallingPermission(String permission) {
3489 return checkPermission(
3490 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3491 }
3492
3493 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003494 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3496 mAmInternal.enforceCallingPermission(permission, func);
3497 }
3498 }
3499
3500 @VisibleForTesting
3501 int checkGetTasksPermission(String permission, int pid, int uid) {
3502 return checkPermission(permission, pid, uid);
3503 }
3504
3505 static int checkPermission(String permission, int pid, int uid) {
3506 if (permission == null) {
3507 return PackageManager.PERMISSION_DENIED;
3508 }
3509 return checkComponentPermission(permission, pid, uid, -1, true);
3510 }
3511
Wale Ogunwale214f3482018-10-04 11:00:47 -07003512 public static int checkComponentPermission(String permission, int pid, int uid,
3513 int owningUid, boolean exported) {
3514 return ActivityManagerService.checkComponentPermission(
3515 permission, pid, uid, owningUid, exported);
3516 }
3517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003518 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3519 if (getRecentTasks().isCallerRecents(callingUid)) {
3520 // Always allow the recents component to get tasks
3521 return true;
3522 }
3523
3524 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3525 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3526 if (!allowed) {
3527 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3528 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3529 // Temporary compatibility: some existing apps on the system image may
3530 // still be requesting the old permission and not switched to the new
3531 // one; if so, we'll still allow them full access. This means we need
3532 // to see if they are holding the old permission and are a system app.
3533 try {
3534 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3535 allowed = true;
3536 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3537 + " is using old GET_TASKS but privileged; allowing");
3538 }
3539 } catch (RemoteException e) {
3540 }
3541 }
3542 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3543 + " does not hold REAL_GET_TASKS; limiting output");
3544 }
3545 return allowed;
3546 }
3547
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3549 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3550 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3551 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003552 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003553 "enqueueAssistContext()");
3554
3555 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003556 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 if (activity == null) {
3558 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3559 return null;
3560 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003561 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3563 return null;
3564 }
3565 if (focused) {
3566 if (activityToken != null) {
3567 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3568 if (activity != caller) {
3569 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3570 + " is not current top " + activity);
3571 return null;
3572 }
3573 }
3574 } else {
3575 activity = ActivityRecord.forTokenLocked(activityToken);
3576 if (activity == null) {
3577 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3578 + " couldn't be found");
3579 return null;
3580 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003581 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003582 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3583 return null;
3584 }
3585 }
3586
3587 PendingAssistExtras pae;
3588 Bundle extras = new Bundle();
3589 if (args != null) {
3590 extras.putAll(args);
3591 }
3592 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003593 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594
3595 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3596 userHandle);
3597 pae.isHome = activity.isActivityTypeHome();
3598
3599 // Increment the sessionId if necessary
3600 if (newSessionId) {
3601 mViSessionId++;
3602 }
3603 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003604 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3605 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003607 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 } catch (RemoteException e) {
3609 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3610 return null;
3611 }
3612 return pae;
3613 }
3614 }
3615
3616 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3617 if (result != null) {
3618 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3619 }
3620 if (pae.hint != null) {
3621 pae.extras.putBoolean(pae.hint, true);
3622 }
3623 }
3624
3625 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3626 IAssistDataReceiver receiver;
3627 synchronized (mGlobalLock) {
3628 mPendingAssistExtras.remove(pae);
3629 receiver = pae.receiver;
3630 }
3631 if (receiver != null) {
3632 // Caller wants result sent back to them.
3633 Bundle sendBundle = new Bundle();
3634 // At least return the receiver extras
3635 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3636 try {
3637 pae.receiver.onHandleAssistData(sendBundle);
3638 } catch (RemoteException e) {
3639 }
3640 }
3641 }
3642
3643 public class PendingAssistExtras extends Binder implements Runnable {
3644 public final ActivityRecord activity;
3645 public boolean isHome;
3646 public final Bundle extras;
3647 public final Intent intent;
3648 public final String hint;
3649 public final IAssistDataReceiver receiver;
3650 public final int userHandle;
3651 public boolean haveResult = false;
3652 public Bundle result = null;
3653 public AssistStructure structure = null;
3654 public AssistContent content = null;
3655 public Bundle receiverExtras;
3656
3657 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3658 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3659 int _userHandle) {
3660 activity = _activity;
3661 extras = _extras;
3662 intent = _intent;
3663 hint = _hint;
3664 receiver = _receiver;
3665 receiverExtras = _receiverExtras;
3666 userHandle = _userHandle;
3667 }
3668
3669 @Override
3670 public void run() {
3671 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3672 synchronized (this) {
3673 haveResult = true;
3674 notifyAll();
3675 }
3676 pendingAssistExtrasTimedOut(this);
3677 }
3678 }
3679
3680 @Override
3681 public boolean isAssistDataAllowedOnCurrentActivity() {
3682 int userId;
3683 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003684 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3686 return false;
3687 }
3688
3689 final ActivityRecord activity = focusedStack.getTopActivity();
3690 if (activity == null) {
3691 return false;
3692 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003693 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 }
3695 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3696 }
3697
3698 @Override
3699 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3700 long ident = Binder.clearCallingIdentity();
3701 try {
3702 synchronized (mGlobalLock) {
3703 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003704 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 if (top != caller) {
3706 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3707 + " is not current top " + top);
3708 return false;
3709 }
3710 if (!top.nowVisible) {
3711 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3712 + " is not visible");
3713 return false;
3714 }
3715 }
3716 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3717 token);
3718 } finally {
3719 Binder.restoreCallingIdentity(ident);
3720 }
3721 }
3722
3723 @Override
3724 public boolean isRootVoiceInteraction(IBinder token) {
3725 synchronized (mGlobalLock) {
3726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3727 if (r == null) {
3728 return false;
3729 }
3730 return r.rootVoiceInteraction;
3731 }
3732 }
3733
Wale Ogunwalef6733932018-06-27 05:14:34 -07003734 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3735 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3736 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3737 if (activityToCallback == null) return;
3738 activityToCallback.setVoiceSessionLocked(voiceSession);
3739
3740 // Inform the activity
3741 try {
3742 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3743 voiceInteractor);
3744 long token = Binder.clearCallingIdentity();
3745 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003746 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003747 } finally {
3748 Binder.restoreCallingIdentity(token);
3749 }
3750 // TODO: VI Should we cache the activity so that it's easier to find later
3751 // rather than scan through all the stacks and activities?
3752 } catch (RemoteException re) {
3753 activityToCallback.clearVoiceSessionLocked();
3754 // TODO: VI Should this terminate the voice session?
3755 }
3756 }
3757
3758 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3759 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3760 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3761 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3762 boolean wasRunningVoice = mRunningVoice != null;
3763 mRunningVoice = session;
3764 if (!wasRunningVoice) {
3765 mVoiceWakeLock.acquire();
3766 updateSleepIfNeededLocked();
3767 }
3768 }
3769 }
3770
3771 void finishRunningVoiceLocked() {
3772 if (mRunningVoice != null) {
3773 mRunningVoice = null;
3774 mVoiceWakeLock.release();
3775 updateSleepIfNeededLocked();
3776 }
3777 }
3778
3779 @Override
3780 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3781 synchronized (mGlobalLock) {
3782 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3783 if (keepAwake) {
3784 mVoiceWakeLock.acquire();
3785 } else {
3786 mVoiceWakeLock.release();
3787 }
3788 }
3789 }
3790 }
3791
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 @Override
3793 public ComponentName getActivityClassForToken(IBinder token) {
3794 synchronized (mGlobalLock) {
3795 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3796 if (r == null) {
3797 return null;
3798 }
3799 return r.intent.getComponent();
3800 }
3801 }
3802
3803 @Override
3804 public String getPackageForToken(IBinder token) {
3805 synchronized (mGlobalLock) {
3806 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3807 if (r == null) {
3808 return null;
3809 }
3810 return r.packageName;
3811 }
3812 }
3813
3814 @Override
3815 public void showLockTaskEscapeMessage(IBinder token) {
3816 synchronized (mGlobalLock) {
3817 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3818 if (r == null) {
3819 return;
3820 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003821 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 }
3823 }
3824
3825 @Override
3826 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003827 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 final long token = Binder.clearCallingIdentity();
3829 try {
3830 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003831 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 }
3833 } finally {
3834 Binder.restoreCallingIdentity(token);
3835 }
3836 }
3837
3838 /**
3839 * Try to place task to provided position. The final position might be different depending on
3840 * current user and stacks state. The task will be moved to target stack if it's currently in
3841 * different stack.
3842 */
3843 @Override
3844 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003845 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 synchronized (mGlobalLock) {
3847 long ident = Binder.clearCallingIdentity();
3848 try {
3849 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3850 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003851 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 if (task == null) {
3853 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3854 + taskId);
3855 }
3856
Wale Ogunwaled32da472018-11-16 07:19:28 -08003857 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858
3859 if (stack == null) {
3860 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3861 + stackId);
3862 }
3863 if (!stack.isActivityTypeStandardOrUndefined()) {
3864 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3865 + " the position of task " + taskId + " in/to non-standard stack");
3866 }
3867
3868 // TODO: Have the callers of this API call a separate reparent method if that is
3869 // what they intended to do vs. having this method also do reparenting.
3870 if (task.getStack() == stack) {
3871 // Change position in current stack.
3872 stack.positionChildAt(task, position);
3873 } else {
3874 // Reparent to new stack.
3875 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3876 !DEFER_RESUME, "positionTaskInStack");
3877 }
3878 } finally {
3879 Binder.restoreCallingIdentity(ident);
3880 }
3881 }
3882 }
3883
3884 @Override
3885 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3886 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3887 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003888 + Arrays.toString(horizontalSizeConfiguration) + " "
3889 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 synchronized (mGlobalLock) {
3891 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3892 if (record == null) {
3893 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3894 + "found for: " + token);
3895 }
3896 record.setSizeConfigurations(horizontalSizeConfiguration,
3897 verticalSizeConfigurations, smallestSizeConfigurations);
3898 }
3899 }
3900
3901 /**
3902 * Dismisses split-screen multi-window mode.
3903 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3904 */
3905 @Override
3906 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003907 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3909 final long ident = Binder.clearCallingIdentity();
3910 try {
3911 synchronized (mGlobalLock) {
3912 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003913 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003914 if (stack == null) {
3915 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3916 return;
3917 }
3918
3919 if (toTop) {
3920 // Caller wants the current split-screen primary stack to be the top stack after
3921 // it goes fullscreen, so move it to the front.
3922 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003923 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003925 // stack after it goes fullscreen, so we move the focus to the top-most
3926 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3928 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3929 if (otherStack != null) {
3930 otherStack.moveToFront("dismissSplitScreenMode_other");
3931 }
3932 }
3933
Evan Rosky10475742018-09-05 19:02:48 -07003934 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 }
3936 } finally {
3937 Binder.restoreCallingIdentity(ident);
3938 }
3939 }
3940
3941 /**
3942 * Dismisses Pip
3943 * @param animate True if the dismissal should be animated.
3944 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3945 * default animation duration should be used.
3946 */
3947 @Override
3948 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003949 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 final long ident = Binder.clearCallingIdentity();
3951 try {
3952 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003953 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003954 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 if (stack == null) {
3956 Slog.w(TAG, "dismissPip: pinned stack not found.");
3957 return;
3958 }
3959 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3960 throw new IllegalArgumentException("Stack: " + stack
3961 + " doesn't support animated resize.");
3962 }
3963 if (animate) {
3964 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3965 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3966 } else {
3967 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3968 }
3969 }
3970 } finally {
3971 Binder.restoreCallingIdentity(ident);
3972 }
3973 }
3974
3975 @Override
3976 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003977 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 synchronized (mGlobalLock) {
3979 mSuppressResizeConfigChanges = suppress;
3980 }
3981 }
3982
3983 /**
3984 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3985 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3986 * activity and clearing the task at the same time.
3987 */
3988 @Override
3989 // TODO: API should just be about changing windowing modes...
3990 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003991 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 "moveTasksToFullscreenStack()");
3993 synchronized (mGlobalLock) {
3994 final long origId = Binder.clearCallingIdentity();
3995 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003996 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 if (stack != null){
3998 if (!stack.isActivityTypeStandardOrUndefined()) {
3999 throw new IllegalArgumentException(
4000 "You can't move tasks from non-standard stacks.");
4001 }
4002 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4003 }
4004 } finally {
4005 Binder.restoreCallingIdentity(origId);
4006 }
4007 }
4008 }
4009
4010 /**
4011 * Moves the top activity in the input stackId to the pinned stack.
4012 *
4013 * @param stackId Id of stack to move the top activity to pinned stack.
4014 * @param bounds Bounds to use for pinned stack.
4015 *
4016 * @return True if the top activity of the input stack was successfully moved to the pinned
4017 * stack.
4018 */
4019 @Override
4020 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004021 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 "moveTopActivityToPinnedStack()");
4023 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4026 + "Device doesn't support picture-in-picture mode");
4027 }
4028
4029 long ident = Binder.clearCallingIdentity();
4030 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004031 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 } finally {
4033 Binder.restoreCallingIdentity(ident);
4034 }
4035 }
4036 }
4037
4038 @Override
4039 public boolean isInMultiWindowMode(IBinder token) {
4040 final long origId = Binder.clearCallingIdentity();
4041 try {
4042 synchronized (mGlobalLock) {
4043 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4044 if (r == null) {
4045 return false;
4046 }
4047 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4048 return r.inMultiWindowMode();
4049 }
4050 } finally {
4051 Binder.restoreCallingIdentity(origId);
4052 }
4053 }
4054
4055 @Override
4056 public boolean isInPictureInPictureMode(IBinder token) {
4057 final long origId = Binder.clearCallingIdentity();
4058 try {
4059 synchronized (mGlobalLock) {
4060 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4061 }
4062 } finally {
4063 Binder.restoreCallingIdentity(origId);
4064 }
4065 }
4066
4067 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004068 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4069 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 return false;
4071 }
4072
4073 // If we are animating to fullscreen then we have already dispatched the PIP mode
4074 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004075 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4076 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004077 }
4078
4079 @Override
4080 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4081 final long origId = Binder.clearCallingIdentity();
4082 try {
4083 synchronized (mGlobalLock) {
4084 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4085 "enterPictureInPictureMode", token, params);
4086
4087 // If the activity is already in picture in picture mode, then just return early
4088 if (isInPictureInPictureMode(r)) {
4089 return true;
4090 }
4091
4092 // Activity supports picture-in-picture, now check that we can enter PiP at this
4093 // point, if it is
4094 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4095 false /* beforeStopping */)) {
4096 return false;
4097 }
4098
4099 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004100 synchronized (mGlobalLock) {
4101 // Only update the saved args from the args that are set
4102 r.pictureInPictureArgs.copyOnlySet(params);
4103 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4104 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4105 // Adjust the source bounds by the insets for the transition down
4106 final Rect sourceBounds = new Rect(
4107 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004108 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004109 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004110 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004111 stack.setPictureInPictureAspectRatio(aspectRatio);
4112 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004113 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4114 r.info.applicationInfo.uid, r.shortComponentName,
4115 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004116 logPictureInPictureArgs(params);
4117 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 };
4119
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004120 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 // If the keyguard is showing or occluded, then try and dismiss it before
4122 // entering picture-in-picture (this will prompt the user to authenticate if the
4123 // device is currently locked).
4124 dismissKeyguard(token, new KeyguardDismissCallback() {
4125 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004126 public void onDismissSucceeded() {
4127 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 }
4129 }, null /* message */);
4130 } else {
4131 // Enter picture in picture immediately otherwise
4132 enterPipRunnable.run();
4133 }
4134 return true;
4135 }
4136 } finally {
4137 Binder.restoreCallingIdentity(origId);
4138 }
4139 }
4140
4141 @Override
4142 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4143 final long origId = Binder.clearCallingIdentity();
4144 try {
4145 synchronized (mGlobalLock) {
4146 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4147 "setPictureInPictureParams", token, params);
4148
4149 // Only update the saved args from the args that are set
4150 r.pictureInPictureArgs.copyOnlySet(params);
4151 if (r.inPinnedWindowingMode()) {
4152 // If the activity is already in picture-in-picture, update the pinned stack now
4153 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4154 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004155 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 if (!stack.isAnimatingBoundsToFullscreen()) {
4157 stack.setPictureInPictureAspectRatio(
4158 r.pictureInPictureArgs.getAspectRatio());
4159 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4160 }
4161 }
4162 logPictureInPictureArgs(params);
4163 }
4164 } finally {
4165 Binder.restoreCallingIdentity(origId);
4166 }
4167 }
4168
4169 @Override
4170 public int getMaxNumPictureInPictureActions(IBinder token) {
4171 // Currently, this is a static constant, but later, we may change this to be dependent on
4172 // the context of the activity
4173 return 3;
4174 }
4175
4176 private void logPictureInPictureArgs(PictureInPictureParams params) {
4177 if (params.hasSetActions()) {
4178 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4179 params.getActions().size());
4180 }
4181 if (params.hasSetAspectRatio()) {
4182 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4183 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4184 MetricsLogger.action(lm);
4185 }
4186 }
4187
4188 /**
4189 * Checks the state of the system and the activity associated with the given {@param token} to
4190 * verify that picture-in-picture is supported for that activity.
4191 *
4192 * @return the activity record for the given {@param token} if all the checks pass.
4193 */
4194 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4195 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004196 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 throw new IllegalStateException(caller
4198 + ": Device doesn't support picture-in-picture mode.");
4199 }
4200
4201 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4202 if (r == null) {
4203 throw new IllegalStateException(caller
4204 + ": Can't find activity for token=" + token);
4205 }
4206
4207 if (!r.supportsPictureInPicture()) {
4208 throw new IllegalStateException(caller
4209 + ": Current activity does not support picture-in-picture.");
4210 }
4211
4212 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004213 && !mWindowManager.isValidPictureInPictureAspectRatio(
4214 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 final float minAspectRatio = mContext.getResources().getFloat(
4216 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4217 final float maxAspectRatio = mContext.getResources().getFloat(
4218 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4219 throw new IllegalArgumentException(String.format(caller
4220 + ": Aspect ratio is too extreme (must be between %f and %f).",
4221 minAspectRatio, maxAspectRatio));
4222 }
4223
4224 // Truncate the number of actions if necessary
4225 params.truncateActions(getMaxNumPictureInPictureActions(token));
4226
4227 return r;
4228 }
4229
4230 @Override
4231 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004232 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 synchronized (mGlobalLock) {
4234 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4235 if (r == null) {
4236 throw new IllegalArgumentException("Activity does not exist; token="
4237 + activityToken);
4238 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004239 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 }
4241 }
4242
4243 @Override
4244 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4245 Rect tempDockedTaskInsetBounds,
4246 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 long ident = Binder.clearCallingIdentity();
4249 try {
4250 synchronized (mGlobalLock) {
4251 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4252 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4253 PRESERVE_WINDOWS);
4254 }
4255 } finally {
4256 Binder.restoreCallingIdentity(ident);
4257 }
4258 }
4259
4260 @Override
4261 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 final long ident = Binder.clearCallingIdentity();
4264 try {
4265 synchronized (mGlobalLock) {
4266 mStackSupervisor.setSplitScreenResizing(resizing);
4267 }
4268 } finally {
4269 Binder.restoreCallingIdentity(ident);
4270 }
4271 }
4272
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 /**
4274 * Check that we have the features required for VR-related API calls, and throw an exception if
4275 * not.
4276 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004277 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 if (!mContext.getPackageManager().hasSystemFeature(
4279 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4280 throw new UnsupportedOperationException("VR mode not supported on this device!");
4281 }
4282 }
4283
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004284 @Override
4285 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287
4288 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4289
4290 ActivityRecord r;
4291 synchronized (mGlobalLock) {
4292 r = ActivityRecord.isInStackLocked(token);
4293 }
4294
4295 if (r == null) {
4296 throw new IllegalArgumentException();
4297 }
4298
4299 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004300 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301 VrManagerInternal.NO_ERROR) {
4302 return err;
4303 }
4304
4305 // Clear the binder calling uid since this path may call moveToTask().
4306 final long callingId = Binder.clearCallingIdentity();
4307 try {
4308 synchronized (mGlobalLock) {
4309 r.requestedVrComponent = (enabled) ? packageName : null;
4310
4311 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004312 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004313 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 }
4315 return 0;
4316 }
4317 } finally {
4318 Binder.restoreCallingIdentity(callingId);
4319 }
4320 }
4321
4322 @Override
4323 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4324 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4325 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004326 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4328 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4329 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004330 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004331 || activity.voiceSession != null) {
4332 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4333 return;
4334 }
4335 if (activity.pendingVoiceInteractionStart) {
4336 Slog.w(TAG, "Pending start of voice interaction already.");
4337 return;
4338 }
4339 activity.pendingVoiceInteractionStart = true;
4340 }
4341 LocalServices.getService(VoiceInteractionManagerInternal.class)
4342 .startLocalVoiceInteraction(callingActivity, options);
4343 }
4344
4345 @Override
4346 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4347 LocalServices.getService(VoiceInteractionManagerInternal.class)
4348 .stopLocalVoiceInteraction(callingActivity);
4349 }
4350
4351 @Override
4352 public boolean supportsLocalVoiceInteraction() {
4353 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4354 .supportsLocalVoiceInteraction();
4355 }
4356
4357 /** Notifies all listeners when the pinned stack animation starts. */
4358 @Override
4359 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004360 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 }
4362
4363 /** Notifies all listeners when the pinned stack animation ends. */
4364 @Override
4365 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004366 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368
4369 @Override
4370 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004371 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 final long ident = Binder.clearCallingIdentity();
4373 try {
4374 synchronized (mGlobalLock) {
4375 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4376 }
4377 } finally {
4378 Binder.restoreCallingIdentity(ident);
4379 }
4380 }
4381
4382 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004384 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385
4386 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 }
4391
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004392 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004393 final Message msg = PooledLambda.obtainMessage(
4394 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4395 DEFAULT_DISPLAY);
4396 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 }
4398
4399 final long origId = Binder.clearCallingIdentity();
4400 try {
4401 if (values != null) {
4402 Settings.System.clearConfiguration(values);
4403 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004404 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004405 UserHandle.USER_NULL, false /* deferResume */,
4406 mTmpUpdateConfigurationResult);
4407 return mTmpUpdateConfigurationResult.changes != 0;
4408 } finally {
4409 Binder.restoreCallingIdentity(origId);
4410 }
4411 }
4412 }
4413
4414 @Override
4415 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4416 CharSequence message) {
4417 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004418 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4420 }
4421 final long callingId = Binder.clearCallingIdentity();
4422 try {
4423 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004424 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 }
4426 } finally {
4427 Binder.restoreCallingIdentity(callingId);
4428 }
4429 }
4430
4431 @Override
4432 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004433 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 "cancelTaskWindowTransition()");
4435 final long ident = Binder.clearCallingIdentity();
4436 try {
4437 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004438 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 MATCH_TASK_IN_STACKS_ONLY);
4440 if (task == null) {
4441 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4442 return;
4443 }
4444 task.cancelWindowTransition();
4445 }
4446 } finally {
4447 Binder.restoreCallingIdentity(ident);
4448 }
4449 }
4450
4451 @Override
4452 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 final long ident = Binder.clearCallingIdentity();
4455 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004456 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 } finally {
4458 Binder.restoreCallingIdentity(ident);
4459 }
4460 }
4461
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004462 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4463 boolean restoreFromDisk) {
4464 final TaskRecord task;
4465 synchronized (mGlobalLock) {
4466 task = mRootActivityContainer.anyTaskForId(taskId,
4467 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4468 if (task == null) {
4469 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4470 return null;
4471 }
4472 }
4473 // Don't call this while holding the lock as this operation might hit the disk.
4474 return task.getSnapshot(reducedResolution, restoreFromDisk);
4475 }
4476
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 @Override
4478 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4479 synchronized (mGlobalLock) {
4480 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4481 if (r == null) {
4482 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4483 + token);
4484 return;
4485 }
4486 final long origId = Binder.clearCallingIdentity();
4487 try {
4488 r.setDisablePreviewScreenshots(disable);
4489 } finally {
4490 Binder.restoreCallingIdentity(origId);
4491 }
4492 }
4493 }
4494
4495 /** Return the user id of the last resumed activity. */
4496 @Override
4497 public @UserIdInt
4498 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4501 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004502 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004505 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
4507 }
4508
4509 @Override
4510 public void updateLockTaskFeatures(int userId, int flags) {
4511 final int callingUid = Binder.getCallingUid();
4512 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004513 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 "updateLockTaskFeatures()");
4515 }
4516 synchronized (mGlobalLock) {
4517 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4518 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004519 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 }
4521 }
4522
4523 @Override
4524 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4525 synchronized (mGlobalLock) {
4526 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4527 if (r == null) {
4528 return;
4529 }
4530 final long origId = Binder.clearCallingIdentity();
4531 try {
4532 r.setShowWhenLocked(showWhenLocked);
4533 } finally {
4534 Binder.restoreCallingIdentity(origId);
4535 }
4536 }
4537 }
4538
4539 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004540 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4541 synchronized (mGlobalLock) {
4542 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4543 if (r == null) {
4544 return;
4545 }
4546 final long origId = Binder.clearCallingIdentity();
4547 try {
4548 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4549 } finally {
4550 Binder.restoreCallingIdentity(origId);
4551 }
4552 }
4553 }
4554
4555 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4557 synchronized (mGlobalLock) {
4558 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4559 if (r == null) {
4560 return;
4561 }
4562 final long origId = Binder.clearCallingIdentity();
4563 try {
4564 r.setTurnScreenOn(turnScreenOn);
4565 } finally {
4566 Binder.restoreCallingIdentity(origId);
4567 }
4568 }
4569 }
4570
4571 @Override
4572 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004573 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004575 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 synchronized (mGlobalLock) {
4577 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4578 if (r == null) {
4579 return;
4580 }
4581 final long origId = Binder.clearCallingIdentity();
4582 try {
4583 r.registerRemoteAnimations(definition);
4584 } finally {
4585 Binder.restoreCallingIdentity(origId);
4586 }
4587 }
4588 }
4589
4590 @Override
4591 public void registerRemoteAnimationForNextActivityStart(String packageName,
4592 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004593 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004595 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 synchronized (mGlobalLock) {
4597 final long origId = Binder.clearCallingIdentity();
4598 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004599 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 packageName, adapter);
4601 } finally {
4602 Binder.restoreCallingIdentity(origId);
4603 }
4604 }
4605 }
4606
Evan Rosky966759f2019-01-15 10:33:58 -08004607 @Override
4608 public void registerRemoteAnimationsForDisplay(int displayId,
4609 RemoteAnimationDefinition definition) {
4610 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4611 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004612 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004613 synchronized (mGlobalLock) {
4614 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4615 if (display == null) {
4616 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4617 return;
4618 }
4619 final long origId = Binder.clearCallingIdentity();
4620 try {
4621 display.mDisplayContent.registerRemoteAnimations(definition);
4622 } finally {
4623 Binder.restoreCallingIdentity(origId);
4624 }
4625 }
4626 }
4627
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4629 @Override
4630 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4631 synchronized (mGlobalLock) {
4632 final long origId = Binder.clearCallingIdentity();
4633 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004634 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004640
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 @Override
4642 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004643 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004645 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004646 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004647 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004648 }
4649 }
4650
4651 @Override
4652 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004653 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004654 != PERMISSION_GRANTED) {
4655 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4656 + Binder.getCallingPid()
4657 + ", uid=" + Binder.getCallingUid()
4658 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4659 Slog.w(TAG, msg);
4660 throw new SecurityException(msg);
4661 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004662 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004664 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004665 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004666 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004667 }
4668 }
4669
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 @Override
4671 public void stopAppSwitches() {
4672 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4673 synchronized (mGlobalLock) {
4674 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004675 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004676 mDidAppSwitch = false;
4677 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4678 }
4679 }
4680
4681 @Override
4682 public void resumeAppSwitches() {
4683 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4684 synchronized (mGlobalLock) {
4685 // Note that we don't execute any pending app switches... we will
4686 // let those wait until either the timeout, or the next start
4687 // activity request.
4688 mAppSwitchesAllowedTime = 0;
4689 }
4690 }
4691
Ricky Wai906af482019-06-03 17:25:28 +01004692 long getLastStopAppSwitchesTime() {
4693 return mLastStopAppSwitchesTime;
4694 }
4695
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 void onStartActivitySetDidAppSwitch() {
4697 if (mDidAppSwitch) {
4698 // This is the second allowed switch since we stopped switches, so now just generally
4699 // allow switches. Use case:
4700 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4701 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4702 // anyone to switch again).
4703 mAppSwitchesAllowedTime = 0;
4704 } else {
4705 mDidAppSwitch = true;
4706 }
4707 }
4708
4709 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 boolean shouldDisableNonVrUiLocked() {
4711 return mVrController.shouldDisableNonVrUiLocked();
4712 }
4713
Wale Ogunwale53783742018-09-16 10:21:51 -07004714 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 // 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 +00004716 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004718 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4719 + " to main display for VR");
4720 mRootActivityContainer.moveStackToDisplay(
4721 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 }
4723 mH.post(() -> {
4724 if (!mVrController.onVrModeChanged(r)) {
4725 return;
4726 }
4727 synchronized (mGlobalLock) {
4728 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4729 mWindowManager.disableNonVrUi(disableNonVrUi);
4730 if (disableNonVrUi) {
4731 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4732 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004733 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 }
4735 }
4736 });
4737 }
4738
Wale Ogunwale53783742018-09-16 10:21:51 -07004739 @Override
4740 public int getPackageScreenCompatMode(String packageName) {
4741 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4742 synchronized (mGlobalLock) {
4743 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4744 }
4745 }
4746
4747 @Override
4748 public void setPackageScreenCompatMode(String packageName, int mode) {
4749 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4750 "setPackageScreenCompatMode");
4751 synchronized (mGlobalLock) {
4752 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4753 }
4754 }
4755
4756 @Override
4757 public boolean getPackageAskScreenCompat(String packageName) {
4758 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4759 synchronized (mGlobalLock) {
4760 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4761 }
4762 }
4763
4764 @Override
4765 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4766 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4767 "setPackageAskScreenCompat");
4768 synchronized (mGlobalLock) {
4769 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4770 }
4771 }
4772
Wale Ogunwale64258362018-10-16 15:13:37 -07004773 public static String relaunchReasonToString(int relaunchReason) {
4774 switch (relaunchReason) {
4775 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4776 return "window_resize";
4777 case RELAUNCH_REASON_FREE_RESIZE:
4778 return "free_resize";
4779 default:
4780 return null;
4781 }
4782 }
4783
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004784 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004785 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004786 }
4787
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004788 /** Pokes the task persister. */
4789 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4790 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4791 }
4792
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 boolean isKeyguardLocked() {
4794 return mKeyguardController.isKeyguardLocked();
4795 }
4796
Garfield Tan01548632018-11-27 10:15:48 -08004797 /**
4798 * Clears launch params for the given package.
4799 * @param packageNames the names of the packages of which the launch params are to be cleared
4800 */
4801 @Override
4802 public void clearLaunchParamsForPackages(List<String> packageNames) {
4803 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4804 "clearLaunchParamsForPackages");
4805 synchronized (mGlobalLock) {
4806 for (int i = 0; i < packageNames.size(); ++i) {
4807 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4808 }
4809 }
4810 }
4811
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004812 /**
4813 * Makes the display with the given id a single task instance display. I.e the display can only
4814 * contain one task.
4815 */
4816 @Override
4817 public void setDisplayToSingleTaskInstance(int displayId) {
4818 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4819 "setDisplayToSingleTaskInstance");
4820 final long origId = Binder.clearCallingIdentity();
4821 try {
4822 final ActivityDisplay display =
4823 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4824 if (display != null) {
4825 display.setDisplayToSingleTaskInstance();
4826 }
4827 } finally {
4828 Binder.restoreCallingIdentity(origId);
4829 }
4830 }
4831
Wale Ogunwale31913b52018-10-13 08:29:31 -07004832 void dumpLastANRLocked(PrintWriter pw) {
4833 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4834 if (mLastANRState == null) {
4835 pw.println(" <no ANR has occurred since boot>");
4836 } else {
4837 pw.println(mLastANRState);
4838 }
4839 }
4840
4841 void dumpLastANRTracesLocked(PrintWriter pw) {
4842 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4843
4844 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4845 if (ArrayUtils.isEmpty(files)) {
4846 pw.println(" <no ANR has occurred since boot>");
4847 return;
4848 }
4849 // Find the latest file.
4850 File latest = null;
4851 for (File f : files) {
4852 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4853 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004854 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004855 }
4856 pw.print("File: ");
4857 pw.print(latest.getName());
4858 pw.println();
4859 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4860 String line;
4861 while ((line = in.readLine()) != null) {
4862 pw.println(line);
4863 }
4864 } catch (IOException e) {
4865 pw.print("Unable to read: ");
4866 pw.print(e);
4867 pw.println();
4868 }
4869 }
4870
4871 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4872 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4873 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4874 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4875 }
4876
4877 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4878 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4879 pw.println(header);
4880
Wale Ogunwaled32da472018-11-16 07:19:28 -08004881 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004882 dumpPackage);
4883 boolean needSep = printedAnything;
4884
4885 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004886 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004887 " ResumedActivity: ");
4888 if (printed) {
4889 printedAnything = true;
4890 needSep = false;
4891 }
4892
4893 if (dumpPackage == null) {
4894 if (needSep) {
4895 pw.println();
4896 }
4897 printedAnything = true;
4898 mStackSupervisor.dump(pw, " ");
4899 }
4900
4901 if (!printedAnything) {
4902 pw.println(" (nothing)");
4903 }
4904 }
4905
4906 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004907 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004908 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004909 pw.println(" ");
4910 }
4911
4912 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4913 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4914 getActivityStartController().dump(pw, "", dumpPackage);
4915 }
4916
4917 /**
4918 * There are three things that cmd can be:
4919 * - a flattened component name that matches an existing activity
4920 * - the cmd arg isn't the flattened component name of an existing activity:
4921 * dump all activity whose component contains the cmd as a substring
4922 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004923 * <p>
4924 * The caller should not hold lock when calling this method because it will wait for the
4925 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004926 *
4927 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4928 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4929 */
4930 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4931 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4932 ArrayList<ActivityRecord> activities;
4933
4934 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004935 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004936 dumpFocusedStackOnly);
4937 }
4938
4939 if (activities.size() <= 0) {
4940 return false;
4941 }
4942
4943 String[] newArgs = new String[args.length - opti];
4944 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4945
4946 TaskRecord lastTask = null;
4947 boolean needSep = false;
4948 for (int i = activities.size() - 1; i >= 0; i--) {
4949 ActivityRecord r = activities.get(i);
4950 if (needSep) {
4951 pw.println();
4952 }
4953 needSep = true;
4954 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004955 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004956 if (lastTask != task) {
4957 lastTask = task;
4958 pw.print("TASK "); pw.print(lastTask.affinity);
4959 pw.print(" id="); pw.print(lastTask.taskId);
4960 pw.print(" userId="); pw.println(lastTask.userId);
4961 if (dumpAll) {
4962 lastTask.dump(pw, " ");
4963 }
4964 }
4965 }
4966 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4967 }
4968 return true;
4969 }
4970
4971 /**
4972 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4973 * there is a thread associated with the activity.
4974 */
4975 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4976 final ActivityRecord r, String[] args, boolean dumpAll) {
4977 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004978 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004979 synchronized (mGlobalLock) {
4980 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4981 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4982 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004983 if (r.hasProcess()) {
4984 pw.println(r.app.getPid());
4985 appThread = r.app.getThread();
4986 } else {
4987 pw.println("(not running)");
4988 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004989 if (dumpAll) {
4990 r.dump(pw, innerPrefix);
4991 }
4992 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004993 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004994 // flush anything that is already in the PrintWriter since the thread is going
4995 // to write to the file descriptor directly
4996 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004997 try (TransferPipe tp = new TransferPipe()) {
4998 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4999 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 } catch (IOException e) {
5001 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5002 } catch (RemoteException e) {
5003 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5004 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005005 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005006 }
5007
sanryhuang498e77e2018-12-06 14:57:01 +08005008 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5009 boolean testPssMode) {
5010 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5011 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5012 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005013 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5015 st.toString());
5016 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005017 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5018 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5019 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005020 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5021 testPssMode);
5022 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005023 }
5024
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025 int getCurrentUserId() {
5026 return mAmInternal.getCurrentUserId();
5027 }
5028
5029 private void enforceNotIsolatedCaller(String caller) {
5030 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5031 throw new SecurityException("Isolated process not allowed to call " + caller);
5032 }
5033 }
5034
Wale Ogunwalef6733932018-06-27 05:14:34 -07005035 public Configuration getConfiguration() {
5036 Configuration ci;
5037 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005038 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005039 ci.userSetLocale = false;
5040 }
5041 return ci;
5042 }
5043
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005044 /**
5045 * Current global configuration information. Contains general settings for the entire system,
5046 * also corresponds to the merged configuration of the default display.
5047 */
5048 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005049 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005050 }
5051
5052 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5053 boolean initLocale) {
5054 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5055 }
5056
5057 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5058 boolean initLocale, boolean deferResume) {
5059 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5060 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5061 UserHandle.USER_NULL, deferResume);
5062 }
5063
Wale Ogunwale59507092018-10-29 09:00:30 -07005064 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005065 final long origId = Binder.clearCallingIdentity();
5066 try {
5067 synchronized (mGlobalLock) {
5068 updateConfigurationLocked(values, null, false, true, userId,
5069 false /* deferResume */);
5070 }
5071 } finally {
5072 Binder.restoreCallingIdentity(origId);
5073 }
5074 }
5075
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5077 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5078 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5079 deferResume, null /* result */);
5080 }
5081
5082 /**
5083 * Do either or both things: (1) change the current configuration, and (2)
5084 * make sure the given activity is running with the (now) current
5085 * configuration. Returns true if the activity has been left running, or
5086 * false if <var>starting</var> is being destroyed to match the new
5087 * configuration.
5088 *
5089 * @param userId is only used when persistent parameter is set to true to persist configuration
5090 * for that particular user
5091 */
5092 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5093 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5094 ActivityTaskManagerService.UpdateConfigurationResult result) {
5095 int changes = 0;
5096 boolean kept = true;
5097
5098 if (mWindowManager != null) {
5099 mWindowManager.deferSurfaceLayout();
5100 }
5101 try {
5102 if (values != null) {
5103 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5104 deferResume);
5105 }
5106
5107 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5108 } finally {
5109 if (mWindowManager != null) {
5110 mWindowManager.continueSurfaceLayout();
5111 }
5112 }
5113
5114 if (result != null) {
5115 result.changes = changes;
5116 result.activityRelaunched = !kept;
5117 }
5118 return kept;
5119 }
5120
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005121 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005122 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005123 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005124
5125 final ActivityDisplay defaultDisplay =
5126 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 mTempConfig.setTo(getGlobalConfiguration());
5129 final int changes = mTempConfig.updateFrom(values);
5130 if (changes == 0) {
5131 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5132 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5133 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5134 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005135 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005136 return 0;
5137 }
5138
5139 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5140 "Updating global configuration to: " + values);
5141
5142 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5143 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5144 values.colorMode,
5145 values.densityDpi,
5146 values.fontScale,
5147 values.hardKeyboardHidden,
5148 values.keyboard,
5149 values.keyboardHidden,
5150 values.mcc,
5151 values.mnc,
5152 values.navigation,
5153 values.navigationHidden,
5154 values.orientation,
5155 values.screenHeightDp,
5156 values.screenLayout,
5157 values.screenWidthDp,
5158 values.smallestScreenWidthDp,
5159 values.touchscreen,
5160 values.uiMode);
5161
5162
5163 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5164 final LocaleList locales = values.getLocales();
5165 int bestLocaleIndex = 0;
5166 if (locales.size() > 1) {
5167 if (mSupportedSystemLocales == null) {
5168 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5169 }
5170 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5171 }
5172 SystemProperties.set("persist.sys.locale",
5173 locales.get(bestLocaleIndex).toLanguageTag());
5174 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005175
5176 final Message m = PooledLambda.obtainMessage(
5177 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5178 locales.get(bestLocaleIndex));
5179 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 }
5181
Yunfan Chen75157d72018-07-27 14:47:21 +09005182 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183
5184 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005185 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186
5187 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5188 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005189 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005192 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193
5194 AttributeCache ac = AttributeCache.instance();
5195 if (ac != null) {
5196 ac.updateConfiguration(mTempConfig);
5197 }
5198
5199 // Make sure all resources in our process are updated right now, so that anyone who is going
5200 // to retrieve resource values after we return will be sure to get the new ones. This is
5201 // especially important during boot, where the first config change needs to guarantee all
5202 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005203 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005204
5205 // We need another copy of global config because we're scheduling some calls instead of
5206 // running them in place. We need to be sure that object we send will be handled unchanged.
5207 final Configuration configCopy = new Configuration(mTempConfig);
5208 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005209 final Message msg = PooledLambda.obtainMessage(
5210 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5211 this, userId, configCopy);
5212 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 }
5214
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005215 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5216 for (int i = pidMap.size() - 1; i >= 0; i--) {
5217 final int pid = pidMap.keyAt(i);
5218 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005219 if (DEBUG_CONFIGURATION) {
5220 Slog.v(TAG_CONFIGURATION, "Update process config of "
5221 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005223 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 }
5225
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005226 final Message msg = PooledLambda.obtainMessage(
5227 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5228 mAmInternal, changes, initLocale);
5229 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 // Override configuration of the default display duplicates global config, so we need to
5232 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005233 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5234 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235
5236 return changes;
5237 }
5238
Wale Ogunwalef6733932018-06-27 05:14:34 -07005239 private void updateEventDispatchingLocked(boolean booted) {
5240 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5241 }
5242
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005243 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5244 final ContentResolver resolver = mContext.getContentResolver();
5245 Settings.System.putConfigurationForUser(resolver, config, userId);
5246 }
5247
5248 private void sendLocaleToMountDaemonMsg(Locale l) {
5249 try {
5250 IBinder service = ServiceManager.getService("mount");
5251 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5252 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5253 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5254 } catch (RemoteException e) {
5255 Log.e(TAG, "Error storing locale for decryption UI", e);
5256 }
5257 }
5258
Alison Cichowlas3e340502018-08-07 17:15:01 -04005259 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5260 mStartActivitySources.remove(permissionToken);
5261 mExpiredStartAsCallerTokens.add(permissionToken);
5262 }
5263
5264 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5265 mExpiredStartAsCallerTokens.remove(permissionToken);
5266 }
5267
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005268 boolean isActivityStartsLoggingEnabled() {
5269 return mAmInternal.isActivityStartsLoggingEnabled();
5270 }
5271
Michal Karpinski8596ded2018-11-14 14:43:48 +00005272 boolean isBackgroundActivityStartsEnabled() {
5273 return mAmInternal.isBackgroundActivityStartsEnabled();
5274 }
5275
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276 void enableScreenAfterBoot(boolean booted) {
5277 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5278 SystemClock.uptimeMillis());
5279 mWindowManager.enableScreenAfterBoot();
5280
5281 synchronized (mGlobalLock) {
5282 updateEventDispatchingLocked(booted);
5283 }
5284 }
5285
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005286 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5287 if (r == null || !r.hasProcess()) {
5288 return KEY_DISPATCHING_TIMEOUT_MS;
5289 }
5290 return getInputDispatchingTimeoutLocked(r.app);
5291 }
5292
5293 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005294 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005295 }
5296
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 /**
5298 * Decide based on the configuration whether we should show the ANR,
5299 * crash, etc dialogs. The idea is that if there is no affordance to
5300 * press the on-screen buttons, or the user experience would be more
5301 * greatly impacted than the crash itself, we shouldn't show the dialog.
5302 *
5303 * A thought: SystemUI might also want to get told about this, the Power
5304 * dialog / global actions also might want different behaviors.
5305 */
5306 private void updateShouldShowDialogsLocked(Configuration config) {
5307 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5308 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5309 && config.navigation == Configuration.NAVIGATION_NONAV);
5310 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5311 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5312 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5313 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5314 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5315 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5316 HIDE_ERROR_DIALOGS, 0) != 0;
5317 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5318 }
5319
5320 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5321 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5322 FONT_SCALE, 1.0f, userId);
5323
5324 synchronized (this) {
5325 if (getGlobalConfiguration().fontScale == scaleFactor) {
5326 return;
5327 }
5328
5329 final Configuration configuration
5330 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5331 configuration.fontScale = scaleFactor;
5332 updatePersistentConfiguration(configuration, userId);
5333 }
5334 }
5335
5336 // Actually is sleeping or shutting down or whatever else in the future
5337 // is an inactive state.
5338 boolean isSleepingOrShuttingDownLocked() {
5339 return isSleepingLocked() || mShuttingDown;
5340 }
5341
5342 boolean isSleepingLocked() {
5343 return mSleeping;
5344 }
5345
Riddle Hsu16567132018-08-16 21:37:47 +08005346 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005347 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005348 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005349 if (task.isActivityTypeStandard()) {
5350 if (mCurAppTimeTracker != r.appTimeTracker) {
5351 // We are switching app tracking. Complete the current one.
5352 if (mCurAppTimeTracker != null) {
5353 mCurAppTimeTracker.stop();
5354 mH.obtainMessage(
5355 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005356 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 mCurAppTimeTracker = null;
5358 }
5359 if (r.appTimeTracker != null) {
5360 mCurAppTimeTracker = r.appTimeTracker;
5361 startTimeTrackingFocusedActivityLocked();
5362 }
5363 } else {
5364 startTimeTrackingFocusedActivityLocked();
5365 }
5366 } else {
5367 r.appTimeTracker = null;
5368 }
5369 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5370 // TODO: Probably not, because we don't want to resume voice on switching
5371 // back to this activity
5372 if (task.voiceInteractor != null) {
5373 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5374 } else {
5375 finishRunningVoiceLocked();
5376
5377 if (mLastResumedActivity != null) {
5378 final IVoiceInteractionSession session;
5379
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005380 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005381 if (lastResumedActivityTask != null
5382 && lastResumedActivityTask.voiceSession != null) {
5383 session = lastResumedActivityTask.voiceSession;
5384 } else {
5385 session = mLastResumedActivity.voiceSession;
5386 }
5387
5388 if (session != null) {
5389 // We had been in a voice interaction session, but now focused has
5390 // move to something different. Just finish the session, we can't
5391 // return to it and retain the proper state and synchronization with
5392 // the voice interaction service.
5393 finishVoiceTask(session);
5394 }
5395 }
5396 }
5397
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005398 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5399 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 }
5401 updateResumedAppTrace(r);
5402 mLastResumedActivity = r;
5403
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005404 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005405
5406 applyUpdateLockStateLocked(r);
5407 applyUpdateVrModeLocked(r);
5408
5409 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005410 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 r == null ? "NULL" : r.shortComponentName,
5412 reason);
5413 }
5414
5415 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5416 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005417 final ActivityTaskManagerInternal.SleepToken token =
5418 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005419 updateSleepIfNeededLocked();
5420 return token;
5421 }
5422 }
5423
5424 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005425 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426 final boolean wasSleeping = mSleeping;
5427 boolean updateOomAdj = false;
5428
5429 if (!shouldSleep) {
5430 // If wasSleeping is true, we need to wake up activity manager state from when
5431 // we started sleeping. In either case, we need to apply the sleep tokens, which
5432 // will wake up stacks or put them to sleep as appropriate.
5433 if (wasSleeping) {
5434 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005435 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5436 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 startTimeTrackingFocusedActivityLocked();
5438 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005439 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5441 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005442 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 if (wasSleeping) {
5444 updateOomAdj = true;
5445 }
5446 } else if (!mSleeping && shouldSleep) {
5447 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005448 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5449 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 if (mCurAppTimeTracker != null) {
5451 mCurAppTimeTracker.stop();
5452 }
5453 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005454 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 mStackSupervisor.goingToSleepLocked();
5456 updateResumedAppTrace(null /* resumed */);
5457 updateOomAdj = true;
5458 }
5459 if (updateOomAdj) {
5460 mH.post(mAmInternal::updateOomAdj);
5461 }
5462 }
5463
5464 void updateOomAdj() {
5465 mH.post(mAmInternal::updateOomAdj);
5466 }
5467
Wale Ogunwale53783742018-09-16 10:21:51 -07005468 void updateCpuStats() {
5469 mH.post(mAmInternal::updateCpuStats);
5470 }
5471
Hui Yu03d12402018-12-06 18:00:37 -08005472 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5473 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005474 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5475 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005476 mH.sendMessage(m);
5477 }
5478
Hui Yu03d12402018-12-06 18:00:37 -08005479 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005480 ComponentName taskRoot = null;
5481 final TaskRecord task = activity.getTaskRecord();
5482 if (task != null) {
5483 final ActivityRecord rootActivity = task.getRootActivity();
5484 if (rootActivity != null) {
5485 taskRoot = rootActivity.mActivityComponent;
5486 }
5487 }
5488
Hui Yu03d12402018-12-06 18:00:37 -08005489 final Message m = PooledLambda.obtainMessage(
5490 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005491 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005492 mH.sendMessage(m);
5493 }
5494
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005495 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5496 String hostingType) {
5497 try {
5498 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5499 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5500 + activity.processName);
5501 }
5502 // Post message to start process to avoid possible deadlock of calling into AMS with the
5503 // ATMS lock held.
5504 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5505 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5506 isTop, hostingType, activity.intent.getComponent());
5507 mH.sendMessage(m);
5508 } finally {
5509 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5510 }
5511 }
5512
Wale Ogunwale53783742018-09-16 10:21:51 -07005513 void setBooting(boolean booting) {
5514 mAmInternal.setBooting(booting);
5515 }
5516
5517 boolean isBooting() {
5518 return mAmInternal.isBooting();
5519 }
5520
5521 void setBooted(boolean booted) {
5522 mAmInternal.setBooted(booted);
5523 }
5524
5525 boolean isBooted() {
5526 return mAmInternal.isBooted();
5527 }
5528
5529 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5530 mH.post(() -> {
5531 if (finishBooting) {
5532 mAmInternal.finishBooting();
5533 }
5534 if (enableScreen) {
5535 mInternal.enableScreenAfterBoot(isBooted());
5536 }
5537 });
5538 }
5539
5540 void setHeavyWeightProcess(ActivityRecord root) {
5541 mHeavyWeightProcess = root.app;
5542 final Message m = PooledLambda.obtainMessage(
5543 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005544 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005545 mH.sendMessage(m);
5546 }
5547
5548 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5549 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5550 return;
5551 }
5552
5553 mHeavyWeightProcess = null;
5554 final Message m = PooledLambda.obtainMessage(
5555 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5556 proc.mUserId);
5557 mH.sendMessage(m);
5558 }
5559
5560 private void cancelHeavyWeightProcessNotification(int userId) {
5561 final INotificationManager inm = NotificationManager.getService();
5562 if (inm == null) {
5563 return;
5564 }
5565 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005566 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005567 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5568 } catch (RuntimeException e) {
5569 Slog.w(TAG, "Error canceling notification for service", e);
5570 } catch (RemoteException e) {
5571 }
5572
5573 }
5574
5575 private void postHeavyWeightProcessNotification(
5576 WindowProcessController proc, Intent intent, int userId) {
5577 if (proc == null) {
5578 return;
5579 }
5580
5581 final INotificationManager inm = NotificationManager.getService();
5582 if (inm == null) {
5583 return;
5584 }
5585
5586 try {
5587 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5588 String text = mContext.getString(R.string.heavy_weight_notification,
5589 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5590 Notification notification =
5591 new Notification.Builder(context,
5592 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5593 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5594 .setWhen(0)
5595 .setOngoing(true)
5596 .setTicker(text)
5597 .setColor(mContext.getColor(
5598 com.android.internal.R.color.system_notification_accent_color))
5599 .setContentTitle(text)
5600 .setContentText(
5601 mContext.getText(R.string.heavy_weight_notification_detail))
5602 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5603 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5604 new UserHandle(userId)))
5605 .build();
5606 try {
5607 inm.enqueueNotificationWithTag("android", "android", null,
5608 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5609 } catch (RuntimeException e) {
5610 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5611 } catch (RemoteException e) {
5612 }
5613 } catch (PackageManager.NameNotFoundException e) {
5614 Slog.w(TAG, "Unable to create context for heavy notification", e);
5615 }
5616
5617 }
5618
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005619 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5620 IBinder token, String resultWho, int requestCode, Intent[] intents,
5621 String[] resolvedTypes, int flags, Bundle bOptions) {
5622
5623 ActivityRecord activity = null;
5624 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5625 activity = ActivityRecord.isInStackLocked(token);
5626 if (activity == null) {
5627 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5628 return null;
5629 }
5630 if (activity.finishing) {
5631 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5632 return null;
5633 }
5634 }
5635
5636 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5637 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5638 bOptions);
5639 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5640 if (noCreate) {
5641 return rec;
5642 }
5643 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5644 if (activity.pendingResults == null) {
5645 activity.pendingResults = new HashSet<>();
5646 }
5647 activity.pendingResults.add(rec.ref);
5648 }
5649 return rec;
5650 }
5651
Andrii Kulian52d255c2018-07-13 11:32:19 -07005652 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005653 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005654 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005655 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5656 mCurAppTimeTracker.start(resumedActivity.packageName);
5657 }
5658 }
5659
5660 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5661 if (mTracedResumedActivity != null) {
5662 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5663 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5664 }
5665 if (resumed != null) {
5666 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5667 constructResumedTraceName(resumed.packageName), 0);
5668 }
5669 mTracedResumedActivity = resumed;
5670 }
5671
5672 private String constructResumedTraceName(String packageName) {
5673 return "focused app: " + packageName;
5674 }
5675
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005676 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005677 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005678 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005679 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005680 // mainStack is null during startup.
5681 if (mainStack != null) {
5682 if (changes != 0 && starting == null) {
5683 // If the configuration changed, and the caller is not already
5684 // in the process of starting an activity, then find the top
5685 // activity to check if its configuration needs to change.
5686 starting = mainStack.topRunningActivityLocked();
5687 }
5688
5689 if (starting != null) {
5690 kept = starting.ensureActivityConfiguration(changes,
5691 false /* preserveWindow */);
5692 // And we need to make sure at this point that all other activities
5693 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005694 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005695 !PRESERVE_WINDOWS);
5696 }
5697 }
5698
5699 return kept;
5700 }
5701
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005702 void scheduleAppGcsLocked() {
5703 mH.post(() -> mAmInternal.scheduleAppGcs());
5704 }
5705
Wale Ogunwale53783742018-09-16 10:21:51 -07005706 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5707 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5708 }
5709
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005710 /**
5711 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5712 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5713 * on demand.
5714 */
5715 IPackageManager getPackageManager() {
5716 return AppGlobals.getPackageManager();
5717 }
5718
5719 PackageManagerInternal getPackageManagerInternalLocked() {
5720 if (mPmInternal == null) {
5721 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5722 }
5723 return mPmInternal;
5724 }
5725
Hai Zhangf4da9be2019-05-01 13:46:06 +08005726 PermissionPolicyInternal getPermissionPolicyInternal() {
5727 if (mPermissionPolicyInternal == null) {
5728 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5729 }
5730 return mPermissionPolicyInternal;
5731 }
5732
Wale Ogunwale008163e2018-07-23 23:11:08 -07005733 AppWarnings getAppWarningsLocked() {
5734 return mAppWarnings;
5735 }
5736
Wale Ogunwale214f3482018-10-04 11:00:47 -07005737 Intent getHomeIntent() {
5738 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5739 intent.setComponent(mTopComponent);
5740 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5741 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5742 intent.addCategory(Intent.CATEGORY_HOME);
5743 }
5744 return intent;
5745 }
5746
Chilun2ef71f72018-11-16 17:57:15 +08005747 /**
5748 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5749 * activities.
5750 *
5751 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5752 * component defined in config_secondaryHomeComponent.
5753 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5754 */
5755 Intent getSecondaryHomeIntent(String preferredPackage) {
5756 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005757 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5758 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5759 if (preferredPackage == null || useSystemProvidedLauncher) {
5760 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005761 final String secondaryHomeComponent = mContext.getResources().getString(
5762 com.android.internal.R.string.config_secondaryHomeComponent);
5763 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5764 } else {
5765 intent.setPackage(preferredPackage);
5766 }
5767 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5768 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5769 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5770 }
5771 return intent;
5772 }
5773
Wale Ogunwale214f3482018-10-04 11:00:47 -07005774 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5775 if (info == null) return null;
5776 ApplicationInfo newInfo = new ApplicationInfo(info);
5777 newInfo.initForUser(userId);
5778 return newInfo;
5779 }
5780
Wale Ogunwale9c103022018-10-18 07:44:54 -07005781 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005782 if (uid == SYSTEM_UID) {
5783 // The system gets to run in any process. If there are multiple processes with the same
5784 // uid, just pick the first (this should never happen).
5785 final SparseArray<WindowProcessController> procs =
5786 mProcessNames.getMap().get(processName);
5787 if (procs == null) return null;
5788 final int procCount = procs.size();
5789 for (int i = 0; i < procCount; i++) {
5790 final int procUid = procs.keyAt(i);
5791 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5792 // Don't use an app process or different user process for system component.
5793 continue;
5794 }
5795 return procs.valueAt(i);
5796 }
5797 }
5798
5799 return mProcessNames.get(processName, uid);
5800 }
5801
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005802 WindowProcessController getProcessController(IApplicationThread thread) {
5803 if (thread == null) {
5804 return null;
5805 }
5806
5807 final IBinder threadBinder = thread.asBinder();
5808 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5809 for (int i = pmap.size()-1; i >= 0; i--) {
5810 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5811 for (int j = procs.size() - 1; j >= 0; j--) {
5812 final WindowProcessController proc = procs.valueAt(j);
5813 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5814 return proc;
5815 }
5816 }
5817 }
5818
5819 return null;
5820 }
5821
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005822 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005823 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005824 if (proc == null) return null;
5825 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5826 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005827 }
5828 return null;
5829 }
5830
Riddle Hsua0536432019-02-16 00:38:59 +08005831 int getUidState(int uid) {
5832 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005833 }
5834
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005835 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005836 // A uid is considered to be foreground if it has a visible non-toast window.
5837 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005838 }
5839
Ricky Wai96f5c352019-04-10 18:40:17 +01005840 boolean isDeviceOwner(int uid) {
5841 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005842 }
5843
Ricky Wai96f5c352019-04-10 18:40:17 +01005844 void setDeviceOwnerUid(int uid) {
5845 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005846 }
5847
Wale Ogunwale9de19442018-10-18 19:05:03 -07005848 /**
5849 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5850 * the whitelist
5851 */
5852 String getPendingTempWhitelistTagForUidLocked(int uid) {
5853 return mPendingTempWhitelist.get(uid);
5854 }
5855
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005856 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5857 if (true || Build.IS_USER) {
5858 return;
5859 }
5860
5861 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5862 StrictMode.allowThreadDiskWrites();
5863 try {
5864 File tracesDir = new File("/data/anr");
5865 File tracesFile = null;
5866 try {
5867 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5868
5869 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005870 String timeString =
5871 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5872 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005873 sb.append(": ");
5874 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5875 sb.append(" since ");
5876 sb.append(msg);
5877 FileOutputStream fos = new FileOutputStream(tracesFile);
5878 fos.write(sb.toString().getBytes());
5879 if (app == null) {
5880 fos.write("\n*** No application process!".getBytes());
5881 }
5882 fos.close();
5883 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5884 } catch (IOException e) {
5885 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5886 return;
5887 }
5888
5889 if (app != null && app.getPid() > 0) {
5890 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5891 firstPids.add(app.getPid());
5892 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5893 }
5894
5895 File lastTracesFile = null;
5896 File curTracesFile = null;
5897 for (int i=9; i>=0; i--) {
5898 String name = String.format(Locale.US, "slow%02d.txt", i);
5899 curTracesFile = new File(tracesDir, name);
5900 if (curTracesFile.exists()) {
5901 if (lastTracesFile != null) {
5902 curTracesFile.renameTo(lastTracesFile);
5903 } else {
5904 curTracesFile.delete();
5905 }
5906 }
5907 lastTracesFile = curTracesFile;
5908 }
5909 tracesFile.renameTo(curTracesFile);
5910 } finally {
5911 StrictMode.setThreadPolicy(oldPolicy);
5912 }
5913 }
5914
Michal Karpinskida34cd42019-04-02 19:46:52 +01005915 boolean isAssociatedCompanionApp(int userId, int uid) {
5916 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5917 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005918 return false;
5919 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005920 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005921 }
5922
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005923 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005924 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005925
5926
Wale Ogunwale98875612018-10-12 07:53:02 -07005927 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5928 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005929
Riddle Hsud93a6c42018-11-29 21:50:06 +08005930 H(Looper looper) {
5931 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005932 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005933
5934 @Override
5935 public void handleMessage(Message msg) {
5936 switch (msg.what) {
5937 case REPORT_TIME_TRACKER_MSG: {
5938 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5939 tracker.deliverResult(mContext);
5940 } break;
5941 }
5942 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005943 }
5944
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005945 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005946 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005947
5948 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005949 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005951
5952 @Override
5953 public void handleMessage(Message msg) {
5954 switch (msg.what) {
5955 case DISMISS_DIALOG_UI_MSG: {
5956 final Dialog d = (Dialog) msg.obj;
5957 d.dismiss();
5958 break;
5959 }
5960 }
5961 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005962 }
5963
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005964 final class LocalService extends ActivityTaskManagerInternal {
5965 @Override
5966 public SleepToken acquireSleepToken(String tag, int displayId) {
5967 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005968 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005969 }
5970
5971 @Override
5972 public ComponentName getHomeActivityForUser(int userId) {
5973 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005974 final ActivityRecord homeActivity =
5975 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005976 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005977 }
5978 }
5979
5980 @Override
5981 public void onLocalVoiceInteractionStarted(IBinder activity,
5982 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5983 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005984 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005985 }
5986 }
5987
5988 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005989 public void notifyAppTransitionStarting(SparseIntArray reasons,
5990 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005991 synchronized (mGlobalLock) {
5992 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5993 reasons, timestamp);
5994 }
5995 }
5996
5997 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005998 public void notifySingleTaskDisplayDrawn(int displayId) {
5999 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6000 }
6001
6002 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 public void notifyAppTransitionFinished() {
6004 synchronized (mGlobalLock) {
6005 mStackSupervisor.notifyAppTransitionDone();
6006 }
6007 }
6008
6009 @Override
6010 public void notifyAppTransitionCancelled() {
6011 synchronized (mGlobalLock) {
6012 mStackSupervisor.notifyAppTransitionDone();
6013 }
6014 }
6015
6016 @Override
6017 public List<IBinder> getTopVisibleActivities() {
6018 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006019 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006020 }
6021 }
6022
6023 @Override
6024 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6025 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006026 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006027 }
6028 }
6029
6030 @Override
6031 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6032 Bundle bOptions) {
6033 Preconditions.checkNotNull(intents, "intents");
6034 final String[] resolvedTypes = new String[intents.length];
6035
6036 // UID of the package on user userId.
6037 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6038 // packageUid may not be initialized.
6039 int packageUid = 0;
6040 final long ident = Binder.clearCallingIdentity();
6041
6042 try {
6043 for (int i = 0; i < intents.length; i++) {
6044 resolvedTypes[i] =
6045 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6046 }
6047
6048 packageUid = AppGlobals.getPackageManager().getPackageUid(
6049 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6050 } catch (RemoteException e) {
6051 // Shouldn't happen.
6052 } finally {
6053 Binder.restoreCallingIdentity(ident);
6054 }
6055
Riddle Hsu591bf612019-02-14 17:55:31 +08006056 return getActivityStartController().startActivitiesInPackage(
6057 packageUid, packageName,
6058 intents, resolvedTypes, null /* resultTo */,
6059 SafeActivityOptions.fromBundle(bOptions), userId,
6060 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6061 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006062 }
6063
6064 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006065 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6066 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6067 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6068 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006069 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006070 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006071 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6072 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6073 userId, validateIncomingUser, originatingPendingIntent,
6074 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006075 }
6076 }
6077
6078 @Override
6079 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6080 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6081 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6082 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006083 PendingIntentRecord originatingPendingIntent,
6084 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006085 synchronized (mGlobalLock) {
6086 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6087 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6088 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006089 validateIncomingUser, originatingPendingIntent,
6090 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006091 }
6092 }
6093
6094 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6096 Intent intent, Bundle options, int userId) {
6097 return ActivityTaskManagerService.this.startActivityAsUser(
6098 caller, callerPacakge, intent,
6099 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6100 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6101 false /*validateIncomingUser*/);
6102 }
6103
6104 @Override
lumark588a3e82018-07-20 18:53:54 +08006105 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 synchronized (mGlobalLock) {
6107
6108 // We might change the visibilities here, so prepare an empty app transition which
6109 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006110 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006111 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006112 if (activityDisplay == null) {
6113 return;
6114 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006115 final DisplayContent dc = activityDisplay.mDisplayContent;
6116 final boolean wasTransitionSet =
6117 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006118 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006119 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006121 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122
6123 // If there was a transition set already we don't want to interfere with it as we
6124 // might be starting it too early.
6125 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006126 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128 }
6129 if (callback != null) {
6130 callback.run();
6131 }
6132 }
6133
6134 @Override
6135 public void notifyKeyguardTrustedChanged() {
6136 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006137 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006138 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006139 }
6140 }
6141 }
6142
6143 /**
6144 * Called after virtual display Id is updated by
6145 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6146 * {@param vrVr2dDisplayId}.
6147 */
6148 @Override
6149 public void setVr2dDisplayId(int vr2dDisplayId) {
6150 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6151 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006152 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 }
6154 }
6155
6156 @Override
6157 public void setFocusedActivity(IBinder token) {
6158 synchronized (mGlobalLock) {
6159 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6160 if (r == null) {
6161 throw new IllegalArgumentException(
6162 "setFocusedActivity: No activity record matching token=" + token);
6163 }
Louis Chang19443452018-10-09 12:10:21 +08006164 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006165 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167 }
6168 }
6169
6170 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006172 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 }
6174
6175 @Override
6176 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006177 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179
6180 @Override
6181 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006182 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006183 }
6184
6185 @Override
6186 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6187 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6188 }
6189
6190 @Override
6191 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006192 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006194
6195 @Override
6196 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6197 synchronized (mGlobalLock) {
6198 mActiveVoiceInteractionServiceComponent = component;
6199 }
6200 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006201
6202 @Override
6203 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6204 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6205 return;
6206 }
6207 synchronized (mGlobalLock) {
6208 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6209 if (types == null) {
6210 if (uid < 0) {
6211 return;
6212 }
6213 types = new ArrayMap<>();
6214 mAllowAppSwitchUids.put(userId, types);
6215 }
6216 if (uid < 0) {
6217 types.remove(type);
6218 } else {
6219 types.put(type, uid);
6220 }
6221 }
6222 }
6223
6224 @Override
6225 public void onUserStopped(int userId) {
6226 synchronized (mGlobalLock) {
6227 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6228 mAllowAppSwitchUids.remove(userId);
6229 }
6230 }
6231
6232 @Override
6233 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6234 synchronized (mGlobalLock) {
6235 return ActivityTaskManagerService.this.isGetTasksAllowed(
6236 caller, callingPid, callingUid);
6237 }
6238 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006239
Riddle Hsua0536432019-02-16 00:38:59 +08006240 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006241 @Override
6242 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006243 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006244 mProcessNames.put(proc.mName, proc.mUid, proc);
6245 }
6246 }
6247
Riddle Hsua0536432019-02-16 00:38:59 +08006248 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006249 @Override
6250 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006251 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 mProcessNames.remove(name, uid);
6253 }
6254 }
6255
Riddle Hsua0536432019-02-16 00:38:59 +08006256 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006257 @Override
6258 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006259 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006260 if (proc == mHomeProcess) {
6261 mHomeProcess = null;
6262 }
6263 if (proc == mPreviousProcess) {
6264 mPreviousProcess = null;
6265 }
6266 }
6267 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006268
Riddle Hsua0536432019-02-16 00:38:59 +08006269 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006270 @Override
6271 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006272 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006273 return mTopProcessState;
6274 }
6275 }
6276
Riddle Hsua0536432019-02-16 00:38:59 +08006277 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006278 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006279 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006280 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 return proc == mHeavyWeightProcess;
6282 }
6283 }
6284
Riddle Hsua0536432019-02-16 00:38:59 +08006285 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006286 @Override
6287 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006288 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006289 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6290 }
6291 }
6292
6293 @Override
6294 public void finishHeavyWeightApp() {
6295 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006296 if (mHeavyWeightProcess != null) {
6297 mHeavyWeightProcess.finishActivities();
6298 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006299 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6300 mHeavyWeightProcess);
6301 }
6302 }
6303
Riddle Hsua0536432019-02-16 00:38:59 +08006304 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006305 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006308 return isSleepingLocked();
6309 }
6310 }
6311
6312 @Override
6313 public boolean isShuttingDown() {
6314 synchronized (mGlobalLock) {
6315 return mShuttingDown;
6316 }
6317 }
6318
6319 @Override
6320 public boolean shuttingDown(boolean booted, int timeout) {
6321 synchronized (mGlobalLock) {
6322 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006323 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006324 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006325 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006326 return mStackSupervisor.shutdownLocked(timeout);
6327 }
6328 }
6329
6330 @Override
6331 public void enableScreenAfterBoot(boolean booted) {
6332 synchronized (mGlobalLock) {
6333 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6334 SystemClock.uptimeMillis());
6335 mWindowManager.enableScreenAfterBoot();
6336 updateEventDispatchingLocked(booted);
6337 }
6338 }
6339
6340 @Override
6341 public boolean showStrictModeViolationDialog() {
6342 synchronized (mGlobalLock) {
6343 return mShowDialogs && !mSleeping && !mShuttingDown;
6344 }
6345 }
6346
6347 @Override
6348 public void showSystemReadyErrorDialogsIfNeeded() {
6349 synchronized (mGlobalLock) {
6350 try {
6351 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6352 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6353 + " data partition or your device will be unstable.");
6354 mUiHandler.post(() -> {
6355 if (mShowDialogs) {
6356 AlertDialog d = new BaseErrorDialog(mUiContext);
6357 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6358 d.setCancelable(false);
6359 d.setTitle(mUiContext.getText(R.string.android_system_label));
6360 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6361 d.setButton(DialogInterface.BUTTON_POSITIVE,
6362 mUiContext.getText(R.string.ok),
6363 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6364 d.show();
6365 }
6366 });
6367 }
6368 } catch (RemoteException e) {
6369 }
6370
6371 if (!Build.isBuildConsistent()) {
6372 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6373 mUiHandler.post(() -> {
6374 if (mShowDialogs) {
6375 AlertDialog d = new BaseErrorDialog(mUiContext);
6376 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6377 d.setCancelable(false);
6378 d.setTitle(mUiContext.getText(R.string.android_system_label));
6379 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6380 d.setButton(DialogInterface.BUTTON_POSITIVE,
6381 mUiContext.getText(R.string.ok),
6382 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6383 d.show();
6384 }
6385 });
6386 }
6387 }
6388 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006389
6390 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006391 public void onProcessMapped(int pid, WindowProcessController proc) {
6392 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006393 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006394 }
6395 }
6396
6397 @Override
6398 public void onProcessUnMapped(int pid) {
6399 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006400 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006401 }
6402 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006403
6404 @Override
6405 public void onPackageDataCleared(String name) {
6406 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006407 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006408 mAppWarnings.onPackageDataCleared(name);
6409 }
6410 }
6411
6412 @Override
6413 public void onPackageUninstalled(String name) {
6414 synchronized (mGlobalLock) {
6415 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006416 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006417 }
6418 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006419
6420 @Override
6421 public void onPackageAdded(String name, boolean replacing) {
6422 synchronized (mGlobalLock) {
6423 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6424 }
6425 }
6426
6427 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006428 public void onPackageReplaced(ApplicationInfo aInfo) {
6429 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006430 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006431 }
6432 }
6433
6434 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6436 synchronized (mGlobalLock) {
6437 return compatibilityInfoForPackageLocked(ai);
6438 }
6439 }
6440
Yunfan Chen75157d72018-07-27 14:47:21 +09006441 /**
6442 * Set the corresponding display information for the process global configuration. To be
6443 * called when we need to show IME on a different display.
6444 *
6445 * @param pid The process id associated with the IME window.
6446 * @param displayId The ID of the display showing the IME.
6447 */
6448 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006449 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006450 // Don't update process-level configuration for Multi-Client IME process since other
6451 // IMEs on other displays will also receive this configuration change due to IME
6452 // services use the same application config/context.
6453 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006454
Yunfan Chen75157d72018-07-27 14:47:21 +09006455 if (pid == MY_PID || pid < 0) {
6456 if (DEBUG_CONFIGURATION) {
6457 Slog.w(TAG,
6458 "Trying to update display configuration for system/invalid process.");
6459 }
6460 return;
6461 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006462 synchronized (mGlobalLock) {
6463 final ActivityDisplay activityDisplay =
6464 mRootActivityContainer.getActivityDisplay(displayId);
6465 if (activityDisplay == null) {
6466 // Call might come when display is not yet added or has been removed.
6467 if (DEBUG_CONFIGURATION) {
6468 Slog.w(TAG, "Trying to update display configuration for non-existing "
6469 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006470 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006471 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006472 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006473 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006474 if (process == null) {
6475 if (DEBUG_CONFIGURATION) {
6476 Slog.w(TAG, "Trying to update display configuration for invalid "
6477 + "process, pid=" + pid);
6478 }
6479 return;
6480 }
lumarkddc77fb2019-06-27 22:22:23 +08006481 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006482 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6483 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006484 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006485
6486 @Override
6487 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006488 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006489 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006490 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6491 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006492 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006493 }
6494 }
6495 }
6496
6497 @Override
6498 public void clearPendingResultForActivity(IBinder activityToken,
6499 WeakReference<PendingIntentRecord> pir) {
6500 synchronized (mGlobalLock) {
6501 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6502 if (r != null && r.pendingResults != null) {
6503 r.pendingResults.remove(pir);
6504 }
6505 }
6506 }
6507
6508 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006509 public ActivityTokens getTopActivityForTask(int taskId) {
6510 synchronized (mGlobalLock) {
6511 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6512 if (taskRecord == null) {
6513 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6514 + " Requested task not found");
6515 return null;
6516 }
6517 final ActivityRecord activity = taskRecord.getTopActivity();
6518 if (activity == null) {
6519 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6520 + " Requested activity not found");
6521 return null;
6522 }
6523 if (!activity.attachedToProcess()) {
6524 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6525 + activity);
6526 return null;
6527 }
6528 return new ActivityTokens(activity.appToken, activity.assistToken,
6529 activity.app.getThread());
6530 }
6531 }
6532
6533 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006534 public IIntentSender getIntentSender(int type, String packageName,
6535 int callingUid, int userId, IBinder token, String resultWho,
6536 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6537 Bundle bOptions) {
6538 synchronized (mGlobalLock) {
6539 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6540 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6541 }
6542 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006543
6544 @Override
6545 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6546 synchronized (mGlobalLock) {
6547 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6548 if (r == null) {
6549 return null;
6550 }
6551 if (r.mServiceConnectionsHolder == null) {
6552 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6553 ActivityTaskManagerService.this, r);
6554 }
6555
6556 return r.mServiceConnectionsHolder;
6557 }
6558 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006559
6560 @Override
6561 public Intent getHomeIntent() {
6562 synchronized (mGlobalLock) {
6563 return ActivityTaskManagerService.this.getHomeIntent();
6564 }
6565 }
6566
6567 @Override
6568 public boolean startHomeActivity(int userId, String reason) {
6569 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006570 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006571 }
6572 }
6573
6574 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006575 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006576 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006577 synchronized (mGlobalLock) {
6578 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006579 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006580 }
Chilun8b1f1be2019-03-13 17:14:36 +08006581 }
6582
6583 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006584 public boolean startHomeOnAllDisplays(int userId, String reason) {
6585 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006586 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006587 }
6588 }
6589
Riddle Hsua0536432019-02-16 00:38:59 +08006590 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006591 @Override
6592 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006593 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006594 if (mFactoryTest == FACTORY_TEST_OFF) {
6595 return false;
6596 }
6597 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6598 && wpc.mName.equals(mTopComponent.getPackageName())) {
6599 return true;
6600 }
6601 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6602 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6603 }
6604 }
6605
6606 @Override
6607 public void updateTopComponentForFactoryTest() {
6608 synchronized (mGlobalLock) {
6609 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6610 return;
6611 }
6612 final ResolveInfo ri = mContext.getPackageManager()
6613 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6614 final CharSequence errorMsg;
6615 if (ri != null) {
6616 final ActivityInfo ai = ri.activityInfo;
6617 final ApplicationInfo app = ai.applicationInfo;
6618 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6619 mTopAction = Intent.ACTION_FACTORY_TEST;
6620 mTopData = null;
6621 mTopComponent = new ComponentName(app.packageName, ai.name);
6622 errorMsg = null;
6623 } else {
6624 errorMsg = mContext.getResources().getText(
6625 com.android.internal.R.string.factorytest_not_system);
6626 }
6627 } else {
6628 errorMsg = mContext.getResources().getText(
6629 com.android.internal.R.string.factorytest_no_action);
6630 }
6631 if (errorMsg == null) {
6632 return;
6633 }
6634
6635 mTopAction = null;
6636 mTopData = null;
6637 mTopComponent = null;
6638 mUiHandler.post(() -> {
6639 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6640 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006641 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006642 });
6643 }
6644 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006645
Riddle Hsua0536432019-02-16 00:38:59 +08006646 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006647 @Override
6648 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6649 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006650 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006651 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006652 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006653
6654 wpc.clearRecentTasks();
6655 wpc.clearActivities();
6656
6657 if (wpc.isInstrumenting()) {
6658 finishInstrumentationCallback.run();
6659 }
6660
Jorim Jaggid0752812018-10-16 16:07:20 +02006661 if (!restarting && hasVisibleActivities) {
6662 mWindowManager.deferSurfaceLayout();
6663 try {
6664 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6665 // If there was nothing to resume, and we are not already restarting
6666 // this process, but there is a visible activity that is hosted by the
6667 // process...then make sure all visible activities are running, taking
6668 // care of restarting this process.
6669 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6670 !PRESERVE_WINDOWS);
6671 }
6672 } finally {
6673 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006674 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006675 }
6676 }
6677 }
6678
6679 @Override
6680 public void closeSystemDialogs(String reason) {
6681 enforceNotIsolatedCaller("closeSystemDialogs");
6682
6683 final int pid = Binder.getCallingPid();
6684 final int uid = Binder.getCallingUid();
6685 final long origId = Binder.clearCallingIdentity();
6686 try {
6687 synchronized (mGlobalLock) {
6688 // Only allow this from foreground processes, so that background
6689 // applications can't abuse it to prevent system UI from being shown.
6690 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006691 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 if (!proc.isPerceptible()) {
6693 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6694 + " from background process " + proc);
6695 return;
6696 }
6697 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006698 mWindowManager.closeSystemDialogs(reason);
6699
Wale Ogunwaled32da472018-11-16 07:19:28 -08006700 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006702 // Call into AM outside the synchronized block.
6703 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006704 } finally {
6705 Binder.restoreCallingIdentity(origId);
6706 }
6707 }
6708
6709 @Override
6710 public void cleanupDisabledPackageComponents(
6711 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6712 synchronized (mGlobalLock) {
6713 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006714 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006715 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006716 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006717 mStackSupervisor.scheduleIdleLocked();
6718 }
6719
6720 // Clean-up disabled tasks
6721 getRecentTasks().cleanupDisabledPackageTasksLocked(
6722 packageName, disabledClasses, userId);
6723 }
6724 }
6725
6726 @Override
6727 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6728 int userId) {
6729 synchronized (mGlobalLock) {
6730
6731 boolean didSomething =
6732 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006733 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 null, doit, evenPersistent, userId);
6735 return didSomething;
6736 }
6737 }
6738
6739 @Override
6740 public void resumeTopActivities(boolean scheduleIdle) {
6741 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006742 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 if (scheduleIdle) {
6744 mStackSupervisor.scheduleIdleLocked();
6745 }
6746 }
6747 }
6748
Riddle Hsua0536432019-02-16 00:38:59 +08006749 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 @Override
6751 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006752 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6754 }
6755 }
6756
Riddle Hsua0536432019-02-16 00:38:59 +08006757 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 @Override
6759 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006760 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006761 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006762 }
6763 }
6764
6765 @Override
6766 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6767 try {
6768 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6769 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6770 }
6771 } catch (RemoteException ex) {
6772 throw new SecurityException("Fail to check is caller a privileged app", ex);
6773 }
6774
6775 synchronized (mGlobalLock) {
6776 final long ident = Binder.clearCallingIdentity();
6777 try {
6778 if (mAmInternal.shouldConfirmCredentials(userId)) {
6779 if (mKeyguardController.isKeyguardLocked()) {
6780 // Showing launcher to avoid user entering credential twice.
6781 startHomeActivity(currentUserId, "notifyLockedProfile");
6782 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006783 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 }
6785 } finally {
6786 Binder.restoreCallingIdentity(ident);
6787 }
6788 }
6789 }
6790
6791 @Override
6792 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6793 mAmInternal.enforceCallingPermission(
6794 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6795
6796 synchronized (mGlobalLock) {
6797 final long ident = Binder.clearCallingIdentity();
6798 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006799 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6800 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6803 UserHandle.CURRENT);
6804 } finally {
6805 Binder.restoreCallingIdentity(ident);
6806 }
6807 }
6808 }
6809
6810 @Override
6811 public void writeActivitiesToProto(ProtoOutputStream proto) {
6812 synchronized (mGlobalLock) {
6813 // The output proto of "activity --proto activities"
6814 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006815 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006816 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6817 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006818 }
6819 }
6820
6821 @Override
6822 public void saveANRState(String reason) {
6823 synchronized (mGlobalLock) {
6824 final StringWriter sw = new StringWriter();
6825 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6826 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6827 if (reason != null) {
6828 pw.println(" Reason: " + reason);
6829 }
6830 pw.println();
6831 getActivityStartController().dump(pw, " ", null);
6832 pw.println();
6833 pw.println("-------------------------------------------------------------------------------");
6834 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6835 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6836 "" /* header */);
6837 pw.println();
6838 pw.close();
6839
6840 mLastANRState = sw.toString();
6841 }
6842 }
6843
6844 @Override
6845 public void clearSavedANRState() {
6846 synchronized (mGlobalLock) {
6847 mLastANRState = null;
6848 }
6849 }
6850
6851 @Override
6852 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6853 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6854 synchronized (mGlobalLock) {
6855 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6856 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6857 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6858 dumpLastANRLocked(pw);
6859 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6860 dumpLastANRTracesLocked(pw);
6861 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6862 dumpActivityStarterLocked(pw, dumpPackage);
6863 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6864 dumpActivityContainersLocked(pw);
6865 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6866 if (getRecentTasks() != null) {
6867 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6868 }
6869 }
6870 }
6871 }
6872
6873 @Override
6874 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6875 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6876 int wakefulness) {
6877 synchronized (mGlobalLock) {
6878 if (mHomeProcess != null && (dumpPackage == null
6879 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6880 if (needSep) {
6881 pw.println();
6882 needSep = false;
6883 }
6884 pw.println(" mHomeProcess: " + mHomeProcess);
6885 }
6886 if (mPreviousProcess != null && (dumpPackage == null
6887 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6888 if (needSep) {
6889 pw.println();
6890 needSep = false;
6891 }
6892 pw.println(" mPreviousProcess: " + mPreviousProcess);
6893 }
6894 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6895 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6896 StringBuilder sb = new StringBuilder(128);
6897 sb.append(" mPreviousProcessVisibleTime: ");
6898 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6899 pw.println(sb);
6900 }
6901 if (mHeavyWeightProcess != null && (dumpPackage == null
6902 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6903 if (needSep) {
6904 pw.println();
6905 needSep = false;
6906 }
6907 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6908 }
6909 if (dumpPackage == null) {
6910 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 }
6913 if (dumpAll) {
6914 if (dumpPackage == null) {
6915 pw.println(" mConfigWillChange: "
6916 + getTopDisplayFocusedStack().mConfigWillChange);
6917 }
6918 if (mCompatModePackages.getPackages().size() > 0) {
6919 boolean printed = false;
6920 for (Map.Entry<String, Integer> entry
6921 : mCompatModePackages.getPackages().entrySet()) {
6922 String pkg = entry.getKey();
6923 int mode = entry.getValue();
6924 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6925 continue;
6926 }
6927 if (!printed) {
6928 pw.println(" mScreenCompatPackages:");
6929 printed = true;
6930 }
6931 pw.println(" " + pkg + ": " + mode);
6932 }
6933 }
6934 }
6935
6936 if (dumpPackage == null) {
6937 pw.println(" mWakefulness="
6938 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006939 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 if (mRunningVoice != null) {
6941 pw.println(" mRunningVoice=" + mRunningVoice);
6942 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6943 }
6944 pw.println(" mSleeping=" + mSleeping);
6945 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6946 pw.println(" mVrController=" + mVrController);
6947 }
6948 if (mCurAppTimeTracker != null) {
6949 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6950 }
6951 if (mAllowAppSwitchUids.size() > 0) {
6952 boolean printed = false;
6953 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6954 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6955 for (int j = 0; j < types.size(); j++) {
6956 if (dumpPackage == null ||
6957 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6958 if (needSep) {
6959 pw.println();
6960 needSep = false;
6961 }
6962 if (!printed) {
6963 pw.println(" mAllowAppSwitchUids:");
6964 printed = true;
6965 }
6966 pw.print(" User ");
6967 pw.print(mAllowAppSwitchUids.keyAt(i));
6968 pw.print(": Type ");
6969 pw.print(types.keyAt(j));
6970 pw.print(" = ");
6971 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6972 pw.println();
6973 }
6974 }
6975 }
6976 }
6977 if (dumpPackage == null) {
6978 if (mController != null) {
6979 pw.println(" mController=" + mController
6980 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6981 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006982 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6983 pw.println(" mLaunchingActivityWakeLock="
6984 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006985 }
6986
6987 return needSep;
6988 }
6989 }
6990
6991 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006992 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6993 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 synchronized (mGlobalLock) {
6995 if (dumpPackage == null) {
6996 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6997 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006998 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6999 if (mRunningVoice != null) {
7000 final long vrToken = proto.start(
7001 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7002 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7003 mRunningVoice.toString());
7004 mVoiceWakeLock.writeToProto(
7005 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7006 proto.end(vrToken);
7007 }
7008 mVrController.writeToProto(proto,
7009 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007010 if (mController != null) {
7011 final long token = proto.start(CONTROLLER);
7012 proto.write(CONTROLLER, mController.toString());
7013 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7014 proto.end(token);
7015 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007016 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7017 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7018 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007019 }
7020
7021 if (mHomeProcess != null && (dumpPackage == null
7022 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007023 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007024 }
7025
7026 if (mPreviousProcess != null && (dumpPackage == null
7027 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007028 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007029 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7030 }
7031
7032 if (mHeavyWeightProcess != null && (dumpPackage == null
7033 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007034 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007035 }
7036
7037 for (Map.Entry<String, Integer> entry
7038 : mCompatModePackages.getPackages().entrySet()) {
7039 String pkg = entry.getKey();
7040 int mode = entry.getValue();
7041 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7042 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7043 proto.write(PACKAGE, pkg);
7044 proto.write(MODE, mode);
7045 proto.end(compatToken);
7046 }
7047 }
7048
7049 if (mCurAppTimeTracker != null) {
7050 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7051 }
7052
7053 }
7054 }
7055
7056 @Override
7057 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7058 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7059 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007060 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7061 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007062 }
7063
7064 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007065 public void dumpForOom(PrintWriter pw) {
7066 synchronized (mGlobalLock) {
7067 pw.println(" mHomeProcess: " + mHomeProcess);
7068 pw.println(" mPreviousProcess: " + mPreviousProcess);
7069 if (mHeavyWeightProcess != null) {
7070 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7071 }
7072 }
7073 }
7074
7075 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 public boolean canGcNow() {
7077 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007078 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 }
7080 }
7081
Riddle Hsua0536432019-02-16 00:38:59 +08007082 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 @Override
7084 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007085 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007086 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 return top != null ? top.app : null;
7088 }
7089 }
7090
Riddle Hsua0536432019-02-16 00:38:59 +08007091 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 @Override
7093 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007094 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007095 if (mRootActivityContainer != null) {
7096 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007097 }
7098 }
7099 }
7100
7101 @Override
7102 public void scheduleDestroyAllActivities(String reason) {
7103 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007104 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 }
7106 }
7107
7108 @Override
7109 public void removeUser(int userId) {
7110 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007111 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 }
7113 }
7114
7115 @Override
7116 public boolean switchUser(int userId, UserState userState) {
7117 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007118 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120 }
7121
7122 @Override
7123 public void onHandleAppCrash(WindowProcessController wpc) {
7124 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007125 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 }
7127 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007128
7129 @Override
7130 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7131 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007132 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007133 }
7134 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007135
Riddle Hsua0536432019-02-16 00:38:59 +08007136 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007137 @Override
7138 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007139 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007140 }
7141
Riddle Hsua0536432019-02-16 00:38:59 +08007142 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007143 @Override
7144 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007145 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007146 }
7147
Riddle Hsua0536432019-02-16 00:38:59 +08007148 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007149 @Override
7150 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007151 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152 }
7153
Riddle Hsua0536432019-02-16 00:38:59 +08007154 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007155 @Override
7156 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007157 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007158 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007159
7160 @Override
7161 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007162 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007163 mPendingTempWhitelist.put(uid, tag);
7164 }
7165 }
7166
7167 @Override
7168 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007169 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007170 mPendingTempWhitelist.remove(uid);
7171 }
7172 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007173
7174 @Override
7175 public boolean handleAppCrashInActivityController(String processName, int pid,
7176 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7177 Runnable killCrashingAppCallback) {
7178 synchronized (mGlobalLock) {
7179 if (mController == null) {
7180 return false;
7181 }
7182
7183 try {
7184 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7185 stackTrace)) {
7186 killCrashingAppCallback.run();
7187 return true;
7188 }
7189 } catch (RemoteException e) {
7190 mController = null;
7191 Watchdog.getInstance().setActivityController(null);
7192 }
7193 return false;
7194 }
7195 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007196
7197 @Override
7198 public void removeRecentTasksByPackageName(String packageName, int userId) {
7199 synchronized (mGlobalLock) {
7200 mRecentTasks.removeTasksByPackageName(packageName, userId);
7201 }
7202 }
7203
7204 @Override
7205 public void cleanupRecentTasksForUser(int userId) {
7206 synchronized (mGlobalLock) {
7207 mRecentTasks.cleanupLocked(userId);
7208 }
7209 }
7210
7211 @Override
7212 public void loadRecentTasksForUser(int userId) {
7213 synchronized (mGlobalLock) {
7214 mRecentTasks.loadUserRecentsLocked(userId);
7215 }
7216 }
7217
7218 @Override
7219 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7220 synchronized (mGlobalLock) {
7221 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7222 }
7223 }
7224
7225 @Override
7226 public void flushRecentTasks() {
7227 mRecentTasks.flush();
7228 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007229
7230 @Override
7231 public WindowProcessController getHomeProcess() {
7232 synchronized (mGlobalLock) {
7233 return mHomeProcess;
7234 }
7235 }
7236
7237 @Override
7238 public WindowProcessController getPreviousProcess() {
7239 synchronized (mGlobalLock) {
7240 return mPreviousProcess;
7241 }
7242 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007243
7244 @Override
7245 public void clearLockedTasks(String reason) {
7246 synchronized (mGlobalLock) {
7247 getLockTaskController().clearLockedTasks(reason);
7248 }
7249 }
7250
7251 @Override
7252 public void updateUserConfiguration() {
7253 synchronized (mGlobalLock) {
7254 final Configuration configuration = new Configuration(getGlobalConfiguration());
7255 final int currentUserId = mAmInternal.getCurrentUserId();
7256 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7257 configuration, currentUserId, Settings.System.canWrite(mContext));
7258 updateConfigurationLocked(configuration, null /* starting */,
7259 false /* initLocale */, false /* persistent */, currentUserId,
7260 false /* deferResume */);
7261 }
7262 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007263
7264 @Override
7265 public boolean canShowErrorDialogs() {
7266 synchronized (mGlobalLock) {
7267 return mShowDialogs && !mSleeping && !mShuttingDown
7268 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7269 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7270 mAmInternal.getCurrentUserId())
7271 && !(UserManager.isDeviceInDemoMode(mContext)
7272 && mAmInternal.getCurrentUser().isDemo());
7273 }
7274 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007275
7276 @Override
7277 public void setProfileApp(String profileApp) {
7278 synchronized (mGlobalLock) {
7279 mProfileApp = profileApp;
7280 }
7281 }
7282
7283 @Override
7284 public void setProfileProc(WindowProcessController wpc) {
7285 synchronized (mGlobalLock) {
7286 mProfileProc = wpc;
7287 }
7288 }
7289
7290 @Override
7291 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7292 synchronized (mGlobalLock) {
7293 mProfilerInfo = profilerInfo;
7294 }
7295 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007296
7297 @Override
7298 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7299 synchronized (mGlobalLock) {
7300 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7301 }
7302 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007303
7304 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007305 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7306 boolean reducedResolution) {
7307 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7308 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007309 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007310
7311 @Override
7312 public boolean isUidForeground(int uid) {
7313 synchronized (mGlobalLock) {
7314 return ActivityTaskManagerService.this.isUidForeground(uid);
7315 }
7316 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007317
7318 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007319 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007320 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007321 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007322 }
7323 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007324
7325 @Override
7326 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007327 // Translate package names into UIDs
7328 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007329 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007330 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7331 if (uid >= 0) {
7332 result.add(uid);
7333 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007334 }
7335 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007336 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007337 }
7338 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007339 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007340}