blob: c6daf9088aa52d4a7201cff0d0c09ddf85640bc6 [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
Evan Roskydbe2ce52019-07-18 11:13:17 -07002585 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2586 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002587
2588 final long ident = Binder.clearCallingIdentity();
2589 try {
2590 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002591 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2592 if (stack == null) {
2593 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2594 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002596 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2597 throw new IllegalArgumentException("Stack: " + stackId
2598 + " doesn't support animated resize.");
2599 }
2600 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2601 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 }
2603 } finally {
2604 Binder.restoreCallingIdentity(ident);
2605 }
2606 }
2607
wilsonshih5c4cf522019-01-25 09:03:47 +08002608 @Override
2609 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2610 int animationDuration) {
2611 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2612
2613 final long ident = Binder.clearCallingIdentity();
2614 try {
2615 synchronized (mGlobalLock) {
2616 if (xOffset == 0 && yOffset == 0) {
2617 return;
2618 }
2619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2620 if (stack == null) {
2621 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2622 return;
2623 }
2624 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2625 throw new IllegalArgumentException("Stack: " + stackId
2626 + " doesn't support animated resize.");
2627 }
2628 final Rect destBounds = new Rect();
2629 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002630 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002631 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2632 return;
2633 }
2634 destBounds.offset(xOffset, yOffset);
2635 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2636 animationDuration, false /* fromFullscreen */);
2637 }
2638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 /**
2643 * Moves the specified task to the primary-split-screen stack.
2644 *
2645 * @param taskId Id of task to move.
2646 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2647 * exist already. See
2648 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2649 * and
2650 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2651 * @param toTop If the task and stack should be moved to the top.
2652 * @param animate Whether we should play an animation for the moving the task.
2653 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2654 * stack. Pass {@code null} to use default bounds.
2655 * @param showRecents If the recents activity should be shown on the other side of the task
2656 * going into split-screen mode.
2657 */
2658 @Override
2659 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2660 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002661 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002662 "setTaskWindowingModeSplitScreenPrimary()");
2663 synchronized (mGlobalLock) {
2664 final long ident = Binder.clearCallingIdentity();
2665 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002666 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002667 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 if (task == null) {
2669 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2670 return false;
2671 }
2672 if (DEBUG_STACK) Slog.d(TAG_STACK,
2673 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2674 + " to createMode=" + createMode + " toTop=" + toTop);
2675 if (!task.isActivityTypeStandardOrUndefined()) {
2676 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2677 + " non-standard task " + taskId + " to split-screen windowing mode");
2678 }
2679
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002680 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002681 final int windowingMode = task.getWindowingMode();
2682 final ActivityStack stack = task.getStack();
2683 if (toTop) {
2684 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2685 }
2686 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002687 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2688 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 return windowingMode != task.getWindowingMode();
2690 } finally {
2691 Binder.restoreCallingIdentity(ident);
2692 }
2693 }
2694 }
2695
2696 /**
2697 * Removes stacks in the input windowing modes from the system if they are of activity type
2698 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2699 */
2700 @Override
2701 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002702 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 "removeStacksInWindowingModes()");
2704
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002708 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713 }
2714
2715 @Override
2716 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 "removeStacksWithActivityTypes()");
2719
2720 synchronized (mGlobalLock) {
2721 final long ident = Binder.clearCallingIdentity();
2722 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729
2730 @Override
2731 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2732 int userId) {
2733 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2735 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 final boolean detailed = checkGetTasksPermission(
2738 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2739 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 == PackageManager.PERMISSION_GRANTED;
2741
2742 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002743 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 callingUid);
2745 }
2746 }
2747
2748 @Override
2749 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002750 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 long ident = Binder.clearCallingIdentity();
2752 try {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002754 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 } finally {
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760
2761 @Override
2762 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002763 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 long ident = Binder.clearCallingIdentity();
2765 try {
2766 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002767 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 }
2769 } finally {
2770 Binder.restoreCallingIdentity(ident);
2771 }
2772 }
2773
2774 @Override
2775 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 final long callingUid = Binder.getCallingUid();
2778 final long origId = Binder.clearCallingIdentity();
2779 try {
2780 synchronized (mGlobalLock) {
2781 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002782 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2784 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2785 }
2786 } finally {
2787 Binder.restoreCallingIdentity(origId);
2788 }
2789 }
2790
2791 @Override
2792 public void startLockTaskModeByToken(IBinder token) {
2793 synchronized (mGlobalLock) {
2794 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2795 if (r == null) {
2796 return;
2797 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002798 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800 }
2801
2802 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002803 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 // This makes inner call to look as if it was initiated by system.
2806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002809 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002810 MATCH_TASK_IN_STACKS_ONLY);
2811 if (task == null) {
2812 return;
2813 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814
2815 // When starting lock task mode the stack must be in front and focused
2816 task.getStack().moveToFront("startSystemLockTaskMode");
2817 startLockTaskModeLocked(task, true /* isSystemCaller */);
2818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
2825 public void stopLockTaskModeByToken(IBinder token) {
2826 synchronized (mGlobalLock) {
2827 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2828 if (r == null) {
2829 return;
2830 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002831 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 }
2833 }
2834
2835 /**
2836 * This API should be called by SystemUI only when user perform certain action to dismiss
2837 * lock task mode. We should only dismiss pinned lock task mode in this case.
2838 */
2839 @Override
2840 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2843 }
2844
2845 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2846 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2847 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2848 return;
2849 }
2850
Wale Ogunwaled32da472018-11-16 07:19:28 -08002851 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 if (stack == null || task != stack.topTask()) {
2853 throw new IllegalArgumentException("Invalid task, not in foreground");
2854 }
2855
2856 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2857 // system or a specific app.
2858 // * System-initiated requests will only start the pinned mode (screen pinning)
2859 // * App-initiated requests
2860 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2861 // - will start the pinned mode, otherwise
2862 final int callingUid = Binder.getCallingUid();
2863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002866 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002868 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 } finally {
2870 Binder.restoreCallingIdentity(ident);
2871 }
2872 }
2873
2874 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2875 final int callingUid = Binder.getCallingUid();
2876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002879 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2882 // task and jumping straight into a call in the case of emergency call back.
2883 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2884 if (tm != null) {
2885 tm.showInCallScreen(false);
2886 }
2887 } finally {
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891
2892 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002893 public void updateLockTaskPackages(int userId, String[] packages) {
2894 final int callingUid = Binder.getCallingUid();
2895 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2896 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2897 "updateLockTaskPackages()");
2898 }
2899 synchronized (this) {
2900 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2901 + Arrays.toString(packages));
2902 getLockTaskController().updateLockTaskPackages(userId, packages);
2903 }
2904 }
2905
2906 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 public boolean isInLockTaskMode() {
2908 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2909 }
2910
2911 @Override
2912 public int getLockTaskModeState() {
2913 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002914 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 }
2916 }
2917
2918 @Override
2919 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2920 synchronized (mGlobalLock) {
2921 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2922 if (r != null) {
2923 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002926 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929 }
2930
2931 @Override
2932 public Bundle getActivityOptions(IBinder token) {
2933 final long origId = Binder.clearCallingIdentity();
2934 try {
2935 synchronized (mGlobalLock) {
2936 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2937 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002938 final ActivityOptions activityOptions = r.takeOptionsLocked(
2939 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 return activityOptions == null ? null : activityOptions.toBundle();
2941 }
2942 return null;
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(origId);
2946 }
2947 }
2948
2949 @Override
2950 public List<IBinder> getAppTasks(String callingPackage) {
2951 int callingUid = Binder.getCallingUid();
2952 long ident = Binder.clearCallingIdentity();
2953 try {
2954 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002955 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
2963 public void finishVoiceTask(IVoiceInteractionSession session) {
2964 synchronized (mGlobalLock) {
2965 final long origId = Binder.clearCallingIdentity();
2966 try {
2967 // TODO: VI Consider treating local voice interactions and voice tasks
2968 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002969 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 } finally {
2971 Binder.restoreCallingIdentity(origId);
2972 }
2973 }
2974
2975 }
2976
2977 @Override
2978 public boolean isTopOfTask(IBinder token) {
2979 synchronized (mGlobalLock) {
2980 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002981 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 }
2983 }
2984
2985 @Override
2986 public void notifyLaunchTaskBehindComplete(IBinder token) {
2987 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2988 }
2989
2990 @Override
2991 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002992 mH.post(() -> {
2993 synchronized (mGlobalLock) {
2994 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002995 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002996 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002997 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002998 } catch (RemoteException e) {
2999 }
3000 }
3001 }
3002
3003 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005
3006 /** Called from an app when assist data is ready. */
3007 @Override
3008 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3009 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 synchronized (pae) {
3012 pae.result = extras;
3013 pae.structure = structure;
3014 pae.content = content;
3015 if (referrer != null) {
3016 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3017 }
3018 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003019 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3021 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 structure.setHomeActivity(pae.isHome);
3023 }
3024 pae.haveResult = true;
3025 pae.notifyAll();
3026 if (pae.intent == null && pae.receiver == null) {
3027 // Caller is just waiting for the result.
3028 return;
3029 }
3030 }
3031 // We are now ready to launch the assist activity.
3032 IAssistDataReceiver sendReceiver = null;
3033 Bundle sendBundle = null;
3034 synchronized (mGlobalLock) {
3035 buildAssistBundleLocked(pae, extras);
3036 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003037 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 if (!exists) {
3039 // Timed out.
3040 return;
3041 }
3042
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 // Caller wants result sent back to them.
3045 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003046 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3047 pae.activity.getTaskRecord().taskId);
3048 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3049 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3051 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3052 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3053 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3054 }
3055 }
3056 if (sendReceiver != null) {
3057 try {
3058 sendReceiver.onHandleAssistData(sendBundle);
3059 } catch (RemoteException e) {
3060 }
3061 return;
3062 }
3063
3064 final long ident = Binder.clearCallingIdentity();
3065 try {
3066 if (TextUtils.equals(pae.intent.getAction(),
3067 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003068 // Start voice interaction through VoiceInteractionManagerService.
3069 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3070 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 } else {
3072 pae.intent.replaceExtras(pae.extras);
3073 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3074 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3075 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003076 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077
3078 try {
3079 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3080 } catch (ActivityNotFoundException e) {
3081 Slog.w(TAG, "No activity to handle assist action.", e);
3082 }
3083 }
3084 } finally {
3085 Binder.restoreCallingIdentity(ident);
3086 }
3087 }
3088
3089 @Override
3090 public int addAppTask(IBinder activityToken, Intent intent,
3091 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3092 final int callingUid = Binder.getCallingUid();
3093 final long callingIdent = Binder.clearCallingIdentity();
3094
3095 try {
3096 synchronized (mGlobalLock) {
3097 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3098 if (r == null) {
3099 throw new IllegalArgumentException("Activity does not exist; token="
3100 + activityToken);
3101 }
3102 ComponentName comp = intent.getComponent();
3103 if (comp == null) {
3104 throw new IllegalArgumentException("Intent " + intent
3105 + " must specify explicit component");
3106 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003107 if (thumbnail.getWidth() != mThumbnailWidth
3108 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 throw new IllegalArgumentException("Bad thumbnail size: got "
3110 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003111 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 }
3113 if (intent.getSelector() != null) {
3114 intent.setSelector(null);
3115 }
3116 if (intent.getSourceBounds() != null) {
3117 intent.setSourceBounds(null);
3118 }
3119 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3120 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3121 // The caller has added this as an auto-remove task... that makes no
3122 // sense, so turn off auto-remove.
3123 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3124 }
3125 }
3126 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3127 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3128 if (ainfo.applicationInfo.uid != callingUid) {
3129 throw new SecurityException(
3130 "Can't add task for another application: target uid="
3131 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3132 }
3133
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003134 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003136 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003138 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 // The app has too many tasks already and we can't add any more
3140 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3141 return INVALID_TASK_ID;
3142 }
3143 task.lastTaskDescription.copyFrom(description);
3144
3145 // TODO: Send the thumbnail to WM to store it.
3146
3147 return task.taskId;
3148 }
3149 } finally {
3150 Binder.restoreCallingIdentity(callingIdent);
3151 }
3152 }
3153
3154 @Override
3155 public Point getAppTaskThumbnailSize() {
3156 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003157 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 }
3159 }
3160
3161 @Override
3162 public void setTaskResizeable(int taskId, int resizeableMode) {
3163 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003164 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3166 if (task == null) {
3167 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3168 return;
3169 }
3170 task.setResizeMode(resizeableMode);
3171 }
3172 }
3173
3174 @Override
3175 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 long ident = Binder.clearCallingIdentity();
3178 try {
3179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003180 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003181 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 if (task == null) {
3183 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3184 return;
3185 }
3186 // Place the task in the right stack if it isn't there already based on
3187 // the requested bounds.
3188 // The stack transition logic is:
3189 // - a null bounds on a freeform task moves that task to fullscreen
3190 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3191 // that task to freeform
3192 // - otherwise the task is not moved
3193 ActivityStack stack = task.getStack();
3194 if (!task.getWindowConfiguration().canResizeTask()) {
3195 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3196 }
3197 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3198 stack = stack.getDisplay().getOrCreateStack(
3199 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3200 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3201 stack = stack.getDisplay().getOrCreateStack(
3202 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3203 }
3204
3205 // Reparent the task to the right stack if necessary
3206 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3207 if (stack != task.getStack()) {
3208 // Defer resume until the task is resized below
3209 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3210 DEFER_RESUME, "resizeTask");
3211 preserveWindow = false;
3212 }
3213
3214 // After reparenting (which only resizes the task to the stack bounds), resize the
3215 // task to the actual bounds provided
3216 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3217 }
3218 } finally {
3219 Binder.restoreCallingIdentity(ident);
3220 }
3221 }
3222
3223 @Override
3224 public boolean releaseActivityInstance(IBinder token) {
3225 synchronized (mGlobalLock) {
3226 final long origId = Binder.clearCallingIdentity();
3227 try {
3228 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3229 if (r == null) {
3230 return false;
3231 }
Andrii Kulian79d67982019-08-19 11:56:16 -07003232 return r.safelyDestroy("app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 } finally {
3234 Binder.restoreCallingIdentity(origId);
3235 }
3236 }
3237 }
3238
3239 @Override
3240 public void releaseSomeActivities(IApplicationThread appInt) {
3241 synchronized (mGlobalLock) {
3242 final long origId = Binder.clearCallingIdentity();
3243 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003244 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003245 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 } finally {
3247 Binder.restoreCallingIdentity(origId);
3248 }
3249 }
3250 }
3251
3252 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003253 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003254 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 != PackageManager.PERMISSION_GRANTED) {
3256 throw new SecurityException("Requires permission "
3257 + android.Manifest.permission.DEVICE_POWER);
3258 }
3259
3260 synchronized (mGlobalLock) {
3261 long ident = Binder.clearCallingIdentity();
3262 if (mKeyguardShown != keyguardShowing) {
3263 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003264 final Message msg = PooledLambda.obtainMessage(
3265 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3266 keyguardShowing);
3267 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 }
3269 try {
wilsonshih177261f2019-02-22 12:02:18 +08003270 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 } finally {
3272 Binder.restoreCallingIdentity(ident);
3273 }
3274 }
3275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003276 mH.post(() -> {
3277 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3278 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3279 }
3280 });
3281 }
3282
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003283 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003284 mH.post(() -> {
3285 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3286 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3287 }
3288 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 }
3290
3291 @Override
3292 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003293 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3294 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295
3296 final File passedIconFile = new File(filePath);
3297 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3298 passedIconFile.getName());
3299 if (!legitIconFile.getPath().equals(filePath)
3300 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3301 throw new IllegalArgumentException("Bad file path: " + filePath
3302 + " passed for userId " + userId);
3303 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003304 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 }
3306
3307 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003308 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3310 final ActivityOptions activityOptions = safeOptions != null
3311 ? safeOptions.getOptions(mStackSupervisor)
3312 : null;
3313 if (activityOptions == null
3314 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3315 || activityOptions.getCustomInPlaceResId() == 0) {
3316 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3317 "with valid animation");
3318 }
lumark588a3e82018-07-20 18:53:54 +08003319 // Get top display of front most application.
3320 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3321 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003322 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3323 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3324 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003325 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003326 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003327 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 }
3329
3330 @Override
3331 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003332 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 synchronized (mGlobalLock) {
3334 final long ident = Binder.clearCallingIdentity();
3335 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003336 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 if (stack == null) {
3338 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3339 return;
3340 }
3341 if (!stack.isActivityTypeStandardOrUndefined()) {
3342 throw new IllegalArgumentException(
3343 "Removing non-standard stack is not allowed.");
3344 }
3345 mStackSupervisor.removeStack(stack);
3346 } finally {
3347 Binder.restoreCallingIdentity(ident);
3348 }
3349 }
3350 }
3351
3352 @Override
3353 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003354 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355
3356 synchronized (mGlobalLock) {
3357 final long ident = Binder.clearCallingIdentity();
3358 try {
3359 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3360 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003361 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 } finally {
3363 Binder.restoreCallingIdentity(ident);
3364 }
3365 }
3366 }
3367
3368 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003369 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 synchronized (mGlobalLock) {
3371 long ident = Binder.clearCallingIdentity();
3372 try {
3373 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3374 if (r == null) {
3375 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003376 "toggleFreeformWindowingMode: No activity record matching token="
3377 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 }
3379
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003380 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003381 if (stack == null) {
3382 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3383 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 }
3385
Yunfan Chend967af82019-01-17 18:30:18 +09003386 if (!stack.inFreeformWindowingMode()
3387 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3388 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3389 + "toggle between fullscreen and freeform.");
3390 }
3391
3392 if (stack.inFreeformWindowingMode()) {
3393 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003394 } else if (stack.getParent().inFreeformWindowingMode()) {
3395 // If the window is on a freeform display, set it to undefined. It will be
3396 // resolved to freeform and it can adjust windowing mode when the display mode
3397 // changes in runtime.
3398 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003399 } else {
3400 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3401 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 } finally {
3403 Binder.restoreCallingIdentity(ident);
3404 }
3405 }
3406 }
3407
3408 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3409 @Override
3410 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003411 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003413 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 }
3415
3416 /** Unregister a task stack listener so that it stops receiving callbacks. */
3417 @Override
3418 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003421 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 @Override
3425 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3426 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3427 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3428 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3429 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3430 }
3431
3432 @Override
3433 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3434 IBinder activityToken, int flags) {
3435 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3436 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3437 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3438 }
3439
3440 @Override
3441 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3442 Bundle args) {
3443 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3444 true /* focused */, true /* newSessionId */, userHandle, args,
3445 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3446 }
3447
3448 @Override
3449 public Bundle getAssistContextExtras(int requestType) {
3450 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3451 null, null, true /* focused */, true /* newSessionId */,
3452 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3453 if (pae == null) {
3454 return null;
3455 }
3456 synchronized (pae) {
3457 while (!pae.haveResult) {
3458 try {
3459 pae.wait();
3460 } catch (InterruptedException e) {
3461 }
3462 }
3463 }
3464 synchronized (mGlobalLock) {
3465 buildAssistBundleLocked(pae, pae.result);
3466 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003467 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 }
3469 return pae.extras;
3470 }
3471
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003472 /**
3473 * Binder IPC calls go through the public entry point.
3474 * This can be called with or without the global lock held.
3475 */
3476 private static int checkCallingPermission(String permission) {
3477 return checkPermission(
3478 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3479 }
3480
3481 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003482 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003483 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3484 mAmInternal.enforceCallingPermission(permission, func);
3485 }
3486 }
3487
3488 @VisibleForTesting
3489 int checkGetTasksPermission(String permission, int pid, int uid) {
3490 return checkPermission(permission, pid, uid);
3491 }
3492
3493 static int checkPermission(String permission, int pid, int uid) {
3494 if (permission == null) {
3495 return PackageManager.PERMISSION_DENIED;
3496 }
3497 return checkComponentPermission(permission, pid, uid, -1, true);
3498 }
3499
Wale Ogunwale214f3482018-10-04 11:00:47 -07003500 public static int checkComponentPermission(String permission, int pid, int uid,
3501 int owningUid, boolean exported) {
3502 return ActivityManagerService.checkComponentPermission(
3503 permission, pid, uid, owningUid, exported);
3504 }
3505
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3507 if (getRecentTasks().isCallerRecents(callingUid)) {
3508 // Always allow the recents component to get tasks
3509 return true;
3510 }
3511
3512 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3513 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3514 if (!allowed) {
3515 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3516 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3517 // Temporary compatibility: some existing apps on the system image may
3518 // still be requesting the old permission and not switched to the new
3519 // one; if so, we'll still allow them full access. This means we need
3520 // to see if they are holding the old permission and are a system app.
3521 try {
3522 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3523 allowed = true;
3524 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3525 + " is using old GET_TASKS but privileged; allowing");
3526 }
3527 } catch (RemoteException e) {
3528 }
3529 }
3530 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3531 + " does not hold REAL_GET_TASKS; limiting output");
3532 }
3533 return allowed;
3534 }
3535
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3537 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3538 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3539 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003540 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003541 "enqueueAssistContext()");
3542
3543 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003544 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 if (activity == null) {
3546 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3547 return null;
3548 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003549 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3551 return null;
3552 }
3553 if (focused) {
3554 if (activityToken != null) {
3555 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3556 if (activity != caller) {
3557 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3558 + " is not current top " + activity);
3559 return null;
3560 }
3561 }
3562 } else {
3563 activity = ActivityRecord.forTokenLocked(activityToken);
3564 if (activity == null) {
3565 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3566 + " couldn't be found");
3567 return null;
3568 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003569 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3571 return null;
3572 }
3573 }
3574
3575 PendingAssistExtras pae;
3576 Bundle extras = new Bundle();
3577 if (args != null) {
3578 extras.putAll(args);
3579 }
3580 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003581 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003582
3583 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3584 userHandle);
3585 pae.isHome = activity.isActivityTypeHome();
3586
3587 // Increment the sessionId if necessary
3588 if (newSessionId) {
3589 mViSessionId++;
3590 }
3591 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003592 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3593 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003595 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 } catch (RemoteException e) {
3597 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3598 return null;
3599 }
3600 return pae;
3601 }
3602 }
3603
3604 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3605 if (result != null) {
3606 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3607 }
3608 if (pae.hint != null) {
3609 pae.extras.putBoolean(pae.hint, true);
3610 }
3611 }
3612
3613 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3614 IAssistDataReceiver receiver;
3615 synchronized (mGlobalLock) {
3616 mPendingAssistExtras.remove(pae);
3617 receiver = pae.receiver;
3618 }
3619 if (receiver != null) {
3620 // Caller wants result sent back to them.
3621 Bundle sendBundle = new Bundle();
3622 // At least return the receiver extras
3623 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3624 try {
3625 pae.receiver.onHandleAssistData(sendBundle);
3626 } catch (RemoteException e) {
3627 }
3628 }
3629 }
3630
3631 public class PendingAssistExtras extends Binder implements Runnable {
3632 public final ActivityRecord activity;
3633 public boolean isHome;
3634 public final Bundle extras;
3635 public final Intent intent;
3636 public final String hint;
3637 public final IAssistDataReceiver receiver;
3638 public final int userHandle;
3639 public boolean haveResult = false;
3640 public Bundle result = null;
3641 public AssistStructure structure = null;
3642 public AssistContent content = null;
3643 public Bundle receiverExtras;
3644
3645 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3646 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3647 int _userHandle) {
3648 activity = _activity;
3649 extras = _extras;
3650 intent = _intent;
3651 hint = _hint;
3652 receiver = _receiver;
3653 receiverExtras = _receiverExtras;
3654 userHandle = _userHandle;
3655 }
3656
3657 @Override
3658 public void run() {
3659 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3660 synchronized (this) {
3661 haveResult = true;
3662 notifyAll();
3663 }
3664 pendingAssistExtrasTimedOut(this);
3665 }
3666 }
3667
3668 @Override
3669 public boolean isAssistDataAllowedOnCurrentActivity() {
3670 int userId;
3671 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003672 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003673 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3674 return false;
3675 }
3676
3677 final ActivityRecord activity = focusedStack.getTopActivity();
3678 if (activity == null) {
3679 return false;
3680 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003681 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682 }
3683 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3684 }
3685
3686 @Override
3687 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3688 long ident = Binder.clearCallingIdentity();
3689 try {
3690 synchronized (mGlobalLock) {
3691 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003692 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 if (top != caller) {
3694 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3695 + " is not current top " + top);
3696 return false;
3697 }
3698 if (!top.nowVisible) {
3699 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3700 + " is not visible");
3701 return false;
3702 }
3703 }
3704 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3705 token);
3706 } finally {
3707 Binder.restoreCallingIdentity(ident);
3708 }
3709 }
3710
3711 @Override
3712 public boolean isRootVoiceInteraction(IBinder token) {
3713 synchronized (mGlobalLock) {
3714 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3715 if (r == null) {
3716 return false;
3717 }
3718 return r.rootVoiceInteraction;
3719 }
3720 }
3721
Wale Ogunwalef6733932018-06-27 05:14:34 -07003722 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3723 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3724 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3725 if (activityToCallback == null) return;
3726 activityToCallback.setVoiceSessionLocked(voiceSession);
3727
3728 // Inform the activity
3729 try {
3730 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3731 voiceInteractor);
3732 long token = Binder.clearCallingIdentity();
3733 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003734 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003735 } finally {
3736 Binder.restoreCallingIdentity(token);
3737 }
3738 // TODO: VI Should we cache the activity so that it's easier to find later
3739 // rather than scan through all the stacks and activities?
3740 } catch (RemoteException re) {
3741 activityToCallback.clearVoiceSessionLocked();
3742 // TODO: VI Should this terminate the voice session?
3743 }
3744 }
3745
3746 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3747 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3748 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3749 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3750 boolean wasRunningVoice = mRunningVoice != null;
3751 mRunningVoice = session;
3752 if (!wasRunningVoice) {
3753 mVoiceWakeLock.acquire();
3754 updateSleepIfNeededLocked();
3755 }
3756 }
3757 }
3758
3759 void finishRunningVoiceLocked() {
3760 if (mRunningVoice != null) {
3761 mRunningVoice = null;
3762 mVoiceWakeLock.release();
3763 updateSleepIfNeededLocked();
3764 }
3765 }
3766
3767 @Override
3768 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3769 synchronized (mGlobalLock) {
3770 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3771 if (keepAwake) {
3772 mVoiceWakeLock.acquire();
3773 } else {
3774 mVoiceWakeLock.release();
3775 }
3776 }
3777 }
3778 }
3779
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003780 @Override
3781 public ComponentName getActivityClassForToken(IBinder token) {
3782 synchronized (mGlobalLock) {
3783 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3784 if (r == null) {
3785 return null;
3786 }
3787 return r.intent.getComponent();
3788 }
3789 }
3790
3791 @Override
3792 public String getPackageForToken(IBinder token) {
3793 synchronized (mGlobalLock) {
3794 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3795 if (r == null) {
3796 return null;
3797 }
3798 return r.packageName;
3799 }
3800 }
3801
3802 @Override
3803 public void showLockTaskEscapeMessage(IBinder token) {
3804 synchronized (mGlobalLock) {
3805 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3806 if (r == null) {
3807 return;
3808 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003809 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 }
3811 }
3812
3813 @Override
3814 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003815 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 final long token = Binder.clearCallingIdentity();
3817 try {
3818 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003819 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003820 }
3821 } finally {
3822 Binder.restoreCallingIdentity(token);
3823 }
3824 }
3825
3826 /**
3827 * Try to place task to provided position. The final position might be different depending on
3828 * current user and stacks state. The task will be moved to target stack if it's currently in
3829 * different stack.
3830 */
3831 @Override
3832 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003833 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 synchronized (mGlobalLock) {
3835 long ident = Binder.clearCallingIdentity();
3836 try {
3837 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3838 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003839 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 if (task == null) {
3841 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3842 + taskId);
3843 }
3844
Wale Ogunwaled32da472018-11-16 07:19:28 -08003845 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846
3847 if (stack == null) {
3848 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3849 + stackId);
3850 }
3851 if (!stack.isActivityTypeStandardOrUndefined()) {
3852 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3853 + " the position of task " + taskId + " in/to non-standard stack");
3854 }
3855
3856 // TODO: Have the callers of this API call a separate reparent method if that is
3857 // what they intended to do vs. having this method also do reparenting.
3858 if (task.getStack() == stack) {
3859 // Change position in current stack.
3860 stack.positionChildAt(task, position);
3861 } else {
3862 // Reparent to new stack.
3863 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3864 !DEFER_RESUME, "positionTaskInStack");
3865 }
3866 } finally {
3867 Binder.restoreCallingIdentity(ident);
3868 }
3869 }
3870 }
3871
3872 @Override
3873 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3874 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3875 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003876 + Arrays.toString(horizontalSizeConfiguration) + " "
3877 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 synchronized (mGlobalLock) {
3879 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3880 if (record == null) {
3881 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3882 + "found for: " + token);
3883 }
3884 record.setSizeConfigurations(horizontalSizeConfiguration,
3885 verticalSizeConfigurations, smallestSizeConfigurations);
3886 }
3887 }
3888
3889 /**
3890 * Dismisses split-screen multi-window mode.
3891 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3892 */
3893 @Override
3894 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003895 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3897 final long ident = Binder.clearCallingIdentity();
3898 try {
3899 synchronized (mGlobalLock) {
3900 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003901 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902 if (stack == null) {
3903 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3904 return;
3905 }
3906
3907 if (toTop) {
3908 // Caller wants the current split-screen primary stack to be the top stack after
3909 // it goes fullscreen, so move it to the front.
3910 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003911 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003913 // stack after it goes fullscreen, so we move the focus to the top-most
3914 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3916 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3917 if (otherStack != null) {
3918 otherStack.moveToFront("dismissSplitScreenMode_other");
3919 }
3920 }
3921
Evan Rosky10475742018-09-05 19:02:48 -07003922 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(ident);
3926 }
3927 }
3928
3929 /**
3930 * Dismisses Pip
3931 * @param animate True if the dismissal should be animated.
3932 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3933 * default animation duration should be used.
3934 */
3935 @Override
3936 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003937 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 final long ident = Binder.clearCallingIdentity();
3939 try {
3940 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003941 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003942 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943 if (stack == null) {
3944 Slog.w(TAG, "dismissPip: pinned stack not found.");
3945 return;
3946 }
3947 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3948 throw new IllegalArgumentException("Stack: " + stack
3949 + " doesn't support animated resize.");
3950 }
3951 if (animate) {
3952 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3953 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3954 } else {
3955 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3956 }
3957 }
3958 } finally {
3959 Binder.restoreCallingIdentity(ident);
3960 }
3961 }
3962
3963 @Override
3964 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003965 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 synchronized (mGlobalLock) {
3967 mSuppressResizeConfigChanges = suppress;
3968 }
3969 }
3970
3971 /**
3972 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3973 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3974 * activity and clearing the task at the same time.
3975 */
3976 @Override
3977 // TODO: API should just be about changing windowing modes...
3978 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003979 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 "moveTasksToFullscreenStack()");
3981 synchronized (mGlobalLock) {
3982 final long origId = Binder.clearCallingIdentity();
3983 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003984 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 if (stack != null){
3986 if (!stack.isActivityTypeStandardOrUndefined()) {
3987 throw new IllegalArgumentException(
3988 "You can't move tasks from non-standard stacks.");
3989 }
3990 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3991 }
3992 } finally {
3993 Binder.restoreCallingIdentity(origId);
3994 }
3995 }
3996 }
3997
3998 /**
3999 * Moves the top activity in the input stackId to the pinned stack.
4000 *
4001 * @param stackId Id of stack to move the top activity to pinned stack.
4002 * @param bounds Bounds to use for pinned stack.
4003 *
4004 * @return True if the top activity of the input stack was successfully moved to the pinned
4005 * stack.
4006 */
4007 @Override
4008 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 "moveTopActivityToPinnedStack()");
4011 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4014 + "Device doesn't support picture-in-picture mode");
4015 }
4016
4017 long ident = Binder.clearCallingIdentity();
4018 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004019 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 } finally {
4021 Binder.restoreCallingIdentity(ident);
4022 }
4023 }
4024 }
4025
4026 @Override
4027 public boolean isInMultiWindowMode(IBinder token) {
4028 final long origId = Binder.clearCallingIdentity();
4029 try {
4030 synchronized (mGlobalLock) {
4031 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4032 if (r == null) {
4033 return false;
4034 }
4035 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4036 return r.inMultiWindowMode();
4037 }
4038 } finally {
4039 Binder.restoreCallingIdentity(origId);
4040 }
4041 }
4042
4043 @Override
4044 public boolean isInPictureInPictureMode(IBinder token) {
4045 final long origId = Binder.clearCallingIdentity();
4046 try {
4047 synchronized (mGlobalLock) {
4048 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4049 }
4050 } finally {
4051 Binder.restoreCallingIdentity(origId);
4052 }
4053 }
4054
4055 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004056 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4057 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 return false;
4059 }
4060
4061 // If we are animating to fullscreen then we have already dispatched the PIP mode
4062 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004063 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4064 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 }
4066
4067 @Override
4068 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4069 final long origId = Binder.clearCallingIdentity();
4070 try {
4071 synchronized (mGlobalLock) {
4072 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4073 "enterPictureInPictureMode", token, params);
4074
4075 // If the activity is already in picture in picture mode, then just return early
4076 if (isInPictureInPictureMode(r)) {
4077 return true;
4078 }
4079
4080 // Activity supports picture-in-picture, now check that we can enter PiP at this
4081 // point, if it is
4082 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4083 false /* beforeStopping */)) {
4084 return false;
4085 }
4086
4087 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004088 synchronized (mGlobalLock) {
4089 // Only update the saved args from the args that are set
4090 r.pictureInPictureArgs.copyOnlySet(params);
4091 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4092 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4093 // Adjust the source bounds by the insets for the transition down
4094 final Rect sourceBounds = new Rect(
4095 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004096 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004097 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004098 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004099 stack.setPictureInPictureAspectRatio(aspectRatio);
4100 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004101 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4102 r.info.applicationInfo.uid, r.shortComponentName,
4103 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004104 logPictureInPictureArgs(params);
4105 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004106 };
4107
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004108 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004109 // If the keyguard is showing or occluded, then try and dismiss it before
4110 // entering picture-in-picture (this will prompt the user to authenticate if the
4111 // device is currently locked).
4112 dismissKeyguard(token, new KeyguardDismissCallback() {
4113 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 public void onDismissSucceeded() {
4115 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 }
4117 }, null /* message */);
4118 } else {
4119 // Enter picture in picture immediately otherwise
4120 enterPipRunnable.run();
4121 }
4122 return true;
4123 }
4124 } finally {
4125 Binder.restoreCallingIdentity(origId);
4126 }
4127 }
4128
4129 @Override
4130 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4131 final long origId = Binder.clearCallingIdentity();
4132 try {
4133 synchronized (mGlobalLock) {
4134 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4135 "setPictureInPictureParams", token, params);
4136
4137 // Only update the saved args from the args that are set
4138 r.pictureInPictureArgs.copyOnlySet(params);
4139 if (r.inPinnedWindowingMode()) {
4140 // If the activity is already in picture-in-picture, update the pinned stack now
4141 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4142 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004143 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 if (!stack.isAnimatingBoundsToFullscreen()) {
4145 stack.setPictureInPictureAspectRatio(
4146 r.pictureInPictureArgs.getAspectRatio());
4147 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4148 }
4149 }
4150 logPictureInPictureArgs(params);
4151 }
4152 } finally {
4153 Binder.restoreCallingIdentity(origId);
4154 }
4155 }
4156
4157 @Override
4158 public int getMaxNumPictureInPictureActions(IBinder token) {
4159 // Currently, this is a static constant, but later, we may change this to be dependent on
4160 // the context of the activity
4161 return 3;
4162 }
4163
4164 private void logPictureInPictureArgs(PictureInPictureParams params) {
4165 if (params.hasSetActions()) {
4166 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4167 params.getActions().size());
4168 }
4169 if (params.hasSetAspectRatio()) {
4170 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4171 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4172 MetricsLogger.action(lm);
4173 }
4174 }
4175
4176 /**
4177 * Checks the state of the system and the activity associated with the given {@param token} to
4178 * verify that picture-in-picture is supported for that activity.
4179 *
4180 * @return the activity record for the given {@param token} if all the checks pass.
4181 */
4182 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4183 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004184 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 throw new IllegalStateException(caller
4186 + ": Device doesn't support picture-in-picture mode.");
4187 }
4188
4189 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4190 if (r == null) {
4191 throw new IllegalStateException(caller
4192 + ": Can't find activity for token=" + token);
4193 }
4194
4195 if (!r.supportsPictureInPicture()) {
4196 throw new IllegalStateException(caller
4197 + ": Current activity does not support picture-in-picture.");
4198 }
4199
4200 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004201 && !mWindowManager.isValidPictureInPictureAspectRatio(
4202 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 final float minAspectRatio = mContext.getResources().getFloat(
4204 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4205 final float maxAspectRatio = mContext.getResources().getFloat(
4206 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4207 throw new IllegalArgumentException(String.format(caller
4208 + ": Aspect ratio is too extreme (must be between %f and %f).",
4209 minAspectRatio, maxAspectRatio));
4210 }
4211
4212 // Truncate the number of actions if necessary
4213 params.truncateActions(getMaxNumPictureInPictureActions(token));
4214
4215 return r;
4216 }
4217
4218 @Override
4219 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 synchronized (mGlobalLock) {
4222 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4223 if (r == null) {
4224 throw new IllegalArgumentException("Activity does not exist; token="
4225 + activityToken);
4226 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004227 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 }
4229 }
4230
4231 @Override
4232 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4233 Rect tempDockedTaskInsetBounds,
4234 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 long ident = Binder.clearCallingIdentity();
4237 try {
4238 synchronized (mGlobalLock) {
4239 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4240 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4241 PRESERVE_WINDOWS);
4242 }
4243 } finally {
4244 Binder.restoreCallingIdentity(ident);
4245 }
4246 }
4247
4248 @Override
4249 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 final long ident = Binder.clearCallingIdentity();
4252 try {
4253 synchronized (mGlobalLock) {
4254 mStackSupervisor.setSplitScreenResizing(resizing);
4255 }
4256 } finally {
4257 Binder.restoreCallingIdentity(ident);
4258 }
4259 }
4260
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 /**
4262 * Check that we have the features required for VR-related API calls, and throw an exception if
4263 * not.
4264 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004265 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004266 if (!mContext.getPackageManager().hasSystemFeature(
4267 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4268 throw new UnsupportedOperationException("VR mode not supported on this device!");
4269 }
4270 }
4271
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 @Override
4273 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275
4276 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4277
4278 ActivityRecord r;
4279 synchronized (mGlobalLock) {
4280 r = ActivityRecord.isInStackLocked(token);
4281 }
4282
4283 if (r == null) {
4284 throw new IllegalArgumentException();
4285 }
4286
4287 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004288 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 VrManagerInternal.NO_ERROR) {
4290 return err;
4291 }
4292
4293 // Clear the binder calling uid since this path may call moveToTask().
4294 final long callingId = Binder.clearCallingIdentity();
4295 try {
4296 synchronized (mGlobalLock) {
4297 r.requestedVrComponent = (enabled) ? packageName : null;
4298
4299 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004300 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004301 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 }
4303 return 0;
4304 }
4305 } finally {
4306 Binder.restoreCallingIdentity(callingId);
4307 }
4308 }
4309
4310 @Override
4311 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4312 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4313 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004314 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4316 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4317 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004318 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 || activity.voiceSession != null) {
4320 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4321 return;
4322 }
4323 if (activity.pendingVoiceInteractionStart) {
4324 Slog.w(TAG, "Pending start of voice interaction already.");
4325 return;
4326 }
4327 activity.pendingVoiceInteractionStart = true;
4328 }
4329 LocalServices.getService(VoiceInteractionManagerInternal.class)
4330 .startLocalVoiceInteraction(callingActivity, options);
4331 }
4332
4333 @Override
4334 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4335 LocalServices.getService(VoiceInteractionManagerInternal.class)
4336 .stopLocalVoiceInteraction(callingActivity);
4337 }
4338
4339 @Override
4340 public boolean supportsLocalVoiceInteraction() {
4341 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4342 .supportsLocalVoiceInteraction();
4343 }
4344
4345 /** Notifies all listeners when the pinned stack animation starts. */
4346 @Override
4347 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004348 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 }
4350
4351 /** Notifies all listeners when the pinned stack animation ends. */
4352 @Override
4353 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004354 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 }
4356
4357 @Override
4358 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 final long ident = Binder.clearCallingIdentity();
4361 try {
4362 synchronized (mGlobalLock) {
4363 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4364 }
4365 } finally {
4366 Binder.restoreCallingIdentity(ident);
4367 }
4368 }
4369
4370 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373
4374 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 }
4379
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004381 final Message msg = PooledLambda.obtainMessage(
4382 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4383 DEFAULT_DISPLAY);
4384 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 }
4386
4387 final long origId = Binder.clearCallingIdentity();
4388 try {
4389 if (values != null) {
4390 Settings.System.clearConfiguration(values);
4391 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004392 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 UserHandle.USER_NULL, false /* deferResume */,
4394 mTmpUpdateConfigurationResult);
4395 return mTmpUpdateConfigurationResult.changes != 0;
4396 } finally {
4397 Binder.restoreCallingIdentity(origId);
4398 }
4399 }
4400 }
4401
4402 @Override
4403 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4404 CharSequence message) {
4405 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4408 }
4409 final long callingId = Binder.clearCallingIdentity();
4410 try {
4411 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004412 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
4414 } finally {
4415 Binder.restoreCallingIdentity(callingId);
4416 }
4417 }
4418
4419 @Override
4420 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 "cancelTaskWindowTransition()");
4423 final long ident = Binder.clearCallingIdentity();
4424 try {
4425 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004426 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 MATCH_TASK_IN_STACKS_ONLY);
4428 if (task == null) {
4429 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4430 return;
4431 }
4432 task.cancelWindowTransition();
4433 }
4434 } finally {
4435 Binder.restoreCallingIdentity(ident);
4436 }
4437 }
4438
4439 @Override
4440 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 final long ident = Binder.clearCallingIdentity();
4443 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004444 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 } finally {
4446 Binder.restoreCallingIdentity(ident);
4447 }
4448 }
4449
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004450 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4451 boolean restoreFromDisk) {
4452 final TaskRecord task;
4453 synchronized (mGlobalLock) {
4454 task = mRootActivityContainer.anyTaskForId(taskId,
4455 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4456 if (task == null) {
4457 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4458 return null;
4459 }
4460 }
4461 // Don't call this while holding the lock as this operation might hit the disk.
4462 return task.getSnapshot(reducedResolution, restoreFromDisk);
4463 }
4464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 @Override
4466 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4467 synchronized (mGlobalLock) {
4468 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4469 if (r == null) {
4470 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4471 + token);
4472 return;
4473 }
4474 final long origId = Binder.clearCallingIdentity();
4475 try {
4476 r.setDisablePreviewScreenshots(disable);
4477 } finally {
4478 Binder.restoreCallingIdentity(origId);
4479 }
4480 }
4481 }
4482
4483 /** Return the user id of the last resumed activity. */
4484 @Override
4485 public @UserIdInt
4486 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4489 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004490 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004491 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004493 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 }
4495 }
4496
4497 @Override
4498 public void updateLockTaskFeatures(int userId, int flags) {
4499 final int callingUid = Binder.getCallingUid();
4500 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004501 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 "updateLockTaskFeatures()");
4503 }
4504 synchronized (mGlobalLock) {
4505 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4506 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004507 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 }
4509 }
4510
4511 @Override
4512 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4513 synchronized (mGlobalLock) {
4514 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4515 if (r == null) {
4516 return;
4517 }
4518 final long origId = Binder.clearCallingIdentity();
4519 try {
4520 r.setShowWhenLocked(showWhenLocked);
4521 } finally {
4522 Binder.restoreCallingIdentity(origId);
4523 }
4524 }
4525 }
4526
4527 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004528 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4529 synchronized (mGlobalLock) {
4530 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4531 if (r == null) {
4532 return;
4533 }
4534 final long origId = Binder.clearCallingIdentity();
4535 try {
4536 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4537 } finally {
4538 Binder.restoreCallingIdentity(origId);
4539 }
4540 }
4541 }
4542
4543 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4545 synchronized (mGlobalLock) {
4546 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4547 if (r == null) {
4548 return;
4549 }
4550 final long origId = Binder.clearCallingIdentity();
4551 try {
4552 r.setTurnScreenOn(turnScreenOn);
4553 } finally {
4554 Binder.restoreCallingIdentity(origId);
4555 }
4556 }
4557 }
4558
4559 @Override
4560 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004561 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004562 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004563 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 synchronized (mGlobalLock) {
4565 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4566 if (r == null) {
4567 return;
4568 }
4569 final long origId = Binder.clearCallingIdentity();
4570 try {
4571 r.registerRemoteAnimations(definition);
4572 } finally {
4573 Binder.restoreCallingIdentity(origId);
4574 }
4575 }
4576 }
4577
4578 @Override
4579 public void registerRemoteAnimationForNextActivityStart(String packageName,
4580 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004581 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004583 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004584 synchronized (mGlobalLock) {
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004587 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004588 packageName, adapter);
4589 } finally {
4590 Binder.restoreCallingIdentity(origId);
4591 }
4592 }
4593 }
4594
Evan Rosky966759f2019-01-15 10:33:58 -08004595 @Override
4596 public void registerRemoteAnimationsForDisplay(int displayId,
4597 RemoteAnimationDefinition definition) {
4598 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4599 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004600 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004601 synchronized (mGlobalLock) {
4602 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4603 if (display == null) {
4604 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 display.mDisplayContent.registerRemoteAnimations(definition);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004616 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4617 @Override
4618 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4619 synchronized (mGlobalLock) {
4620 final long origId = Binder.clearCallingIdentity();
4621 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004622 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004628
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004629 @Override
4630 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004631 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004632 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004633 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004634 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004635 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004636 }
4637 }
4638
4639 @Override
4640 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004641 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004642 != PERMISSION_GRANTED) {
4643 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4644 + Binder.getCallingPid()
4645 + ", uid=" + Binder.getCallingUid()
4646 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4647 Slog.w(TAG, msg);
4648 throw new SecurityException(msg);
4649 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004652 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004653 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004654 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004655 }
4656 }
4657
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 @Override
4659 public void stopAppSwitches() {
4660 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4661 synchronized (mGlobalLock) {
4662 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004663 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 mDidAppSwitch = false;
4665 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4666 }
4667 }
4668
4669 @Override
4670 public void resumeAppSwitches() {
4671 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4672 synchronized (mGlobalLock) {
4673 // Note that we don't execute any pending app switches... we will
4674 // let those wait until either the timeout, or the next start
4675 // activity request.
4676 mAppSwitchesAllowedTime = 0;
4677 }
4678 }
4679
Ricky Wai906af482019-06-03 17:25:28 +01004680 long getLastStopAppSwitchesTime() {
4681 return mLastStopAppSwitchesTime;
4682 }
4683
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004684 void onStartActivitySetDidAppSwitch() {
4685 if (mDidAppSwitch) {
4686 // This is the second allowed switch since we stopped switches, so now just generally
4687 // allow switches. Use case:
4688 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4689 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4690 // anyone to switch again).
4691 mAppSwitchesAllowedTime = 0;
4692 } else {
4693 mDidAppSwitch = true;
4694 }
4695 }
4696
4697 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 boolean shouldDisableNonVrUiLocked() {
4699 return mVrController.shouldDisableNonVrUiLocked();
4700 }
4701
Wale Ogunwale53783742018-09-16 10:21:51 -07004702 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004703 // 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 +00004704 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004706 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4707 + " to main display for VR");
4708 mRootActivityContainer.moveStackToDisplay(
4709 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 }
4711 mH.post(() -> {
4712 if (!mVrController.onVrModeChanged(r)) {
4713 return;
4714 }
4715 synchronized (mGlobalLock) {
4716 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4717 mWindowManager.disableNonVrUi(disableNonVrUi);
4718 if (disableNonVrUi) {
4719 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4720 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004721 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 }
4723 }
4724 });
4725 }
4726
Wale Ogunwale53783742018-09-16 10:21:51 -07004727 @Override
4728 public int getPackageScreenCompatMode(String packageName) {
4729 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4730 synchronized (mGlobalLock) {
4731 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4732 }
4733 }
4734
4735 @Override
4736 public void setPackageScreenCompatMode(String packageName, int mode) {
4737 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4738 "setPackageScreenCompatMode");
4739 synchronized (mGlobalLock) {
4740 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4741 }
4742 }
4743
4744 @Override
4745 public boolean getPackageAskScreenCompat(String packageName) {
4746 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4747 synchronized (mGlobalLock) {
4748 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4749 }
4750 }
4751
4752 @Override
4753 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4754 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4755 "setPackageAskScreenCompat");
4756 synchronized (mGlobalLock) {
4757 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4758 }
4759 }
4760
Wale Ogunwale64258362018-10-16 15:13:37 -07004761 public static String relaunchReasonToString(int relaunchReason) {
4762 switch (relaunchReason) {
4763 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4764 return "window_resize";
4765 case RELAUNCH_REASON_FREE_RESIZE:
4766 return "free_resize";
4767 default:
4768 return null;
4769 }
4770 }
4771
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004772 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004773 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004774 }
4775
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004776 /** Pokes the task persister. */
4777 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4778 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4779 }
4780
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 boolean isKeyguardLocked() {
4782 return mKeyguardController.isKeyguardLocked();
4783 }
4784
Garfield Tan01548632018-11-27 10:15:48 -08004785 /**
4786 * Clears launch params for the given package.
4787 * @param packageNames the names of the packages of which the launch params are to be cleared
4788 */
4789 @Override
4790 public void clearLaunchParamsForPackages(List<String> packageNames) {
4791 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4792 "clearLaunchParamsForPackages");
4793 synchronized (mGlobalLock) {
4794 for (int i = 0; i < packageNames.size(); ++i) {
4795 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4796 }
4797 }
4798 }
4799
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004800 /**
4801 * Makes the display with the given id a single task instance display. I.e the display can only
4802 * contain one task.
4803 */
4804 @Override
4805 public void setDisplayToSingleTaskInstance(int displayId) {
4806 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4807 "setDisplayToSingleTaskInstance");
4808 final long origId = Binder.clearCallingIdentity();
4809 try {
4810 final ActivityDisplay display =
4811 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4812 if (display != null) {
4813 display.setDisplayToSingleTaskInstance();
4814 }
4815 } finally {
4816 Binder.restoreCallingIdentity(origId);
4817 }
4818 }
4819
Wale Ogunwale31913b52018-10-13 08:29:31 -07004820 void dumpLastANRLocked(PrintWriter pw) {
4821 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4822 if (mLastANRState == null) {
4823 pw.println(" <no ANR has occurred since boot>");
4824 } else {
4825 pw.println(mLastANRState);
4826 }
4827 }
4828
4829 void dumpLastANRTracesLocked(PrintWriter pw) {
4830 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4831
4832 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4833 if (ArrayUtils.isEmpty(files)) {
4834 pw.println(" <no ANR has occurred since boot>");
4835 return;
4836 }
4837 // Find the latest file.
4838 File latest = null;
4839 for (File f : files) {
4840 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4841 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004842 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004843 }
4844 pw.print("File: ");
4845 pw.print(latest.getName());
4846 pw.println();
4847 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4848 String line;
4849 while ((line = in.readLine()) != null) {
4850 pw.println(line);
4851 }
4852 } catch (IOException e) {
4853 pw.print("Unable to read: ");
4854 pw.print(e);
4855 pw.println();
4856 }
4857 }
4858
4859 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4860 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4861 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4862 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4863 }
4864
4865 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4866 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4867 pw.println(header);
4868
Wale Ogunwaled32da472018-11-16 07:19:28 -08004869 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004870 dumpPackage);
4871 boolean needSep = printedAnything;
4872
4873 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004874 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004875 " ResumedActivity: ");
4876 if (printed) {
4877 printedAnything = true;
4878 needSep = false;
4879 }
4880
4881 if (dumpPackage == null) {
4882 if (needSep) {
4883 pw.println();
4884 }
4885 printedAnything = true;
4886 mStackSupervisor.dump(pw, " ");
4887 }
4888
4889 if (!printedAnything) {
4890 pw.println(" (nothing)");
4891 }
4892 }
4893
4894 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004895 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004896 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004897 pw.println(" ");
4898 }
4899
4900 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4901 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4902 getActivityStartController().dump(pw, "", dumpPackage);
4903 }
4904
4905 /**
4906 * There are three things that cmd can be:
4907 * - a flattened component name that matches an existing activity
4908 * - the cmd arg isn't the flattened component name of an existing activity:
4909 * dump all activity whose component contains the cmd as a substring
4910 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004911 * <p>
4912 * The caller should not hold lock when calling this method because it will wait for the
4913 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004914 *
4915 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4916 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4917 */
4918 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4919 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4920 ArrayList<ActivityRecord> activities;
4921
4922 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004923 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004924 dumpFocusedStackOnly);
4925 }
4926
4927 if (activities.size() <= 0) {
4928 return false;
4929 }
4930
4931 String[] newArgs = new String[args.length - opti];
4932 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4933
4934 TaskRecord lastTask = null;
4935 boolean needSep = false;
4936 for (int i = activities.size() - 1; i >= 0; i--) {
4937 ActivityRecord r = activities.get(i);
4938 if (needSep) {
4939 pw.println();
4940 }
4941 needSep = true;
4942 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004943 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004944 if (lastTask != task) {
4945 lastTask = task;
4946 pw.print("TASK "); pw.print(lastTask.affinity);
4947 pw.print(" id="); pw.print(lastTask.taskId);
4948 pw.print(" userId="); pw.println(lastTask.userId);
4949 if (dumpAll) {
4950 lastTask.dump(pw, " ");
4951 }
4952 }
4953 }
4954 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4955 }
4956 return true;
4957 }
4958
4959 /**
4960 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4961 * there is a thread associated with the activity.
4962 */
4963 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4964 final ActivityRecord r, String[] args, boolean dumpAll) {
4965 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004966 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 synchronized (mGlobalLock) {
4968 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4969 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4970 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004971 if (r.hasProcess()) {
4972 pw.println(r.app.getPid());
4973 appThread = r.app.getThread();
4974 } else {
4975 pw.println("(not running)");
4976 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004977 if (dumpAll) {
4978 r.dump(pw, innerPrefix);
4979 }
4980 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004981 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 // flush anything that is already in the PrintWriter since the thread is going
4983 // to write to the file descriptor directly
4984 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004985 try (TransferPipe tp = new TransferPipe()) {
4986 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4987 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004988 } catch (IOException e) {
4989 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4990 } catch (RemoteException e) {
4991 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4992 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004993 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004994 }
4995
sanryhuang498e77e2018-12-06 14:57:01 +08004996 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4997 boolean testPssMode) {
4998 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4999 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5000 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005001 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005002 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5003 st.toString());
5004 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005005 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5006 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5007 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005008 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5009 testPssMode);
5010 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005011 }
5012
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005013 int getCurrentUserId() {
5014 return mAmInternal.getCurrentUserId();
5015 }
5016
5017 private void enforceNotIsolatedCaller(String caller) {
5018 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5019 throw new SecurityException("Isolated process not allowed to call " + caller);
5020 }
5021 }
5022
Wale Ogunwalef6733932018-06-27 05:14:34 -07005023 public Configuration getConfiguration() {
5024 Configuration ci;
5025 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005026 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005027 ci.userSetLocale = false;
5028 }
5029 return ci;
5030 }
5031
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005032 /**
5033 * Current global configuration information. Contains general settings for the entire system,
5034 * also corresponds to the merged configuration of the default display.
5035 */
5036 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005037 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005038 }
5039
5040 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5041 boolean initLocale) {
5042 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5043 }
5044
5045 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5046 boolean initLocale, boolean deferResume) {
5047 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5048 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5049 UserHandle.USER_NULL, deferResume);
5050 }
5051
Wale Ogunwale59507092018-10-29 09:00:30 -07005052 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005053 final long origId = Binder.clearCallingIdentity();
5054 try {
5055 synchronized (mGlobalLock) {
5056 updateConfigurationLocked(values, null, false, true, userId,
5057 false /* deferResume */);
5058 }
5059 } finally {
5060 Binder.restoreCallingIdentity(origId);
5061 }
5062 }
5063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5065 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5066 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5067 deferResume, null /* result */);
5068 }
5069
5070 /**
5071 * Do either or both things: (1) change the current configuration, and (2)
5072 * make sure the given activity is running with the (now) current
5073 * configuration. Returns true if the activity has been left running, or
5074 * false if <var>starting</var> is being destroyed to match the new
5075 * configuration.
5076 *
5077 * @param userId is only used when persistent parameter is set to true to persist configuration
5078 * for that particular user
5079 */
5080 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5081 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5082 ActivityTaskManagerService.UpdateConfigurationResult result) {
5083 int changes = 0;
5084 boolean kept = true;
5085
5086 if (mWindowManager != null) {
5087 mWindowManager.deferSurfaceLayout();
5088 }
5089 try {
5090 if (values != null) {
5091 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5092 deferResume);
5093 }
5094
5095 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5096 } finally {
5097 if (mWindowManager != null) {
5098 mWindowManager.continueSurfaceLayout();
5099 }
5100 }
5101
5102 if (result != null) {
5103 result.changes = changes;
5104 result.activityRelaunched = !kept;
5105 }
5106 return kept;
5107 }
5108
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005109 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005110 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005112
5113 final ActivityDisplay defaultDisplay =
5114 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 mTempConfig.setTo(getGlobalConfiguration());
5117 final int changes = mTempConfig.updateFrom(values);
5118 if (changes == 0) {
5119 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5120 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5121 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5122 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005123 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 return 0;
5125 }
5126
5127 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5128 "Updating global configuration to: " + values);
5129
5130 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5131 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5132 values.colorMode,
5133 values.densityDpi,
5134 values.fontScale,
5135 values.hardKeyboardHidden,
5136 values.keyboard,
5137 values.keyboardHidden,
5138 values.mcc,
5139 values.mnc,
5140 values.navigation,
5141 values.navigationHidden,
5142 values.orientation,
5143 values.screenHeightDp,
5144 values.screenLayout,
5145 values.screenWidthDp,
5146 values.smallestScreenWidthDp,
5147 values.touchscreen,
5148 values.uiMode);
5149
5150
5151 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5152 final LocaleList locales = values.getLocales();
5153 int bestLocaleIndex = 0;
5154 if (locales.size() > 1) {
5155 if (mSupportedSystemLocales == null) {
5156 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5157 }
5158 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5159 }
5160 SystemProperties.set("persist.sys.locale",
5161 locales.get(bestLocaleIndex).toLanguageTag());
5162 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005163
5164 final Message m = PooledLambda.obtainMessage(
5165 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5166 locales.get(bestLocaleIndex));
5167 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005168 }
5169
Yunfan Chen75157d72018-07-27 14:47:21 +09005170 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171
5172 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005173 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174
5175 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5176 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005177 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178
5179 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005180 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181
5182 AttributeCache ac = AttributeCache.instance();
5183 if (ac != null) {
5184 ac.updateConfiguration(mTempConfig);
5185 }
5186
5187 // Make sure all resources in our process are updated right now, so that anyone who is going
5188 // to retrieve resource values after we return will be sure to get the new ones. This is
5189 // especially important during boot, where the first config change needs to guarantee all
5190 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005191 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005192
5193 // We need another copy of global config because we're scheduling some calls instead of
5194 // running them in place. We need to be sure that object we send will be handled unchanged.
5195 final Configuration configCopy = new Configuration(mTempConfig);
5196 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005197 final Message msg = PooledLambda.obtainMessage(
5198 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5199 this, userId, configCopy);
5200 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201 }
5202
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005203 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5204 for (int i = pidMap.size() - 1; i >= 0; i--) {
5205 final int pid = pidMap.keyAt(i);
5206 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005207 if (DEBUG_CONFIGURATION) {
5208 Slog.v(TAG_CONFIGURATION, "Update process config of "
5209 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005211 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005212 }
5213
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005214 final Message msg = PooledLambda.obtainMessage(
5215 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5216 mAmInternal, changes, initLocale);
5217 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218
5219 // Override configuration of the default display duplicates global config, so we need to
5220 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005221 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5222 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223
5224 return changes;
5225 }
5226
Wale Ogunwalef6733932018-06-27 05:14:34 -07005227 private void updateEventDispatchingLocked(boolean booted) {
5228 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5229 }
5230
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005231 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5232 final ContentResolver resolver = mContext.getContentResolver();
5233 Settings.System.putConfigurationForUser(resolver, config, userId);
5234 }
5235
5236 private void sendLocaleToMountDaemonMsg(Locale l) {
5237 try {
5238 IBinder service = ServiceManager.getService("mount");
5239 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5240 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5241 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5242 } catch (RemoteException e) {
5243 Log.e(TAG, "Error storing locale for decryption UI", e);
5244 }
5245 }
5246
Alison Cichowlas3e340502018-08-07 17:15:01 -04005247 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5248 mStartActivitySources.remove(permissionToken);
5249 mExpiredStartAsCallerTokens.add(permissionToken);
5250 }
5251
5252 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5253 mExpiredStartAsCallerTokens.remove(permissionToken);
5254 }
5255
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005256 boolean isActivityStartsLoggingEnabled() {
5257 return mAmInternal.isActivityStartsLoggingEnabled();
5258 }
5259
Michal Karpinski8596ded2018-11-14 14:43:48 +00005260 boolean isBackgroundActivityStartsEnabled() {
5261 return mAmInternal.isBackgroundActivityStartsEnabled();
5262 }
5263
Wale Ogunwalef6733932018-06-27 05:14:34 -07005264 void enableScreenAfterBoot(boolean booted) {
5265 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5266 SystemClock.uptimeMillis());
5267 mWindowManager.enableScreenAfterBoot();
5268
5269 synchronized (mGlobalLock) {
5270 updateEventDispatchingLocked(booted);
5271 }
5272 }
5273
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005274 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5275 if (r == null || !r.hasProcess()) {
5276 return KEY_DISPATCHING_TIMEOUT_MS;
5277 }
5278 return getInputDispatchingTimeoutLocked(r.app);
5279 }
5280
5281 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005282 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005283 }
5284
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 /**
5286 * Decide based on the configuration whether we should show the ANR,
5287 * crash, etc dialogs. The idea is that if there is no affordance to
5288 * press the on-screen buttons, or the user experience would be more
5289 * greatly impacted than the crash itself, we shouldn't show the dialog.
5290 *
5291 * A thought: SystemUI might also want to get told about this, the Power
5292 * dialog / global actions also might want different behaviors.
5293 */
5294 private void updateShouldShowDialogsLocked(Configuration config) {
5295 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5296 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5297 && config.navigation == Configuration.NAVIGATION_NONAV);
5298 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5299 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5300 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5301 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5302 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5303 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5304 HIDE_ERROR_DIALOGS, 0) != 0;
5305 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5306 }
5307
5308 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5309 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5310 FONT_SCALE, 1.0f, userId);
5311
5312 synchronized (this) {
5313 if (getGlobalConfiguration().fontScale == scaleFactor) {
5314 return;
5315 }
5316
5317 final Configuration configuration
5318 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5319 configuration.fontScale = scaleFactor;
5320 updatePersistentConfiguration(configuration, userId);
5321 }
5322 }
5323
5324 // Actually is sleeping or shutting down or whatever else in the future
5325 // is an inactive state.
5326 boolean isSleepingOrShuttingDownLocked() {
5327 return isSleepingLocked() || mShuttingDown;
5328 }
5329
5330 boolean isSleepingLocked() {
5331 return mSleeping;
5332 }
5333
Riddle Hsu16567132018-08-16 21:37:47 +08005334 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005335 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005336 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005337 if (task.isActivityTypeStandard()) {
5338 if (mCurAppTimeTracker != r.appTimeTracker) {
5339 // We are switching app tracking. Complete the current one.
5340 if (mCurAppTimeTracker != null) {
5341 mCurAppTimeTracker.stop();
5342 mH.obtainMessage(
5343 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005344 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005345 mCurAppTimeTracker = null;
5346 }
5347 if (r.appTimeTracker != null) {
5348 mCurAppTimeTracker = r.appTimeTracker;
5349 startTimeTrackingFocusedActivityLocked();
5350 }
5351 } else {
5352 startTimeTrackingFocusedActivityLocked();
5353 }
5354 } else {
5355 r.appTimeTracker = null;
5356 }
5357 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5358 // TODO: Probably not, because we don't want to resume voice on switching
5359 // back to this activity
5360 if (task.voiceInteractor != null) {
5361 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5362 } else {
5363 finishRunningVoiceLocked();
5364
5365 if (mLastResumedActivity != null) {
5366 final IVoiceInteractionSession session;
5367
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005368 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005369 if (lastResumedActivityTask != null
5370 && lastResumedActivityTask.voiceSession != null) {
5371 session = lastResumedActivityTask.voiceSession;
5372 } else {
5373 session = mLastResumedActivity.voiceSession;
5374 }
5375
5376 if (session != null) {
5377 // We had been in a voice interaction session, but now focused has
5378 // move to something different. Just finish the session, we can't
5379 // return to it and retain the proper state and synchronization with
5380 // the voice interaction service.
5381 finishVoiceTask(session);
5382 }
5383 }
5384 }
5385
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005386 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5387 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 }
5389 updateResumedAppTrace(r);
5390 mLastResumedActivity = r;
5391
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005392 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005393
5394 applyUpdateLockStateLocked(r);
5395 applyUpdateVrModeLocked(r);
5396
5397 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005398 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005399 r == null ? "NULL" : r.shortComponentName,
5400 reason);
5401 }
5402
5403 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5404 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005405 final ActivityTaskManagerInternal.SleepToken token =
5406 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005407 updateSleepIfNeededLocked();
5408 return token;
5409 }
5410 }
5411
5412 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005413 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 final boolean wasSleeping = mSleeping;
5415 boolean updateOomAdj = false;
5416
5417 if (!shouldSleep) {
5418 // If wasSleeping is true, we need to wake up activity manager state from when
5419 // we started sleeping. In either case, we need to apply the sleep tokens, which
5420 // will wake up stacks or put them to sleep as appropriate.
5421 if (wasSleeping) {
5422 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005423 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5424 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 startTimeTrackingFocusedActivityLocked();
5426 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005427 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5429 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005430 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 if (wasSleeping) {
5432 updateOomAdj = true;
5433 }
5434 } else if (!mSleeping && shouldSleep) {
5435 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005436 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5437 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005438 if (mCurAppTimeTracker != null) {
5439 mCurAppTimeTracker.stop();
5440 }
5441 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005442 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 mStackSupervisor.goingToSleepLocked();
5444 updateResumedAppTrace(null /* resumed */);
5445 updateOomAdj = true;
5446 }
5447 if (updateOomAdj) {
5448 mH.post(mAmInternal::updateOomAdj);
5449 }
5450 }
5451
5452 void updateOomAdj() {
5453 mH.post(mAmInternal::updateOomAdj);
5454 }
5455
Wale Ogunwale53783742018-09-16 10:21:51 -07005456 void updateCpuStats() {
5457 mH.post(mAmInternal::updateCpuStats);
5458 }
5459
Hui Yu03d12402018-12-06 18:00:37 -08005460 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5461 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005462 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5463 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005464 mH.sendMessage(m);
5465 }
5466
Hui Yu03d12402018-12-06 18:00:37 -08005467 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005468 ComponentName taskRoot = null;
5469 final TaskRecord task = activity.getTaskRecord();
5470 if (task != null) {
5471 final ActivityRecord rootActivity = task.getRootActivity();
5472 if (rootActivity != null) {
5473 taskRoot = rootActivity.mActivityComponent;
5474 }
5475 }
5476
Hui Yu03d12402018-12-06 18:00:37 -08005477 final Message m = PooledLambda.obtainMessage(
5478 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005479 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005480 mH.sendMessage(m);
5481 }
5482
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005483 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5484 String hostingType) {
5485 try {
5486 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5487 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5488 + activity.processName);
5489 }
5490 // Post message to start process to avoid possible deadlock of calling into AMS with the
5491 // ATMS lock held.
5492 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5493 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5494 isTop, hostingType, activity.intent.getComponent());
5495 mH.sendMessage(m);
5496 } finally {
5497 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5498 }
5499 }
5500
Wale Ogunwale53783742018-09-16 10:21:51 -07005501 void setBooting(boolean booting) {
5502 mAmInternal.setBooting(booting);
5503 }
5504
5505 boolean isBooting() {
5506 return mAmInternal.isBooting();
5507 }
5508
5509 void setBooted(boolean booted) {
5510 mAmInternal.setBooted(booted);
5511 }
5512
5513 boolean isBooted() {
5514 return mAmInternal.isBooted();
5515 }
5516
5517 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5518 mH.post(() -> {
5519 if (finishBooting) {
5520 mAmInternal.finishBooting();
5521 }
5522 if (enableScreen) {
5523 mInternal.enableScreenAfterBoot(isBooted());
5524 }
5525 });
5526 }
5527
5528 void setHeavyWeightProcess(ActivityRecord root) {
5529 mHeavyWeightProcess = root.app;
5530 final Message m = PooledLambda.obtainMessage(
5531 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005532 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005533 mH.sendMessage(m);
5534 }
5535
5536 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5537 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5538 return;
5539 }
5540
5541 mHeavyWeightProcess = null;
5542 final Message m = PooledLambda.obtainMessage(
5543 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5544 proc.mUserId);
5545 mH.sendMessage(m);
5546 }
5547
5548 private void cancelHeavyWeightProcessNotification(int userId) {
5549 final INotificationManager inm = NotificationManager.getService();
5550 if (inm == null) {
5551 return;
5552 }
5553 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005554 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005555 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5556 } catch (RuntimeException e) {
5557 Slog.w(TAG, "Error canceling notification for service", e);
5558 } catch (RemoteException e) {
5559 }
5560
5561 }
5562
5563 private void postHeavyWeightProcessNotification(
5564 WindowProcessController proc, Intent intent, int userId) {
5565 if (proc == null) {
5566 return;
5567 }
5568
5569 final INotificationManager inm = NotificationManager.getService();
5570 if (inm == null) {
5571 return;
5572 }
5573
5574 try {
5575 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5576 String text = mContext.getString(R.string.heavy_weight_notification,
5577 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5578 Notification notification =
5579 new Notification.Builder(context,
5580 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5581 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5582 .setWhen(0)
5583 .setOngoing(true)
5584 .setTicker(text)
5585 .setColor(mContext.getColor(
5586 com.android.internal.R.color.system_notification_accent_color))
5587 .setContentTitle(text)
5588 .setContentText(
5589 mContext.getText(R.string.heavy_weight_notification_detail))
5590 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5591 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5592 new UserHandle(userId)))
5593 .build();
5594 try {
5595 inm.enqueueNotificationWithTag("android", "android", null,
5596 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5597 } catch (RuntimeException e) {
5598 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5599 } catch (RemoteException e) {
5600 }
5601 } catch (PackageManager.NameNotFoundException e) {
5602 Slog.w(TAG, "Unable to create context for heavy notification", e);
5603 }
5604
5605 }
5606
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005607 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5608 IBinder token, String resultWho, int requestCode, Intent[] intents,
5609 String[] resolvedTypes, int flags, Bundle bOptions) {
5610
5611 ActivityRecord activity = null;
5612 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5613 activity = ActivityRecord.isInStackLocked(token);
5614 if (activity == null) {
5615 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5616 return null;
5617 }
5618 if (activity.finishing) {
5619 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5620 return null;
5621 }
5622 }
5623
5624 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5625 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5626 bOptions);
5627 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5628 if (noCreate) {
5629 return rec;
5630 }
5631 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5632 if (activity.pendingResults == null) {
5633 activity.pendingResults = new HashSet<>();
5634 }
5635 activity.pendingResults.add(rec.ref);
5636 }
5637 return rec;
5638 }
5639
Andrii Kulian52d255c2018-07-13 11:32:19 -07005640 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005641 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005642 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005643 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5644 mCurAppTimeTracker.start(resumedActivity.packageName);
5645 }
5646 }
5647
5648 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5649 if (mTracedResumedActivity != null) {
5650 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5651 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5652 }
5653 if (resumed != null) {
5654 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5655 constructResumedTraceName(resumed.packageName), 0);
5656 }
5657 mTracedResumedActivity = resumed;
5658 }
5659
5660 private String constructResumedTraceName(String packageName) {
5661 return "focused app: " + packageName;
5662 }
5663
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005664 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005665 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005666 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005667 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005668 // mainStack is null during startup.
5669 if (mainStack != null) {
5670 if (changes != 0 && starting == null) {
5671 // If the configuration changed, and the caller is not already
5672 // in the process of starting an activity, then find the top
5673 // activity to check if its configuration needs to change.
5674 starting = mainStack.topRunningActivityLocked();
5675 }
5676
5677 if (starting != null) {
5678 kept = starting.ensureActivityConfiguration(changes,
5679 false /* preserveWindow */);
5680 // And we need to make sure at this point that all other activities
5681 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005682 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005683 !PRESERVE_WINDOWS);
5684 }
5685 }
5686
5687 return kept;
5688 }
5689
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005690 void scheduleAppGcsLocked() {
5691 mH.post(() -> mAmInternal.scheduleAppGcs());
5692 }
5693
Wale Ogunwale53783742018-09-16 10:21:51 -07005694 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5695 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5696 }
5697
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005698 /**
5699 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5700 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5701 * on demand.
5702 */
5703 IPackageManager getPackageManager() {
5704 return AppGlobals.getPackageManager();
5705 }
5706
5707 PackageManagerInternal getPackageManagerInternalLocked() {
5708 if (mPmInternal == null) {
5709 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5710 }
5711 return mPmInternal;
5712 }
5713
Hai Zhangf4da9be2019-05-01 13:46:06 +08005714 PermissionPolicyInternal getPermissionPolicyInternal() {
5715 if (mPermissionPolicyInternal == null) {
5716 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5717 }
5718 return mPermissionPolicyInternal;
5719 }
5720
Wale Ogunwale008163e2018-07-23 23:11:08 -07005721 AppWarnings getAppWarningsLocked() {
5722 return mAppWarnings;
5723 }
5724
Wale Ogunwale214f3482018-10-04 11:00:47 -07005725 Intent getHomeIntent() {
5726 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5727 intent.setComponent(mTopComponent);
5728 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5729 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5730 intent.addCategory(Intent.CATEGORY_HOME);
5731 }
5732 return intent;
5733 }
5734
Chilun2ef71f72018-11-16 17:57:15 +08005735 /**
5736 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5737 * activities.
5738 *
5739 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5740 * component defined in config_secondaryHomeComponent.
5741 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5742 */
5743 Intent getSecondaryHomeIntent(String preferredPackage) {
5744 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005745 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5746 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5747 if (preferredPackage == null || useSystemProvidedLauncher) {
5748 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005749 final String secondaryHomeComponent = mContext.getResources().getString(
5750 com.android.internal.R.string.config_secondaryHomeComponent);
5751 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5752 } else {
5753 intent.setPackage(preferredPackage);
5754 }
5755 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5756 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5757 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5758 }
5759 return intent;
5760 }
5761
Wale Ogunwale214f3482018-10-04 11:00:47 -07005762 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5763 if (info == null) return null;
5764 ApplicationInfo newInfo = new ApplicationInfo(info);
5765 newInfo.initForUser(userId);
5766 return newInfo;
5767 }
5768
Wale Ogunwale9c103022018-10-18 07:44:54 -07005769 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005770 if (uid == SYSTEM_UID) {
5771 // The system gets to run in any process. If there are multiple processes with the same
5772 // uid, just pick the first (this should never happen).
5773 final SparseArray<WindowProcessController> procs =
5774 mProcessNames.getMap().get(processName);
5775 if (procs == null) return null;
5776 final int procCount = procs.size();
5777 for (int i = 0; i < procCount; i++) {
5778 final int procUid = procs.keyAt(i);
5779 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5780 // Don't use an app process or different user process for system component.
5781 continue;
5782 }
5783 return procs.valueAt(i);
5784 }
5785 }
5786
5787 return mProcessNames.get(processName, uid);
5788 }
5789
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005790 WindowProcessController getProcessController(IApplicationThread thread) {
5791 if (thread == null) {
5792 return null;
5793 }
5794
5795 final IBinder threadBinder = thread.asBinder();
5796 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5797 for (int i = pmap.size()-1; i >= 0; i--) {
5798 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5799 for (int j = procs.size() - 1; j >= 0; j--) {
5800 final WindowProcessController proc = procs.valueAt(j);
5801 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5802 return proc;
5803 }
5804 }
5805 }
5806
5807 return null;
5808 }
5809
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005810 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005811 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005812 if (proc == null) return null;
5813 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5814 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005815 }
5816 return null;
5817 }
5818
Riddle Hsua0536432019-02-16 00:38:59 +08005819 int getUidState(int uid) {
5820 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005821 }
5822
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005823 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005824 // A uid is considered to be foreground if it has a visible non-toast window.
5825 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005826 }
5827
Ricky Wai96f5c352019-04-10 18:40:17 +01005828 boolean isDeviceOwner(int uid) {
5829 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005830 }
5831
Ricky Wai96f5c352019-04-10 18:40:17 +01005832 void setDeviceOwnerUid(int uid) {
5833 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005834 }
5835
Wale Ogunwale9de19442018-10-18 19:05:03 -07005836 /**
5837 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5838 * the whitelist
5839 */
5840 String getPendingTempWhitelistTagForUidLocked(int uid) {
5841 return mPendingTempWhitelist.get(uid);
5842 }
5843
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005844 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5845 if (true || Build.IS_USER) {
5846 return;
5847 }
5848
5849 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5850 StrictMode.allowThreadDiskWrites();
5851 try {
5852 File tracesDir = new File("/data/anr");
5853 File tracesFile = null;
5854 try {
5855 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5856
5857 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005858 String timeString =
5859 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5860 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005861 sb.append(": ");
5862 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5863 sb.append(" since ");
5864 sb.append(msg);
5865 FileOutputStream fos = new FileOutputStream(tracesFile);
5866 fos.write(sb.toString().getBytes());
5867 if (app == null) {
5868 fos.write("\n*** No application process!".getBytes());
5869 }
5870 fos.close();
5871 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5872 } catch (IOException e) {
5873 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5874 return;
5875 }
5876
5877 if (app != null && app.getPid() > 0) {
5878 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5879 firstPids.add(app.getPid());
5880 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5881 }
5882
5883 File lastTracesFile = null;
5884 File curTracesFile = null;
5885 for (int i=9; i>=0; i--) {
5886 String name = String.format(Locale.US, "slow%02d.txt", i);
5887 curTracesFile = new File(tracesDir, name);
5888 if (curTracesFile.exists()) {
5889 if (lastTracesFile != null) {
5890 curTracesFile.renameTo(lastTracesFile);
5891 } else {
5892 curTracesFile.delete();
5893 }
5894 }
5895 lastTracesFile = curTracesFile;
5896 }
5897 tracesFile.renameTo(curTracesFile);
5898 } finally {
5899 StrictMode.setThreadPolicy(oldPolicy);
5900 }
5901 }
5902
Michal Karpinskida34cd42019-04-02 19:46:52 +01005903 boolean isAssociatedCompanionApp(int userId, int uid) {
5904 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5905 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005906 return false;
5907 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005908 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005909 }
5910
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005911 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005912 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005913
5914
Wale Ogunwale98875612018-10-12 07:53:02 -07005915 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5916 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005917
Riddle Hsud93a6c42018-11-29 21:50:06 +08005918 H(Looper looper) {
5919 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005920 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005921
5922 @Override
5923 public void handleMessage(Message msg) {
5924 switch (msg.what) {
5925 case REPORT_TIME_TRACKER_MSG: {
5926 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5927 tracker.deliverResult(mContext);
5928 } break;
5929 }
5930 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005931 }
5932
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005933 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005934 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005935
5936 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005937 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005938 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005939
5940 @Override
5941 public void handleMessage(Message msg) {
5942 switch (msg.what) {
5943 case DISMISS_DIALOG_UI_MSG: {
5944 final Dialog d = (Dialog) msg.obj;
5945 d.dismiss();
5946 break;
5947 }
5948 }
5949 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950 }
5951
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005952 final class LocalService extends ActivityTaskManagerInternal {
5953 @Override
5954 public SleepToken acquireSleepToken(String tag, int displayId) {
5955 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005956 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005957 }
5958
5959 @Override
5960 public ComponentName getHomeActivityForUser(int userId) {
5961 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005962 final ActivityRecord homeActivity =
5963 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005964 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 }
5966 }
5967
5968 @Override
5969 public void onLocalVoiceInteractionStarted(IBinder activity,
5970 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5971 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 }
5974 }
5975
5976 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005977 public void notifyAppTransitionStarting(SparseIntArray reasons,
5978 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005979 synchronized (mGlobalLock) {
5980 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5981 reasons, timestamp);
5982 }
5983 }
5984
5985 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005986 public void notifySingleTaskDisplayDrawn(int displayId) {
5987 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
5988 }
5989
5990 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005991 public void notifyAppTransitionFinished() {
5992 synchronized (mGlobalLock) {
5993 mStackSupervisor.notifyAppTransitionDone();
5994 }
5995 }
5996
5997 @Override
5998 public void notifyAppTransitionCancelled() {
5999 synchronized (mGlobalLock) {
6000 mStackSupervisor.notifyAppTransitionDone();
6001 }
6002 }
6003
6004 @Override
6005 public List<IBinder> getTopVisibleActivities() {
6006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006007 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 }
6009 }
6010
6011 @Override
6012 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006014 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006015 }
6016 }
6017
6018 @Override
6019 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6020 Bundle bOptions) {
6021 Preconditions.checkNotNull(intents, "intents");
6022 final String[] resolvedTypes = new String[intents.length];
6023
6024 // UID of the package on user userId.
6025 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6026 // packageUid may not be initialized.
6027 int packageUid = 0;
6028 final long ident = Binder.clearCallingIdentity();
6029
6030 try {
6031 for (int i = 0; i < intents.length; i++) {
6032 resolvedTypes[i] =
6033 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6034 }
6035
6036 packageUid = AppGlobals.getPackageManager().getPackageUid(
6037 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6038 } catch (RemoteException e) {
6039 // Shouldn't happen.
6040 } finally {
6041 Binder.restoreCallingIdentity(ident);
6042 }
6043
Riddle Hsu591bf612019-02-14 17:55:31 +08006044 return getActivityStartController().startActivitiesInPackage(
6045 packageUid, packageName,
6046 intents, resolvedTypes, null /* resultTo */,
6047 SafeActivityOptions.fromBundle(bOptions), userId,
6048 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6049 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006050 }
6051
6052 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006053 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6054 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6055 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6056 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006057 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006058 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006059 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6060 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6061 userId, validateIncomingUser, originatingPendingIntent,
6062 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006063 }
6064 }
6065
6066 @Override
6067 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6068 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6069 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6070 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006071 PendingIntentRecord originatingPendingIntent,
6072 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006073 synchronized (mGlobalLock) {
6074 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6075 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6076 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006077 validateIncomingUser, originatingPendingIntent,
6078 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006079 }
6080 }
6081
6082 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006083 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6084 Intent intent, Bundle options, int userId) {
6085 return ActivityTaskManagerService.this.startActivityAsUser(
6086 caller, callerPacakge, intent,
6087 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6088 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6089 false /*validateIncomingUser*/);
6090 }
6091
6092 @Override
lumark588a3e82018-07-20 18:53:54 +08006093 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006094 synchronized (mGlobalLock) {
6095
6096 // We might change the visibilities here, so prepare an empty app transition which
6097 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006098 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006099 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006100 if (activityDisplay == null) {
6101 return;
6102 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006103 final DisplayContent dc = activityDisplay.mDisplayContent;
6104 final boolean wasTransitionSet =
6105 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006107 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006108 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006109 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110
6111 // If there was a transition set already we don't want to interfere with it as we
6112 // might be starting it too early.
6113 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006114 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 }
6116 }
6117 if (callback != null) {
6118 callback.run();
6119 }
6120 }
6121
6122 @Override
6123 public void notifyKeyguardTrustedChanged() {
6124 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006125 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006126 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128 }
6129 }
6130
6131 /**
6132 * Called after virtual display Id is updated by
6133 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6134 * {@param vrVr2dDisplayId}.
6135 */
6136 @Override
6137 public void setVr2dDisplayId(int vr2dDisplayId) {
6138 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6139 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006140 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006141 }
6142 }
6143
6144 @Override
6145 public void setFocusedActivity(IBinder token) {
6146 synchronized (mGlobalLock) {
6147 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6148 if (r == null) {
6149 throw new IllegalArgumentException(
6150 "setFocusedActivity: No activity record matching token=" + token);
6151 }
Louis Chang19443452018-10-09 12:10:21 +08006152 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006153 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 }
6155 }
6156 }
6157
6158 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006160 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162
6163 @Override
6164 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006165 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167
6168 @Override
6169 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006170 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 }
6172
6173 @Override
6174 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6175 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6176 }
6177
6178 @Override
6179 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006180 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006182
6183 @Override
6184 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6185 synchronized (mGlobalLock) {
6186 mActiveVoiceInteractionServiceComponent = component;
6187 }
6188 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006189
6190 @Override
6191 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6192 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6193 return;
6194 }
6195 synchronized (mGlobalLock) {
6196 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6197 if (types == null) {
6198 if (uid < 0) {
6199 return;
6200 }
6201 types = new ArrayMap<>();
6202 mAllowAppSwitchUids.put(userId, types);
6203 }
6204 if (uid < 0) {
6205 types.remove(type);
6206 } else {
6207 types.put(type, uid);
6208 }
6209 }
6210 }
6211
6212 @Override
6213 public void onUserStopped(int userId) {
6214 synchronized (mGlobalLock) {
6215 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6216 mAllowAppSwitchUids.remove(userId);
6217 }
6218 }
6219
6220 @Override
6221 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6222 synchronized (mGlobalLock) {
6223 return ActivityTaskManagerService.this.isGetTasksAllowed(
6224 caller, callingPid, callingUid);
6225 }
6226 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006227
Riddle Hsua0536432019-02-16 00:38:59 +08006228 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006229 @Override
6230 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006231 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006232 mProcessNames.put(proc.mName, proc.mUid, proc);
6233 }
6234 }
6235
Riddle Hsua0536432019-02-16 00:38:59 +08006236 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006237 @Override
6238 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006239 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006240 mProcessNames.remove(name, uid);
6241 }
6242 }
6243
Riddle Hsua0536432019-02-16 00:38:59 +08006244 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006245 @Override
6246 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006247 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006248 if (proc == mHomeProcess) {
6249 mHomeProcess = null;
6250 }
6251 if (proc == mPreviousProcess) {
6252 mPreviousProcess = null;
6253 }
6254 }
6255 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006256
Riddle Hsua0536432019-02-16 00:38:59 +08006257 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006258 @Override
6259 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006260 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006261 return mTopProcessState;
6262 }
6263 }
6264
Riddle Hsua0536432019-02-16 00:38:59 +08006265 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006266 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006267 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006268 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006269 return proc == mHeavyWeightProcess;
6270 }
6271 }
6272
Riddle Hsua0536432019-02-16 00:38:59 +08006273 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006274 @Override
6275 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006277 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6278 }
6279 }
6280
6281 @Override
6282 public void finishHeavyWeightApp() {
6283 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006284 if (mHeavyWeightProcess != null) {
6285 mHeavyWeightProcess.finishActivities();
6286 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6288 mHeavyWeightProcess);
6289 }
6290 }
6291
Riddle Hsua0536432019-02-16 00:38:59 +08006292 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006293 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006294 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006295 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006296 return isSleepingLocked();
6297 }
6298 }
6299
6300 @Override
6301 public boolean isShuttingDown() {
6302 synchronized (mGlobalLock) {
6303 return mShuttingDown;
6304 }
6305 }
6306
6307 @Override
6308 public boolean shuttingDown(boolean booted, int timeout) {
6309 synchronized (mGlobalLock) {
6310 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006311 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006313 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006314 return mStackSupervisor.shutdownLocked(timeout);
6315 }
6316 }
6317
6318 @Override
6319 public void enableScreenAfterBoot(boolean booted) {
6320 synchronized (mGlobalLock) {
6321 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6322 SystemClock.uptimeMillis());
6323 mWindowManager.enableScreenAfterBoot();
6324 updateEventDispatchingLocked(booted);
6325 }
6326 }
6327
6328 @Override
6329 public boolean showStrictModeViolationDialog() {
6330 synchronized (mGlobalLock) {
6331 return mShowDialogs && !mSleeping && !mShuttingDown;
6332 }
6333 }
6334
6335 @Override
6336 public void showSystemReadyErrorDialogsIfNeeded() {
6337 synchronized (mGlobalLock) {
6338 try {
6339 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6340 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6341 + " data partition or your device will be unstable.");
6342 mUiHandler.post(() -> {
6343 if (mShowDialogs) {
6344 AlertDialog d = new BaseErrorDialog(mUiContext);
6345 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6346 d.setCancelable(false);
6347 d.setTitle(mUiContext.getText(R.string.android_system_label));
6348 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6349 d.setButton(DialogInterface.BUTTON_POSITIVE,
6350 mUiContext.getText(R.string.ok),
6351 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6352 d.show();
6353 }
6354 });
6355 }
6356 } catch (RemoteException e) {
6357 }
6358
6359 if (!Build.isBuildConsistent()) {
6360 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6361 mUiHandler.post(() -> {
6362 if (mShowDialogs) {
6363 AlertDialog d = new BaseErrorDialog(mUiContext);
6364 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6365 d.setCancelable(false);
6366 d.setTitle(mUiContext.getText(R.string.android_system_label));
6367 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6368 d.setButton(DialogInterface.BUTTON_POSITIVE,
6369 mUiContext.getText(R.string.ok),
6370 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6371 d.show();
6372 }
6373 });
6374 }
6375 }
6376 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006377
6378 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006379 public void onProcessMapped(int pid, WindowProcessController proc) {
6380 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006381 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006382 }
6383 }
6384
6385 @Override
6386 public void onProcessUnMapped(int pid) {
6387 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006388 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006389 }
6390 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006391
6392 @Override
6393 public void onPackageDataCleared(String name) {
6394 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006395 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006396 mAppWarnings.onPackageDataCleared(name);
6397 }
6398 }
6399
6400 @Override
6401 public void onPackageUninstalled(String name) {
6402 synchronized (mGlobalLock) {
6403 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006404 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006405 }
6406 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006407
6408 @Override
6409 public void onPackageAdded(String name, boolean replacing) {
6410 synchronized (mGlobalLock) {
6411 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6412 }
6413 }
6414
6415 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006416 public void onPackageReplaced(ApplicationInfo aInfo) {
6417 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006418 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006419 }
6420 }
6421
6422 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006423 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6424 synchronized (mGlobalLock) {
6425 return compatibilityInfoForPackageLocked(ai);
6426 }
6427 }
6428
Yunfan Chen75157d72018-07-27 14:47:21 +09006429 /**
6430 * Set the corresponding display information for the process global configuration. To be
6431 * called when we need to show IME on a different display.
6432 *
6433 * @param pid The process id associated with the IME window.
6434 * @param displayId The ID of the display showing the IME.
6435 */
6436 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006437 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006438 // Don't update process-level configuration for Multi-Client IME process since other
6439 // IMEs on other displays will also receive this configuration change due to IME
6440 // services use the same application config/context.
6441 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006442
Yunfan Chen75157d72018-07-27 14:47:21 +09006443 if (pid == MY_PID || pid < 0) {
6444 if (DEBUG_CONFIGURATION) {
6445 Slog.w(TAG,
6446 "Trying to update display configuration for system/invalid process.");
6447 }
6448 return;
6449 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006450 synchronized (mGlobalLock) {
6451 final ActivityDisplay activityDisplay =
6452 mRootActivityContainer.getActivityDisplay(displayId);
6453 if (activityDisplay == null) {
6454 // Call might come when display is not yet added or has been removed.
6455 if (DEBUG_CONFIGURATION) {
6456 Slog.w(TAG, "Trying to update display configuration for non-existing "
6457 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006458 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006459 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006460 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006461 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006462 if (process == null) {
6463 if (DEBUG_CONFIGURATION) {
6464 Slog.w(TAG, "Trying to update display configuration for invalid "
6465 + "process, pid=" + pid);
6466 }
6467 return;
6468 }
lumarkddc77fb2019-06-27 22:22:23 +08006469 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006470 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6471 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006472 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006473
6474 @Override
6475 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006476 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006477 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006478 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6479 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006480 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006481 }
6482 }
6483 }
6484
6485 @Override
6486 public void clearPendingResultForActivity(IBinder activityToken,
6487 WeakReference<PendingIntentRecord> pir) {
6488 synchronized (mGlobalLock) {
6489 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6490 if (r != null && r.pendingResults != null) {
6491 r.pendingResults.remove(pir);
6492 }
6493 }
6494 }
6495
6496 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006497 public ActivityTokens getTopActivityForTask(int taskId) {
6498 synchronized (mGlobalLock) {
6499 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6500 if (taskRecord == null) {
6501 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6502 + " Requested task not found");
6503 return null;
6504 }
6505 final ActivityRecord activity = taskRecord.getTopActivity();
6506 if (activity == null) {
6507 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6508 + " Requested activity not found");
6509 return null;
6510 }
6511 if (!activity.attachedToProcess()) {
6512 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6513 + activity);
6514 return null;
6515 }
6516 return new ActivityTokens(activity.appToken, activity.assistToken,
6517 activity.app.getThread());
6518 }
6519 }
6520
6521 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006522 public IIntentSender getIntentSender(int type, String packageName,
6523 int callingUid, int userId, IBinder token, String resultWho,
6524 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6525 Bundle bOptions) {
6526 synchronized (mGlobalLock) {
6527 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6528 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6529 }
6530 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006531
6532 @Override
6533 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6534 synchronized (mGlobalLock) {
6535 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6536 if (r == null) {
6537 return null;
6538 }
6539 if (r.mServiceConnectionsHolder == null) {
6540 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6541 ActivityTaskManagerService.this, r);
6542 }
6543
6544 return r.mServiceConnectionsHolder;
6545 }
6546 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006547
6548 @Override
6549 public Intent getHomeIntent() {
6550 synchronized (mGlobalLock) {
6551 return ActivityTaskManagerService.this.getHomeIntent();
6552 }
6553 }
6554
6555 @Override
6556 public boolean startHomeActivity(int userId, String reason) {
6557 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006558 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006559 }
6560 }
6561
6562 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006563 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006564 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006565 synchronized (mGlobalLock) {
6566 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006567 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006568 }
Chilun8b1f1be2019-03-13 17:14:36 +08006569 }
6570
6571 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006572 public boolean startHomeOnAllDisplays(int userId, String reason) {
6573 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006574 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006575 }
6576 }
6577
Riddle Hsua0536432019-02-16 00:38:59 +08006578 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006579 @Override
6580 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006581 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006582 if (mFactoryTest == FACTORY_TEST_OFF) {
6583 return false;
6584 }
6585 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6586 && wpc.mName.equals(mTopComponent.getPackageName())) {
6587 return true;
6588 }
6589 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6590 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6591 }
6592 }
6593
6594 @Override
6595 public void updateTopComponentForFactoryTest() {
6596 synchronized (mGlobalLock) {
6597 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6598 return;
6599 }
6600 final ResolveInfo ri = mContext.getPackageManager()
6601 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6602 final CharSequence errorMsg;
6603 if (ri != null) {
6604 final ActivityInfo ai = ri.activityInfo;
6605 final ApplicationInfo app = ai.applicationInfo;
6606 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6607 mTopAction = Intent.ACTION_FACTORY_TEST;
6608 mTopData = null;
6609 mTopComponent = new ComponentName(app.packageName, ai.name);
6610 errorMsg = null;
6611 } else {
6612 errorMsg = mContext.getResources().getText(
6613 com.android.internal.R.string.factorytest_not_system);
6614 }
6615 } else {
6616 errorMsg = mContext.getResources().getText(
6617 com.android.internal.R.string.factorytest_no_action);
6618 }
6619 if (errorMsg == null) {
6620 return;
6621 }
6622
6623 mTopAction = null;
6624 mTopData = null;
6625 mTopComponent = null;
6626 mUiHandler.post(() -> {
6627 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6628 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006629 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006630 });
6631 }
6632 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006633
Riddle Hsua0536432019-02-16 00:38:59 +08006634 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006635 @Override
6636 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6637 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006638 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006639 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006640 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006641
6642 wpc.clearRecentTasks();
6643 wpc.clearActivities();
6644
6645 if (wpc.isInstrumenting()) {
6646 finishInstrumentationCallback.run();
6647 }
6648
Jorim Jaggid0752812018-10-16 16:07:20 +02006649 if (!restarting && hasVisibleActivities) {
6650 mWindowManager.deferSurfaceLayout();
6651 try {
6652 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6653 // If there was nothing to resume, and we are not already restarting
6654 // this process, but there is a visible activity that is hosted by the
6655 // process...then make sure all visible activities are running, taking
6656 // care of restarting this process.
6657 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6658 !PRESERVE_WINDOWS);
6659 }
6660 } finally {
6661 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006662 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006663 }
6664 }
6665 }
6666
6667 @Override
6668 public void closeSystemDialogs(String reason) {
6669 enforceNotIsolatedCaller("closeSystemDialogs");
6670
6671 final int pid = Binder.getCallingPid();
6672 final int uid = Binder.getCallingUid();
6673 final long origId = Binder.clearCallingIdentity();
6674 try {
6675 synchronized (mGlobalLock) {
6676 // Only allow this from foreground processes, so that background
6677 // applications can't abuse it to prevent system UI from being shown.
6678 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006679 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006680 if (!proc.isPerceptible()) {
6681 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6682 + " from background process " + proc);
6683 return;
6684 }
6685 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006686 mWindowManager.closeSystemDialogs(reason);
6687
Wale Ogunwaled32da472018-11-16 07:19:28 -08006688 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006690 // Call into AM outside the synchronized block.
6691 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 } finally {
6693 Binder.restoreCallingIdentity(origId);
6694 }
6695 }
6696
6697 @Override
6698 public void cleanupDisabledPackageComponents(
6699 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6700 synchronized (mGlobalLock) {
6701 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006702 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006704 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006705 mStackSupervisor.scheduleIdleLocked();
6706 }
6707
6708 // Clean-up disabled tasks
6709 getRecentTasks().cleanupDisabledPackageTasksLocked(
6710 packageName, disabledClasses, userId);
6711 }
6712 }
6713
6714 @Override
6715 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6716 int userId) {
6717 synchronized (mGlobalLock) {
6718
6719 boolean didSomething =
6720 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006721 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 null, doit, evenPersistent, userId);
6723 return didSomething;
6724 }
6725 }
6726
6727 @Override
6728 public void resumeTopActivities(boolean scheduleIdle) {
6729 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006730 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 if (scheduleIdle) {
6732 mStackSupervisor.scheduleIdleLocked();
6733 }
6734 }
6735 }
6736
Riddle Hsua0536432019-02-16 00:38:59 +08006737 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006738 @Override
6739 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006740 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006741 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6742 }
6743 }
6744
Riddle Hsua0536432019-02-16 00:38:59 +08006745 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 @Override
6747 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006748 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006749 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 }
6751 }
6752
6753 @Override
6754 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6755 try {
6756 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6757 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6758 }
6759 } catch (RemoteException ex) {
6760 throw new SecurityException("Fail to check is caller a privileged app", ex);
6761 }
6762
6763 synchronized (mGlobalLock) {
6764 final long ident = Binder.clearCallingIdentity();
6765 try {
6766 if (mAmInternal.shouldConfirmCredentials(userId)) {
6767 if (mKeyguardController.isKeyguardLocked()) {
6768 // Showing launcher to avoid user entering credential twice.
6769 startHomeActivity(currentUserId, "notifyLockedProfile");
6770 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006771 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 }
6773 } finally {
6774 Binder.restoreCallingIdentity(ident);
6775 }
6776 }
6777 }
6778
6779 @Override
6780 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6781 mAmInternal.enforceCallingPermission(
6782 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6783
6784 synchronized (mGlobalLock) {
6785 final long ident = Binder.clearCallingIdentity();
6786 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006787 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6788 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6791 UserHandle.CURRENT);
6792 } finally {
6793 Binder.restoreCallingIdentity(ident);
6794 }
6795 }
6796 }
6797
6798 @Override
6799 public void writeActivitiesToProto(ProtoOutputStream proto) {
6800 synchronized (mGlobalLock) {
6801 // The output proto of "activity --proto activities"
6802 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006803 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006804 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6805 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
6807 }
6808
6809 @Override
6810 public void saveANRState(String reason) {
6811 synchronized (mGlobalLock) {
6812 final StringWriter sw = new StringWriter();
6813 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6814 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6815 if (reason != null) {
6816 pw.println(" Reason: " + reason);
6817 }
6818 pw.println();
6819 getActivityStartController().dump(pw, " ", null);
6820 pw.println();
6821 pw.println("-------------------------------------------------------------------------------");
6822 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6823 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6824 "" /* header */);
6825 pw.println();
6826 pw.close();
6827
6828 mLastANRState = sw.toString();
6829 }
6830 }
6831
6832 @Override
6833 public void clearSavedANRState() {
6834 synchronized (mGlobalLock) {
6835 mLastANRState = null;
6836 }
6837 }
6838
6839 @Override
6840 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6841 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6842 synchronized (mGlobalLock) {
6843 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6844 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6845 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6846 dumpLastANRLocked(pw);
6847 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6848 dumpLastANRTracesLocked(pw);
6849 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6850 dumpActivityStarterLocked(pw, dumpPackage);
6851 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6852 dumpActivityContainersLocked(pw);
6853 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6854 if (getRecentTasks() != null) {
6855 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6856 }
6857 }
6858 }
6859 }
6860
6861 @Override
6862 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6863 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6864 int wakefulness) {
6865 synchronized (mGlobalLock) {
6866 if (mHomeProcess != null && (dumpPackage == null
6867 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6868 if (needSep) {
6869 pw.println();
6870 needSep = false;
6871 }
6872 pw.println(" mHomeProcess: " + mHomeProcess);
6873 }
6874 if (mPreviousProcess != null && (dumpPackage == null
6875 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6876 if (needSep) {
6877 pw.println();
6878 needSep = false;
6879 }
6880 pw.println(" mPreviousProcess: " + mPreviousProcess);
6881 }
6882 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6883 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6884 StringBuilder sb = new StringBuilder(128);
6885 sb.append(" mPreviousProcessVisibleTime: ");
6886 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6887 pw.println(sb);
6888 }
6889 if (mHeavyWeightProcess != null && (dumpPackage == null
6890 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6891 if (needSep) {
6892 pw.println();
6893 needSep = false;
6894 }
6895 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6896 }
6897 if (dumpPackage == null) {
6898 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006899 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 }
6901 if (dumpAll) {
6902 if (dumpPackage == null) {
6903 pw.println(" mConfigWillChange: "
6904 + getTopDisplayFocusedStack().mConfigWillChange);
6905 }
6906 if (mCompatModePackages.getPackages().size() > 0) {
6907 boolean printed = false;
6908 for (Map.Entry<String, Integer> entry
6909 : mCompatModePackages.getPackages().entrySet()) {
6910 String pkg = entry.getKey();
6911 int mode = entry.getValue();
6912 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6913 continue;
6914 }
6915 if (!printed) {
6916 pw.println(" mScreenCompatPackages:");
6917 printed = true;
6918 }
6919 pw.println(" " + pkg + ": " + mode);
6920 }
6921 }
6922 }
6923
6924 if (dumpPackage == null) {
6925 pw.println(" mWakefulness="
6926 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006927 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006928 if (mRunningVoice != null) {
6929 pw.println(" mRunningVoice=" + mRunningVoice);
6930 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6931 }
6932 pw.println(" mSleeping=" + mSleeping);
6933 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6934 pw.println(" mVrController=" + mVrController);
6935 }
6936 if (mCurAppTimeTracker != null) {
6937 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6938 }
6939 if (mAllowAppSwitchUids.size() > 0) {
6940 boolean printed = false;
6941 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6942 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6943 for (int j = 0; j < types.size(); j++) {
6944 if (dumpPackage == null ||
6945 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6946 if (needSep) {
6947 pw.println();
6948 needSep = false;
6949 }
6950 if (!printed) {
6951 pw.println(" mAllowAppSwitchUids:");
6952 printed = true;
6953 }
6954 pw.print(" User ");
6955 pw.print(mAllowAppSwitchUids.keyAt(i));
6956 pw.print(": Type ");
6957 pw.print(types.keyAt(j));
6958 pw.print(" = ");
6959 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6960 pw.println();
6961 }
6962 }
6963 }
6964 }
6965 if (dumpPackage == null) {
6966 if (mController != null) {
6967 pw.println(" mController=" + mController
6968 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6969 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006970 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6971 pw.println(" mLaunchingActivityWakeLock="
6972 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006973 }
6974
6975 return needSep;
6976 }
6977 }
6978
6979 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006980 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6981 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 synchronized (mGlobalLock) {
6983 if (dumpPackage == null) {
6984 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6985 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006986 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6987 if (mRunningVoice != null) {
6988 final long vrToken = proto.start(
6989 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6990 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6991 mRunningVoice.toString());
6992 mVoiceWakeLock.writeToProto(
6993 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6994 proto.end(vrToken);
6995 }
6996 mVrController.writeToProto(proto,
6997 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006998 if (mController != null) {
6999 final long token = proto.start(CONTROLLER);
7000 proto.write(CONTROLLER, mController.toString());
7001 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7002 proto.end(token);
7003 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007004 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7005 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7006 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 }
7008
7009 if (mHomeProcess != null && (dumpPackage == null
7010 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007011 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 }
7013
7014 if (mPreviousProcess != null && (dumpPackage == null
7015 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007016 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7018 }
7019
7020 if (mHeavyWeightProcess != null && (dumpPackage == null
7021 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007022 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007023 }
7024
7025 for (Map.Entry<String, Integer> entry
7026 : mCompatModePackages.getPackages().entrySet()) {
7027 String pkg = entry.getKey();
7028 int mode = entry.getValue();
7029 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7030 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7031 proto.write(PACKAGE, pkg);
7032 proto.write(MODE, mode);
7033 proto.end(compatToken);
7034 }
7035 }
7036
7037 if (mCurAppTimeTracker != null) {
7038 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7039 }
7040
7041 }
7042 }
7043
7044 @Override
7045 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7046 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7047 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007048 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7049 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 }
7051
7052 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007053 public void dumpForOom(PrintWriter pw) {
7054 synchronized (mGlobalLock) {
7055 pw.println(" mHomeProcess: " + mHomeProcess);
7056 pw.println(" mPreviousProcess: " + mPreviousProcess);
7057 if (mHeavyWeightProcess != null) {
7058 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7059 }
7060 }
7061 }
7062
7063 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007064 public boolean canGcNow() {
7065 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007066 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007067 }
7068 }
7069
Riddle Hsua0536432019-02-16 00:38:59 +08007070 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007071 @Override
7072 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007073 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007074 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007075 return top != null ? top.app : null;
7076 }
7077 }
7078
Riddle Hsua0536432019-02-16 00:38:59 +08007079 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 @Override
7081 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007082 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007083 if (mRootActivityContainer != null) {
7084 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007085 }
7086 }
7087 }
7088
7089 @Override
7090 public void scheduleDestroyAllActivities(String reason) {
7091 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007092 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094 }
7095
7096 @Override
7097 public void removeUser(int userId) {
7098 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007099 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 }
7101 }
7102
7103 @Override
7104 public boolean switchUser(int userId, UserState userState) {
7105 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007106 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 }
7108 }
7109
7110 @Override
7111 public void onHandleAppCrash(WindowProcessController wpc) {
7112 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007113 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 }
7115 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007116
7117 @Override
7118 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7119 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007120 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007121 }
7122 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007123
Riddle Hsua0536432019-02-16 00:38:59 +08007124 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007125 @Override
7126 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007127 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007128 }
7129
Riddle Hsua0536432019-02-16 00:38:59 +08007130 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007131 @Override
7132 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007133 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007134 }
7135
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007139 mActiveUids.onActiveUidsCleared();
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 onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007145 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007146 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007147
7148 @Override
7149 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007150 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007151 mPendingTempWhitelist.put(uid, tag);
7152 }
7153 }
7154
7155 @Override
7156 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007157 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007158 mPendingTempWhitelist.remove(uid);
7159 }
7160 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007161
7162 @Override
7163 public boolean handleAppCrashInActivityController(String processName, int pid,
7164 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7165 Runnable killCrashingAppCallback) {
7166 synchronized (mGlobalLock) {
7167 if (mController == null) {
7168 return false;
7169 }
7170
7171 try {
7172 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7173 stackTrace)) {
7174 killCrashingAppCallback.run();
7175 return true;
7176 }
7177 } catch (RemoteException e) {
7178 mController = null;
7179 Watchdog.getInstance().setActivityController(null);
7180 }
7181 return false;
7182 }
7183 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007184
7185 @Override
7186 public void removeRecentTasksByPackageName(String packageName, int userId) {
7187 synchronized (mGlobalLock) {
7188 mRecentTasks.removeTasksByPackageName(packageName, userId);
7189 }
7190 }
7191
7192 @Override
7193 public void cleanupRecentTasksForUser(int userId) {
7194 synchronized (mGlobalLock) {
7195 mRecentTasks.cleanupLocked(userId);
7196 }
7197 }
7198
7199 @Override
7200 public void loadRecentTasksForUser(int userId) {
7201 synchronized (mGlobalLock) {
7202 mRecentTasks.loadUserRecentsLocked(userId);
7203 }
7204 }
7205
7206 @Override
7207 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7208 synchronized (mGlobalLock) {
7209 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7210 }
7211 }
7212
7213 @Override
7214 public void flushRecentTasks() {
7215 mRecentTasks.flush();
7216 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007217
7218 @Override
7219 public WindowProcessController getHomeProcess() {
7220 synchronized (mGlobalLock) {
7221 return mHomeProcess;
7222 }
7223 }
7224
7225 @Override
7226 public WindowProcessController getPreviousProcess() {
7227 synchronized (mGlobalLock) {
7228 return mPreviousProcess;
7229 }
7230 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007231
7232 @Override
7233 public void clearLockedTasks(String reason) {
7234 synchronized (mGlobalLock) {
7235 getLockTaskController().clearLockedTasks(reason);
7236 }
7237 }
7238
7239 @Override
7240 public void updateUserConfiguration() {
7241 synchronized (mGlobalLock) {
7242 final Configuration configuration = new Configuration(getGlobalConfiguration());
7243 final int currentUserId = mAmInternal.getCurrentUserId();
7244 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7245 configuration, currentUserId, Settings.System.canWrite(mContext));
7246 updateConfigurationLocked(configuration, null /* starting */,
7247 false /* initLocale */, false /* persistent */, currentUserId,
7248 false /* deferResume */);
7249 }
7250 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007251
7252 @Override
7253 public boolean canShowErrorDialogs() {
7254 synchronized (mGlobalLock) {
7255 return mShowDialogs && !mSleeping && !mShuttingDown
7256 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7257 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7258 mAmInternal.getCurrentUserId())
7259 && !(UserManager.isDeviceInDemoMode(mContext)
7260 && mAmInternal.getCurrentUser().isDemo());
7261 }
7262 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007263
7264 @Override
7265 public void setProfileApp(String profileApp) {
7266 synchronized (mGlobalLock) {
7267 mProfileApp = profileApp;
7268 }
7269 }
7270
7271 @Override
7272 public void setProfileProc(WindowProcessController wpc) {
7273 synchronized (mGlobalLock) {
7274 mProfileProc = wpc;
7275 }
7276 }
7277
7278 @Override
7279 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7280 synchronized (mGlobalLock) {
7281 mProfilerInfo = profilerInfo;
7282 }
7283 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007284
7285 @Override
7286 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7287 synchronized (mGlobalLock) {
7288 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7289 }
7290 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007291
7292 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007293 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7294 boolean reducedResolution) {
7295 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7296 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007297 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007298
7299 @Override
7300 public boolean isUidForeground(int uid) {
7301 synchronized (mGlobalLock) {
7302 return ActivityTaskManagerService.this.isUidForeground(uid);
7303 }
7304 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007305
7306 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007307 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007308 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007309 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007310 }
7311 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007312
7313 @Override
7314 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007315 // Translate package names into UIDs
7316 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007317 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007318 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7319 if (uid >= 0) {
7320 result.add(uid);
7321 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007322 }
7323 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007324 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007325 }
7326 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007327 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007328}