blob: 468a13d45d55c5019fd75f18eee78b131a6d3042 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070055import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800126import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700218import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.EventLog;
220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700293import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Map;
295import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296
297/**
298 * System service for managing activities and their containers (task, stacks, displays,... ).
299 *
300 * {@hide}
301 */
302public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700303 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700305 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
306 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
307 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
308 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
309 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700310 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700311
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100316 // How long we permit background activity starts after an activity in the process
317 // started or finished.
318 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319
Wale Ogunwale98875612018-10-12 07:53:02 -0700320 /** Used to indicate that an app transition should be animated. */
321 static final boolean ANIMATE = true;
322
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700323 /** Hardware-reported OpenGLES version. */
324 final int GL_ES_VERSION;
325
Wale Ogunwale31913b52018-10-13 08:29:31 -0700326 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
327 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
328 public static final String DUMP_LASTANR_CMD = "lastanr" ;
329 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
330 public static final String DUMP_STARTER_CMD = "starter" ;
331 public static final String DUMP_CONTAINERS_CMD = "containers" ;
332 public static final String DUMP_RECENTS_CMD = "recents" ;
333 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
334
Wale Ogunwale64258362018-10-16 15:13:37 -0700335 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
336 public static final int RELAUNCH_REASON_NONE = 0;
337 /** This activity is being relaunched due to windowing mode change. */
338 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
339 /** This activity is being relaunched due to a free-resize operation. */
340 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
341
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700342 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700343
Wale Ogunwalef6733932018-06-27 05:14:34 -0700344 /**
345 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
346 * change at runtime. Use mContext for non-UI purposes.
347 */
348 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700350 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700353 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700354 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800355 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800356 @VisibleForTesting
357 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 PowerManagerInternal mPowerManagerInternal;
359 private UsageStatsManagerInternal mUsageStatsInternal;
360
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700361 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 IntentFirewall mIntentFirewall;
363
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700364 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800365 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800366 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700367 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
369 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
370 *
371 * @see WindowManagerThreadPriorityBooster
372 */
373 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700374 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800375 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700376 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700377 private UserManagerService mUserManager;
378 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700379 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800380 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700381 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** All processes currently running that might have a window organized by name. */
383 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100384 /** All processes we currently have running mapped by pid and uid */
385 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** This is the process holding what we currently consider to be the "home" activity. */
387 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700388 /** The currently running heavy-weight process, if any. */
389 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700390 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /**
392 * This is the process holding the activity the user last visited that is in a different process
393 * from the one they are currently in.
394 */
395 WindowProcessController mPreviousProcess;
396 /** The time at which the previous process was last visible. */
397 long mPreviousProcessVisibleTime;
398
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700399 /** List of intents that were used to start the most recent tasks. */
400 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700401 /** State of external calls telling us if the device is awake or asleep. */
402 private boolean mKeyguardShown = false;
403
404 // Wrapper around VoiceInteractionServiceManager
405 private AssistUtils mAssistUtils;
406
407 // VoiceInteraction session ID that changes for each new request except when
408 // being called for multi-window assist in a single session.
409 private int mViSessionId = 1000;
410
411 // How long to wait in getAssistContextExtras for the activity and foreground services
412 // to respond with the result.
413 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
414
415 // How long top wait when going through the modern assist (which doesn't need to block
416 // on getting this result before starting to launch its UI).
417 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
418
419 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
420 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
421
Alison Cichowlas3e340502018-08-07 17:15:01 -0400422 // Permission tokens are used to temporarily granted a trusted app the ability to call
423 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
424 // showing any appropriate error messages to the user.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
426 10 * MINUTE_IN_MILLIS;
427
428 // How long before the service actually expires a token. This is slightly longer than
429 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
430 // expiration exception.
431 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
432 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
433
434 // How long the service will remember expired tokens, for the purpose of providing error
435 // messaging when a client uses an expired token.
436 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
437 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
438
439 // Activity tokens of system activities that are delegating their call to
440 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
441 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
442
443 // Permission tokens that have expired, but we remember for error reporting.
444 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
447
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700448 // Keeps track of the active voice interaction service component, notified from
449 // VoiceInteractionManagerService
450 ComponentName mActiveVoiceInteractionServiceComponent;
451
Michal Karpinskida34cd42019-04-02 19:46:52 +0100452 // A map userId and all its companion app uids
453 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000454
Wale Ogunwalee2172292018-10-25 10:11:10 -0700455 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700456 KeyguardController mKeyguardController;
457 private final ClientLifecycleManager mLifecycleManager;
458 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700459 /** The controller for all operations related to locktask. */
460 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700461 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700462
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 boolean mSuppressResizeConfigChanges;
464
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700465 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 new UpdateConfigurationResult();
467
468 static final class UpdateConfigurationResult {
469 // Configuration changes that were updated.
470 int changes;
471 // If the activity was relaunched to match the new configuration.
472 boolean activityRelaunched;
473
474 void reset() {
475 changes = 0;
476 activityRelaunched = false;
477 }
478 }
479
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 private int mConfigurationSeq;
482 // To cache the list of supported system locales
483 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484
485 /**
486 * Temp object used when global and/or display override configuration is updated. It is also
487 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
488 * anyone...
489 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private Configuration mTempConfig = new Configuration();
491
Wale Ogunwalef6733932018-06-27 05:14:34 -0700492 /** Temporary to avoid allocations. */
493 final StringBuilder mStringBuilder = new StringBuilder(256);
494
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 // Amount of time after a call to stopAppSwitches() during which we will
496 // prevent further untrusted switches from happening.
497 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
498
499 /**
500 * The time at which we will allow normal application switches again,
501 * after a call to {@link #stopAppSwitches()}.
502 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700503 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 /**
505 * This is set to true after the first switch after mAppSwitchesAllowedTime
506 * is set; any switches after that will clear the time.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509
Ricky Wai906af482019-06-03 17:25:28 +0100510 /**
511 * Last stop app switches time, apps finished before this time cannot start background activity
512 * even if they are in grace period.
513 */
514 private long mLastStopAppSwitchesTime;
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 IActivityController mController = null;
517 boolean mControllerIsAMonkey = false;
518
Wale Ogunwale214f3482018-10-04 11:00:47 -0700519 final int mFactoryTest;
520
521 /** Used to control how we initialize the service. */
522 ComponentName mTopComponent;
523 String mTopAction = Intent.ACTION_MAIN;
524 String mTopData;
525
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800526 /** Profiling app information. */
527 String mProfileApp = null;
528 WindowProcessController mProfileProc = null;
529 ProfilerInfo mProfilerInfo = null;
530
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700532 * Dump of the activity state at the time of the last ANR. Cleared after
533 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
534 */
535 String mLastANRState;
536
537 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 * Used to retain an update lock when the foreground activity is in
539 * immersive mode.
540 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542
543 /**
544 * Packages that are being allowed to perform unrestricted app switches. Mapping is
545 * User -> Type -> uid.
546 */
547 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
548
549 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private int mThumbnailWidth;
551 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700552
553 /**
554 * Flag that indicates if multi-window is enabled.
555 *
556 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
557 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
558 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
559 * At least one of the forms of multi-window must be enabled in order for this flag to be
560 * initialized to 'true'.
561 *
562 * @see #mSupportsSplitScreenMultiWindow
563 * @see #mSupportsFreeformWindowManagement
564 * @see #mSupportsPictureInPicture
565 * @see #mSupportsMultiDisplay
566 */
567 boolean mSupportsMultiWindow;
568 boolean mSupportsSplitScreenMultiWindow;
569 boolean mSupportsFreeformWindowManagement;
570 boolean mSupportsPictureInPicture;
571 boolean mSupportsMultiDisplay;
572 boolean mForceResizableActivities;
573
574 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
575
576 // VR Vr2d Display Id.
577 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700578
Wale Ogunwalef6733932018-06-27 05:14:34 -0700579 /**
580 * Set while we are wanting to sleep, to prevent any
581 * activities from being started/resumed.
582 *
583 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
584 *
585 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
586 * while in the sleep state until there is a pending transition out of sleep, in which case
587 * mSleeping is set to false, and remains false while awake.
588 *
589 * Whether mSleeping can quickly toggled between true/false without the device actually
590 * display changing states is undefined.
591 */
592 private boolean mSleeping = false;
593
594 /**
595 * The process state used for processes that are running the top activities.
596 * This changes between TOP and TOP_SLEEPING to following mSleeping.
597 */
598 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
599
Riddle Hsua0022cd2019-09-09 21:12:41 +0800600 @Retention(RetentionPolicy.SOURCE)
601 @IntDef({
602 LAYOUT_REASON_CONFIG_CHANGED,
603 LAYOUT_REASON_VISIBILITY_CHANGED,
604 })
605 @interface LayoutReason {}
606 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
607 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
608
609 /** The reasons to perform surface placement. */
610 @LayoutReason
611 private int mLayoutReasons;
612
Wale Ogunwalef6733932018-06-27 05:14:34 -0700613 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
614 // automatically. Important for devices without direct input devices.
615 private boolean mShowDialogs = true;
616
617 /** Set if we are shutting down the system, similar to sleeping. */
618 boolean mShuttingDown = false;
619
620 /**
621 * We want to hold a wake lock while running a voice interaction session, since
622 * this may happen with the screen off and we need to keep the CPU running to
623 * be able to continue to interact with the user.
624 */
625 PowerManager.WakeLock mVoiceWakeLock;
626
627 /**
628 * Set while we are running a voice interaction. This overrides sleeping while it is active.
629 */
630 IVoiceInteractionSession mRunningVoice;
631
632 /**
633 * The last resumed activity. This is identical to the current resumed activity most
634 * of the time but could be different when we're pausing one activity before we resume
635 * another activity.
636 */
637 ActivityRecord mLastResumedActivity;
638
639 /**
640 * The activity that is currently being traced as the active resumed activity.
641 *
642 * @see #updateResumedAppTrace
643 */
644 private @Nullable ActivityRecord mTracedResumedActivity;
645
646 /** If non-null, we are tracking the time the user spends in the currently focused app. */
647 AppTimeTracker mCurAppTimeTracker;
648
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700649 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700650
Wale Ogunwale53783742018-09-16 10:21:51 -0700651 /**
652 * Packages that the user has asked to have run in screen size
653 * compatibility mode instead of filling the screen.
654 */
655 CompatModePackages mCompatModePackages;
656
Wale Ogunwalef6733932018-06-27 05:14:34 -0700657 private FontScaleSettingObserver mFontScaleSettingObserver;
658
Ricky Wai96f5c352019-04-10 18:40:17 +0100659 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private final class FontScaleSettingObserver extends ContentObserver {
662 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
663 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
664
665 public FontScaleSettingObserver() {
666 super(mH);
667 final ContentResolver resolver = mContext.getContentResolver();
668 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
669 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
670 UserHandle.USER_ALL);
671 }
672
673 @Override
674 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
675 if (mFontScaleUri.equals(uri)) {
676 updateFontScaleIfNeeded(userId);
677 } else if (mHideErrorDialogsUri.equals(uri)) {
678 synchronized (mGlobalLock) {
679 updateShouldShowDialogsLocked(getGlobalConfiguration());
680 }
681 }
682 }
683 }
684
Riddle Hsua0536432019-02-16 00:38:59 +0800685 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
686 @Target(ElementType.METHOD)
687 @Retention(RetentionPolicy.SOURCE)
688 @interface HotPath {
689 int NONE = 0;
690 int OOM_ADJUSTMENT = 1;
691 int LRU_UPDATE = 2;
692 int PROCESS_CHANGE = 3;
693 int caller() default NONE;
694 }
695
Charles Chen8d98dd22018-12-26 17:36:54 +0800696 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
697 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700698 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700699 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700700 mSystemThread = ActivityThread.currentActivityThread();
701 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700702 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800703 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700704 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void onSystemReady() {
708 synchronized (mGlobalLock) {
709 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
710 PackageManager.FEATURE_CANT_SAVE_STATE);
711 mAssistUtils = new AssistUtils(mContext);
712 mVrController.onSystemReady();
713 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700714 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700715 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700716 }
717
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 public void onInitPowerManagement() {
719 synchronized (mGlobalLock) {
720 mStackSupervisor.initPowerManagement();
721 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
722 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
723 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
724 mVoiceWakeLock.setReferenceCounted(false);
725 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700726 }
727
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700728 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700729 mFontScaleSettingObserver = new FontScaleSettingObserver();
730 }
731
Wale Ogunwale59507092018-10-29 09:00:30 -0700732 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733 final boolean freeformWindowManagement =
734 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
735 || Settings.Global.getInt(
736 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
737
738 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
739 final boolean supportsPictureInPicture = supportsMultiWindow &&
740 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
741 final boolean supportsSplitScreenMultiWindow =
742 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
743 final boolean supportsMultiDisplay = mContext.getPackageManager()
744 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700745 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
746 final boolean forceResizable = Settings.Global.getInt(
747 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
748
749 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900750 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700751
752 final Configuration configuration = new Configuration();
753 Settings.System.getConfiguration(resolver, configuration);
754 if (forceRtl) {
755 // This will take care of setting the correct layout direction flags
756 configuration.setLayoutDirection(configuration.locale);
757 }
758
759 synchronized (mGlobalLock) {
760 mForceResizableActivities = forceResizable;
761 final boolean multiWindowFormEnabled = freeformWindowManagement
762 || supportsSplitScreenMultiWindow
763 || supportsPictureInPicture
764 || supportsMultiDisplay;
765 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
766 mSupportsMultiWindow = true;
767 mSupportsFreeformWindowManagement = freeformWindowManagement;
768 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
769 mSupportsPictureInPicture = supportsPictureInPicture;
770 mSupportsMultiDisplay = supportsMultiDisplay;
771 } else {
772 mSupportsMultiWindow = false;
773 mSupportsFreeformWindowManagement = false;
774 mSupportsSplitScreenMultiWindow = false;
775 mSupportsPictureInPicture = false;
776 mSupportsMultiDisplay = false;
777 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700778 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 // This happens before any activities are started, so we can change global configuration
780 // in-place.
781 updateConfigurationLocked(configuration, null, true);
782 final Configuration globalConfig = getGlobalConfiguration();
783 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
784
785 // Load resources only after the current configuration has been set.
786 final Resources res = mContext.getResources();
787 mThumbnailWidth = res.getDimensionPixelSize(
788 com.android.internal.R.dimen.thumbnail_width);
789 mThumbnailHeight = res.getDimensionPixelSize(
790 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700791 }
792 }
793
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800794 public WindowManagerGlobalLock getGlobalLock() {
795 return mGlobalLock;
796 }
797
Yunfan Chen585f2932019-01-29 16:04:45 +0900798 /** For test purpose only. */
799 @VisibleForTesting
800 public ActivityTaskManagerInternal getAtmInternal() {
801 return mInternal;
802 }
803
Riddle Hsud93a6c42018-11-29 21:50:06 +0800804 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
805 Looper looper) {
806 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700807 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700808 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700809 final File systemDir = SystemServiceManager.ensureSystemDir();
810 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
811 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
814 mTempConfig.setToDefaults();
815 mTempConfig.setLocales(LocaleList.getDefault());
816 mConfigurationSeq = mTempConfig.seq = 1;
817 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800818 mRootActivityContainer = new RootActivityContainer(this);
819 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700820
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700823 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700825 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mKeyguardController = mStackSupervisor.getKeyguardController();
828 }
829
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 public void onActivityManagerInternalAdded() {
831 synchronized (mGlobalLock) {
832 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
833 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
834 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700835 }
836
Yunfan Chen75157d72018-07-27 14:47:21 +0900837 int increaseConfigurationSeqLocked() {
838 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
839 return mConfigurationSeq;
840 }
841
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700842 protected ActivityStackSupervisor createStackSupervisor() {
843 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
844 supervisor.initialize();
845 return supervisor;
846 }
847
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 public void setWindowManager(WindowManagerService wm) {
849 synchronized (mGlobalLock) {
850 mWindowManager = wm;
851 mLockTaskController.setWindowManager(wm);
852 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800853 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700854 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700855 }
856
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700857 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
858 synchronized (mGlobalLock) {
859 mUsageStatsInternal = usageStatsManager;
860 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700861 }
862
Wale Ogunwalef6733932018-06-27 05:14:34 -0700863 UserManagerService getUserManager() {
864 if (mUserManager == null) {
865 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
866 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
867 }
868 return mUserManager;
869 }
870
871 AppOpsService getAppOpsService() {
872 if (mAppOpsService == null) {
873 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
874 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
875 }
876 return mAppOpsService;
877 }
878
879 boolean hasUserRestriction(String restriction, int userId) {
880 return getUserManager().hasUserRestriction(restriction, userId);
881 }
882
Michal Karpinski15486842019-04-25 17:33:42 +0100883 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
884 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
885 callingUid, callingPackage);
886 if (mode == AppOpsManager.MODE_DEFAULT) {
887 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
888 == PERMISSION_GRANTED;
889 }
890 return mode == AppOpsManager.MODE_ALLOWED;
891 }
892
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700893 @VisibleForTesting
894 protected void setRecentTasks(RecentTasks recentTasks) {
895 mRecentTasks = recentTasks;
896 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700897 }
898
899 RecentTasks getRecentTasks() {
900 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700901 }
902
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700903 ClientLifecycleManager getLifecycleManager() {
904 return mLifecycleManager;
905 }
906
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700907 ActivityStartController getActivityStartController() {
908 return mActivityStartController;
909 }
910
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700911 TaskChangeNotificationController getTaskChangeNotificationController() {
912 return mTaskChangeNotificationController;
913 }
914
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700915 LockTaskController getLockTaskController() {
916 return mLockTaskController;
917 }
918
Yunfan Chen75157d72018-07-27 14:47:21 +0900919 /**
920 * Return the global configuration used by the process corresponding to the input pid. This is
921 * usually the global configuration with some overrides specific to that process.
922 */
923 Configuration getGlobalConfigurationForCallingPid() {
924 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800925 return getGlobalConfigurationForPid(pid);
926 }
927
928 /**
929 * Return the global configuration used by the process corresponding to the given pid.
930 */
931 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900932 if (pid == MY_PID || pid < 0) {
933 return getGlobalConfiguration();
934 }
935 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100936 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900937 return app != null ? app.getConfiguration() : getGlobalConfiguration();
938 }
939 }
940
941 /**
942 * Return the device configuration info used by the process corresponding to the input pid.
943 * The value is consistent with the global configuration for the process.
944 */
945 @Override
946 public ConfigurationInfo getDeviceConfigurationInfo() {
947 ConfigurationInfo config = new ConfigurationInfo();
948 synchronized (mGlobalLock) {
949 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
950 config.reqTouchScreen = globalConfig.touchscreen;
951 config.reqKeyboardType = globalConfig.keyboard;
952 config.reqNavigation = globalConfig.navigation;
953 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
954 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
955 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
956 }
957 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
958 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
959 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
960 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700961 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900962 }
963 return config;
964 }
965
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700966 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700967 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700968 }
969
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700970 public static final class Lifecycle extends SystemService {
971 private final ActivityTaskManagerService mService;
972
973 public Lifecycle(Context context) {
974 super(context);
975 mService = new ActivityTaskManagerService(context);
976 }
977
978 @Override
979 public void onStart() {
980 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700981 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700982 }
983
Garfield Tan891146c2018-10-09 12:14:00 -0700984 @Override
985 public void onUnlockUser(int userId) {
986 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800987 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700988 }
989 }
990
991 @Override
992 public void onCleanupUser(int userId) {
993 synchronized (mService.getGlobalLock()) {
994 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
995 }
996 }
997
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700998 public ActivityTaskManagerService getService() {
999 return mService;
1000 }
1001 }
1002
1003 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 public final int startActivity(IApplicationThread caller, String callingPackage,
1005 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1006 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1007 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1008 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1009 UserHandle.getCallingUserId());
1010 }
1011
1012 @Override
1013 public final int startActivities(IApplicationThread caller, String callingPackage,
1014 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1015 int userId) {
1016 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001017 enforceNotIsolatedCaller(reason);
1018 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001020 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1021 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1022 reason, null /* originatingPendingIntent */,
1023 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 }
1025
1026 @Override
1027 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1030 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1031 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1032 true /*validateIncomingUser*/);
1033 }
1034
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001035 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1037 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1038 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001041 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1043
1044 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001045 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 .setCaller(caller)
1047 .setCallingPackage(callingPackage)
1048 .setResolvedType(resolvedType)
1049 .setResultTo(resultTo)
1050 .setResultWho(resultWho)
1051 .setRequestCode(requestCode)
1052 .setStartFlags(startFlags)
1053 .setProfilerInfo(profilerInfo)
1054 .setActivityOptions(bOptions)
1055 .setMayWait(userId)
1056 .execute();
1057
1058 }
1059
1060 @Override
1061 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1062 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001063 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1064 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 // Refuse possible leaked file descriptors
1066 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1067 throw new IllegalArgumentException("File descriptors passed in Intent");
1068 }
1069
1070 if (!(target instanceof PendingIntentRecord)) {
1071 throw new IllegalArgumentException("Bad PendingIntent object");
1072 }
1073
1074 PendingIntentRecord pir = (PendingIntentRecord)target;
1075
1076 synchronized (mGlobalLock) {
1077 // If this is coming from the currently resumed activity, it is
1078 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001079 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 if (stack.mResumedActivity != null &&
1081 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 }
1084 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001085 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001086 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 }
1088
1089 @Override
1090 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1091 Bundle bOptions) {
1092 // Refuse possible leaked file descriptors
1093 if (intent != null && intent.hasFileDescriptors()) {
1094 throw new IllegalArgumentException("File descriptors passed in Intent");
1095 }
1096 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1097
1098 synchronized (mGlobalLock) {
1099 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1100 if (r == null) {
1101 SafeActivityOptions.abort(options);
1102 return false;
1103 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001104 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 // The caller is not running... d'oh!
1106 SafeActivityOptions.abort(options);
1107 return false;
1108 }
1109 intent = new Intent(intent);
1110 // The caller is not allowed to change the data.
1111 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1112 // And we are resetting to find the next component...
1113 intent.setComponent(null);
1114
1115 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1116
1117 ActivityInfo aInfo = null;
1118 try {
1119 List<ResolveInfo> resolves =
1120 AppGlobals.getPackageManager().queryIntentActivities(
1121 intent, r.resolvedType,
1122 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1123 UserHandle.getCallingUserId()).getList();
1124
1125 // Look for the original activity in the list...
1126 final int N = resolves != null ? resolves.size() : 0;
1127 for (int i=0; i<N; i++) {
1128 ResolveInfo rInfo = resolves.get(i);
1129 if (rInfo.activityInfo.packageName.equals(r.packageName)
1130 && rInfo.activityInfo.name.equals(r.info.name)) {
1131 // We found the current one... the next matching is
1132 // after it.
1133 i++;
1134 if (i<N) {
1135 aInfo = resolves.get(i).activityInfo;
1136 }
1137 if (debug) {
1138 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1139 + "/" + r.info.name);
1140 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1141 ? "null" : aInfo.packageName + "/" + aInfo.name));
1142 }
1143 break;
1144 }
1145 }
1146 } catch (RemoteException e) {
1147 }
1148
1149 if (aInfo == null) {
1150 // Nobody who is next!
1151 SafeActivityOptions.abort(options);
1152 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1153 return false;
1154 }
1155
1156 intent.setComponent(new ComponentName(
1157 aInfo.applicationInfo.packageName, aInfo.name));
1158 intent.setFlags(intent.getFlags()&~(
1159 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1160 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1161 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1162 FLAG_ACTIVITY_NEW_TASK));
1163
1164 // Okay now we need to start the new activity, replacing the currently running activity.
1165 // This is a little tricky because we want to start the new one as if the current one is
1166 // finished, but not finish the current one first so that there is no flicker.
1167 // And thus...
1168 final boolean wasFinishing = r.finishing;
1169 r.finishing = true;
1170
1171 // Propagate reply information over to the new activity.
1172 final ActivityRecord resultTo = r.resultTo;
1173 final String resultWho = r.resultWho;
1174 final int requestCode = r.requestCode;
1175 r.resultTo = null;
1176 if (resultTo != null) {
1177 resultTo.removeResultsLocked(r, resultWho, requestCode);
1178 }
1179
1180 final long origId = Binder.clearCallingIdentity();
1181 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001182 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001184 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001185 .setResolvedType(r.resolvedType)
1186 .setActivityInfo(aInfo)
1187 .setResultTo(resultTo != null ? resultTo.appToken : null)
1188 .setResultWho(resultWho)
1189 .setRequestCode(requestCode)
1190 .setCallingPid(-1)
1191 .setCallingUid(r.launchedFromUid)
1192 .setCallingPackage(r.launchedFromPackage)
1193 .setRealCallingPid(-1)
1194 .setRealCallingUid(r.launchedFromUid)
1195 .setActivityOptions(options)
1196 .execute();
1197 Binder.restoreCallingIdentity(origId);
1198
1199 r.finishing = wasFinishing;
1200 if (res != ActivityManager.START_SUCCESS) {
1201 return false;
1202 }
1203 return true;
1204 }
1205 }
1206
1207 @Override
1208 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1209 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1210 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1211 final WaitResult res = new WaitResult();
1212 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001213 enforceNotIsolatedCaller("startActivityAndWait");
1214 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1215 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001217 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 .setCaller(caller)
1219 .setCallingPackage(callingPackage)
1220 .setResolvedType(resolvedType)
1221 .setResultTo(resultTo)
1222 .setResultWho(resultWho)
1223 .setRequestCode(requestCode)
1224 .setStartFlags(startFlags)
1225 .setActivityOptions(bOptions)
1226 .setMayWait(userId)
1227 .setProfilerInfo(profilerInfo)
1228 .setWaitResult(res)
1229 .execute();
1230 }
1231 return res;
1232 }
1233
1234 @Override
1235 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1236 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1237 int startFlags, Configuration config, Bundle bOptions, int userId) {
1238 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001239 enforceNotIsolatedCaller("startActivityWithConfig");
1240 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1241 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001242 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001243 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 .setCaller(caller)
1245 .setCallingPackage(callingPackage)
1246 .setResolvedType(resolvedType)
1247 .setResultTo(resultTo)
1248 .setResultWho(resultWho)
1249 .setRequestCode(requestCode)
1250 .setStartFlags(startFlags)
1251 .setGlobalConfiguration(config)
1252 .setActivityOptions(bOptions)
1253 .setMayWait(userId)
1254 .execute();
1255 }
1256 }
1257
Alison Cichowlas3e340502018-08-07 17:15:01 -04001258
1259 @Override
1260 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1261 int callingUid = Binder.getCallingUid();
1262 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1263 throw new SecurityException("Only the system process can request a permission token, "
1264 + "received request from uid: " + callingUid);
1265 }
1266 IBinder permissionToken = new Binder();
1267 synchronized (mGlobalLock) {
1268 mStartActivitySources.put(permissionToken, delegatorToken);
1269 }
1270
1271 Message expireMsg = PooledLambda.obtainMessage(
1272 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1273 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1274
1275 Message forgetMsg = PooledLambda.obtainMessage(
1276 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1277 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1278
1279 return permissionToken;
1280 }
1281
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 @Override
1283 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1284 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1286 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001288 // permission grants) as any app that may launch one of your own activities. So we only
1289 // allow this in two cases:
1290 // 1) The caller is an activity that is part of the core framework, and then only when it
1291 // is running as the system.
1292 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1293 // can only be requested by a system activity, which may then delegate this call to
1294 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001295 final ActivityRecord sourceRecord;
1296 final int targetUid;
1297 final String targetPackage;
1298 final boolean isResolver;
1299 synchronized (mGlobalLock) {
1300 if (resultTo == null) {
1301 throw new SecurityException("Must be called from an activity");
1302 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001303 final IBinder sourceToken;
1304 if (permissionToken != null) {
1305 // To even attempt to use a permissionToken, an app must also have this signature
1306 // permission.
1307 mAmInternal.enforceCallingPermission(
1308 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1309 "startActivityAsCaller");
1310 // If called with a permissionToken, we want the sourceRecord from the delegator
1311 // activity that requested this token.
1312 sourceToken = mStartActivitySources.remove(permissionToken);
1313 if (sourceToken == null) {
1314 // Invalid permissionToken, check if it recently expired.
1315 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1316 throw new SecurityException("Called with expired permission token: "
1317 + permissionToken);
1318 } else {
1319 throw new SecurityException("Called with invalid permission token: "
1320 + permissionToken);
1321 }
1322 }
1323 } else {
1324 // This method was called directly by the source.
1325 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327
Wale Ogunwaled32da472018-11-16 07:19:28 -08001328 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329 if (sourceRecord == null) {
1330 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001331 }
1332 if (sourceRecord.app == null) {
1333 throw new SecurityException("Called without a process attached to activity");
1334 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001335
1336 // Whether called directly or from a delegate, the source activity must be from the
1337 // android package.
1338 if (!sourceRecord.info.packageName.equals("android")) {
1339 throw new SecurityException("Must be called from an activity that is "
1340 + "declared in the android package");
1341 }
1342
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001343 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 // This is still okay, as long as this activity is running under the
1345 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001348 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 + " must be system uid or original calling uid "
1350 + sourceRecord.launchedFromUid);
1351 }
1352 }
1353 if (ignoreTargetSecurity) {
1354 if (intent.getComponent() == null) {
1355 throw new SecurityException(
1356 "Component must be specified with ignoreTargetSecurity");
1357 }
1358 if (intent.getSelector() != null) {
1359 throw new SecurityException(
1360 "Selector not allowed with ignoreTargetSecurity");
1361 }
1362 }
1363 targetUid = sourceRecord.launchedFromUid;
1364 targetPackage = sourceRecord.launchedFromPackage;
1365 isResolver = sourceRecord.isResolverOrChildActivity();
1366 }
1367
1368 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001369 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 }
1371
1372 // TODO: Switch to user app stacks here.
1373 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001374 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 .setCallingUid(targetUid)
1376 .setCallingPackage(targetPackage)
1377 .setResolvedType(resolvedType)
1378 .setResultTo(resultTo)
1379 .setResultWho(resultWho)
1380 .setRequestCode(requestCode)
1381 .setStartFlags(startFlags)
1382 .setActivityOptions(bOptions)
1383 .setMayWait(userId)
1384 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1385 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001386 // The target may well be in the background, which would normally prevent it
1387 // from starting an activity. Here we definitely want the start to succeed.
1388 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 .execute();
1390 } catch (SecurityException e) {
1391 // XXX need to figure out how to propagate to original app.
1392 // A SecurityException here is generally actually a fault of the original
1393 // calling activity (such as a fairly granting permissions), so propagate it
1394 // back to them.
1395 /*
1396 StringBuilder msg = new StringBuilder();
1397 msg.append("While launching");
1398 msg.append(intent.toString());
1399 msg.append(": ");
1400 msg.append(e.getMessage());
1401 */
1402 throw e;
1403 }
1404 }
1405
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001406 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1407 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1408 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1409 }
1410
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 @Override
1412 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1413 Intent intent, String resolvedType, IVoiceInteractionSession session,
1414 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1415 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 if (session == null || interactor == null) {
1418 throw new NullPointerException("null session or interactor");
1419 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001420 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001422 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 .setCallingUid(callingUid)
1424 .setCallingPackage(callingPackage)
1425 .setResolvedType(resolvedType)
1426 .setVoiceSession(session)
1427 .setVoiceInteractor(interactor)
1428 .setStartFlags(startFlags)
1429 .setProfilerInfo(profilerInfo)
1430 .setActivityOptions(bOptions)
1431 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001432 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 .execute();
1434 }
1435
1436 @Override
1437 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1438 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1440 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001442 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .setCallingUid(callingUid)
1444 .setCallingPackage(callingPackage)
1445 .setResolvedType(resolvedType)
1446 .setActivityOptions(bOptions)
1447 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001448 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .execute();
1450 }
1451
Riddle Hsu609a8e22019-06-27 16:46:29 -06001452 /**
1453 * Start the recents activity to perform the recents animation.
1454 *
1455 * @param intent The intent to start the recents activity.
1456 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1457 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001459 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1460 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001461 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001463 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 final long origId = Binder.clearCallingIdentity();
1465 try {
1466 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001467 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1468 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001469 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470
1471 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001472 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001473 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001474 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001475 if (recentsAnimationRunner == null) {
1476 anim.preloadRecentsActivity();
1477 } else {
1478 anim.startRecentsActivity(recentsAnimationRunner);
1479 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 }
1481 } finally {
1482 Binder.restoreCallingIdentity(origId);
1483 }
1484 }
1485
1486 @Override
1487 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001488 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 "startActivityFromRecents()");
1490
1491 final int callingPid = Binder.getCallingPid();
1492 final int callingUid = Binder.getCallingUid();
1493 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1494 final long origId = Binder.clearCallingIdentity();
1495 try {
1496 synchronized (mGlobalLock) {
1497 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1498 safeOptions);
1499 }
1500 } finally {
1501 Binder.restoreCallingIdentity(origId);
1502 }
1503 }
1504
1505 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001506 * Public API to check if the client is allowed to start an activity on specified display.
1507 *
1508 * If the target display is private or virtual, some restrictions will apply.
1509 *
1510 * @param displayId Target display id.
1511 * @param intent Intent used to launch the activity.
1512 * @param resolvedType The MIME type of the intent.
1513 * @param userId The id of the user for whom the call is made.
1514 * @return {@code true} if a call to start an activity on the target display should succeed and
1515 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1516 */
1517 @Override
1518 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1519 String resolvedType, int userId) {
1520 final int callingUid = Binder.getCallingUid();
1521 final int callingPid = Binder.getCallingPid();
1522 final long origId = Binder.clearCallingIdentity();
1523
1524 try {
1525 // Collect information about the target of the Intent.
1526 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1527 0 /* startFlags */, null /* profilerInfo */, userId,
1528 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1529 UserHandle.USER_NULL));
1530 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1531
1532 synchronized (mGlobalLock) {
1533 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1534 aInfo);
1535 }
1536 } finally {
1537 Binder.restoreCallingIdentity(origId);
1538 }
1539 }
1540
1541 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 * This is the internal entry point for handling Activity.finish().
1543 *
1544 * @param token The Binder token referencing the Activity we want to finish.
1545 * @param resultCode Result code, if any, from this Activity.
1546 * @param resultData Result data (Intent), if any, from this Activity.
1547 * @param finishTask Whether to finish the task associated with this Activity.
1548 *
1549 * @return Returns true if the activity successfully finished, or false if it is still running.
1550 */
1551 @Override
1552 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1553 int finishTask) {
1554 // Refuse possible leaked file descriptors
1555 if (resultData != null && resultData.hasFileDescriptors()) {
1556 throw new IllegalArgumentException("File descriptors passed in Intent");
1557 }
1558
1559 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001560 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 if (r == null) {
1562 return true;
1563 }
1564 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001565 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001566 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 if (rootR == null) {
1568 Slog.w(TAG, "Finishing task with all activities already finished");
1569 }
1570 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1571 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001572 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 return false;
1574 }
1575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001576 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1577 // We should consolidate.
1578 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001580 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 if (next != null) {
1582 // ask watcher if this is allowed
1583 boolean resumeOK = true;
1584 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001585 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001587 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 Watchdog.getInstance().setActivityController(null);
1589 }
1590
1591 if (!resumeOK) {
1592 Slog.i(TAG, "Not finishing activity because controller resumed");
1593 return false;
1594 }
1595 }
1596 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001597
1598 // note down that the process has finished an activity and is in background activity
1599 // starts grace period
1600 if (r.app != null) {
1601 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1602 }
1603
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 final long origId = Binder.clearCallingIdentity();
1605 try {
1606 boolean res;
1607 final boolean finishWithRootActivity =
1608 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1609 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1610 || (finishWithRootActivity && r == rootR)) {
1611 // If requested, remove the task that is associated to this activity only if it
1612 // was the root activity in the task. The result code and data is ignored
1613 // because we don't support returning them across task boundaries. Also, to
1614 // keep backwards compatibility we remove the task from recents when finishing
1615 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001616 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 finishWithRootActivity, "finish-activity");
1618 if (!res) {
1619 Slog.i(TAG, "Removing task failed to finish activity");
1620 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001621 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001622 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001624 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001625 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001626 if (!res) {
1627 Slog.i(TAG, "Failed to finish by app-request");
1628 }
1629 }
1630 return res;
1631 } finally {
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634 }
1635 }
1636
1637 @Override
1638 public boolean finishActivityAffinity(IBinder token) {
1639 synchronized (mGlobalLock) {
1640 final long origId = Binder.clearCallingIdentity();
1641 try {
1642 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1643 if (r == null) {
1644 return false;
1645 }
1646
1647 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1648 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001649 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 return false;
1651 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001652 r.finishActivityAffinity();
1653 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 } finally {
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657 }
1658 }
1659
1660 @Override
1661 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1662 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001663 try {
1664 WindowProcessController proc = null;
1665 synchronized (mGlobalLock) {
1666 ActivityStack stack = ActivityRecord.getStackLocked(token);
1667 if (stack == null) {
1668 return;
1669 }
1670 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1671 false /* fromTimeout */, false /* processPausingActivities */, config);
1672 if (r != null) {
1673 proc = r.app;
1674 }
1675 if (stopProfiling && proc != null) {
1676 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 }
1678 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001679 } finally {
1680 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 }
1683
1684 @Override
1685 public final void activityResumed(IBinder token) {
1686 final long origId = Binder.clearCallingIdentity();
1687 synchronized (mGlobalLock) {
1688 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001694 public final void activityTopResumedStateLost() {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1698 }
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701
1702 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 public final void activityPaused(IBinder token) {
1704 final long origId = Binder.clearCallingIdentity();
1705 synchronized (mGlobalLock) {
1706 ActivityStack stack = ActivityRecord.getStackLocked(token);
1707 if (stack != null) {
1708 stack.activityPausedLocked(token, false);
1709 }
1710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
1715 public final void activityStopped(IBinder token, Bundle icicle,
1716 PersistableBundle persistentState, CharSequence description) {
1717 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1718
1719 // Refuse possible leaked file descriptors
1720 if (icicle != null && icicle.hasFileDescriptors()) {
1721 throw new IllegalArgumentException("File descriptors passed in Bundle");
1722 }
1723
1724 final long origId = Binder.clearCallingIdentity();
1725
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 String restartingName = null;
1727 int restartingUid = 0;
1728 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001732 if (r.attachedToProcess()
1733 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1734 // The activity was requested to restart from
1735 // {@link #restartActivityProcessIfVisible}.
1736 restartingName = r.app.mName;
1737 restartingUid = r.app.mUid;
1738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 r.activityStoppedLocked(icicle, persistentState, description);
1740 }
1741 }
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 if (restartingName != null) {
1744 // In order to let the foreground activity can be restarted with its saved state from
1745 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1746 // until the activity reports stopped with the state. And the activity record will be
1747 // kept because the record state is restarting, then the activity will be restarted
1748 // immediately if it is still the top one.
1749 mStackSupervisor.removeRestartTimeouts(r);
1750 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1751 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753
1754 Binder.restoreCallingIdentity(origId);
1755 }
1756
1757 @Override
1758 public final void activityDestroyed(IBinder token) {
1759 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1760 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001761 final long origId = Binder.clearCallingIdentity();
1762 try {
1763 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1764 if (activity != null) {
1765 activity.destroyed("activityDestroyed");
1766 }
1767 } finally {
1768 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001769 }
1770 }
1771 }
1772
1773 @Override
1774 public final void activityRelaunched(IBinder token) {
1775 final long origId = Binder.clearCallingIdentity();
1776 synchronized (mGlobalLock) {
1777 mStackSupervisor.activityRelaunchedLocked(token);
1778 }
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781
1782 public final void activitySlept(IBinder token) {
1783 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 synchronized (mGlobalLock) {
1788 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1789 if (r != null) {
1790 mStackSupervisor.activitySleptLocked(r);
1791 }
1792 }
1793
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796
1797 @Override
1798 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1799 synchronized (mGlobalLock) {
1800 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1801 if (r == null) {
1802 return;
1803 }
1804 final long origId = Binder.clearCallingIdentity();
1805 try {
1806 r.setRequestedOrientation(requestedOrientation);
1807 } finally {
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810 }
1811 }
1812
1813 @Override
1814 public int getRequestedOrientation(IBinder token) {
1815 synchronized (mGlobalLock) {
1816 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1817 if (r == null) {
1818 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1819 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001820 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 }
1822 }
1823
1824 @Override
1825 public void setImmersive(IBinder token, boolean immersive) {
1826 synchronized (mGlobalLock) {
1827 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1828 if (r == null) {
1829 throw new IllegalArgumentException();
1830 }
1831 r.immersive = immersive;
1832
1833 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001834 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 }
1838 }
1839 }
1840
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001841 void applyUpdateLockStateLocked(ActivityRecord r) {
1842 // Modifications to the UpdateLock state are done on our handler, outside
1843 // the activity manager's locks. The new state is determined based on the
1844 // state *now* of the relevant activity record. The object is passed to
1845 // the handler solely for logging detail, not to be consulted/modified.
1846 final boolean nextState = r != null && r.immersive;
1847 mH.post(() -> {
1848 if (mUpdateLock.isHeld() != nextState) {
1849 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1850 "Applying new update lock state '" + nextState + "' for " + r);
1851 if (nextState) {
1852 mUpdateLock.acquire();
1853 } else {
1854 mUpdateLock.release();
1855 }
1856 }
1857 });
1858 }
1859
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 @Override
1861 public boolean isImmersive(IBinder token) {
1862 synchronized (mGlobalLock) {
1863 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1864 if (r == null) {
1865 throw new IllegalArgumentException();
1866 }
1867 return r.immersive;
1868 }
1869 }
1870
1871 @Override
1872 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001875 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 return (r != null) ? r.immersive : false;
1877 }
1878 }
1879
1880 @Override
1881 public void overridePendingTransition(IBinder token, String packageName,
1882 int enterAnim, int exitAnim) {
1883 synchronized (mGlobalLock) {
1884 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1885 if (self == null) {
1886 return;
1887 }
1888
1889 final long origId = Binder.clearCallingIdentity();
1890
1891 if (self.isState(
1892 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001893 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001894 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 }
1896
1897 Binder.restoreCallingIdentity(origId);
1898 }
1899 }
1900
1901 @Override
1902 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 if (r == null) {
1907 return ActivityManager.COMPAT_MODE_UNKNOWN;
1908 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001909 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 }
1911 }
1912
1913 @Override
1914 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001919 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 if (r == null) {
1921 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1922 return;
1923 }
1924 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001925 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 }
1927 }
1928
1929 @Override
1930 public int getLaunchedFromUid(IBinder activityToken) {
1931 ActivityRecord srec;
1932 synchronized (mGlobalLock) {
1933 srec = ActivityRecord.forTokenLocked(activityToken);
1934 }
1935 if (srec == null) {
1936 return -1;
1937 }
1938 return srec.launchedFromUid;
1939 }
1940
1941 @Override
1942 public String getLaunchedFromPackage(IBinder activityToken) {
1943 ActivityRecord srec;
1944 synchronized (mGlobalLock) {
1945 srec = ActivityRecord.forTokenLocked(activityToken);
1946 }
1947 if (srec == null) {
1948 return null;
1949 }
1950 return srec.launchedFromPackage;
1951 }
1952
1953 @Override
1954 public boolean convertFromTranslucent(IBinder token) {
1955 final long origId = Binder.clearCallingIdentity();
1956 try {
1957 synchronized (mGlobalLock) {
1958 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1959 if (r == null) {
1960 return false;
1961 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001962 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public boolean convertToTranslucent(IBinder token, Bundle options) {
1971 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1972 final long origId = Binder.clearCallingIdentity();
1973 try {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1976 if (r == null) {
1977 return false;
1978 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 int index = task.mActivities.lastIndexOf(r);
1981 if (index > 0) {
1982 ActivityRecord under = task.mActivities.get(index - 1);
1983 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1984 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001985 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987 } finally {
1988 Binder.restoreCallingIdentity(origId);
1989 }
1990 }
1991
1992 @Override
1993 public void notifyActivityDrawn(IBinder token) {
1994 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1995 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001996 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001998 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 }
2000 }
2001 }
2002
2003 @Override
2004 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2005 synchronized (mGlobalLock) {
2006 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2007 if (r == null) {
2008 return;
2009 }
2010 r.reportFullyDrawnLocked(restoredFromBundle);
2011 }
2012 }
2013
2014 @Override
2015 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2016 synchronized (mGlobalLock) {
2017 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2018 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2019 return stack.mDisplayId;
2020 }
2021 return DEFAULT_DISPLAY;
2022 }
2023 }
2024
2025 @Override
2026 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002027 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 long ident = Binder.clearCallingIdentity();
2029 try {
2030 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002031 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002033 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 }
2035 return null;
2036 }
2037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
2040 }
2041
2042 @Override
2043 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002044 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2046 final long callingId = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002049 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (stack == null) {
2051 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2052 return;
2053 }
2054 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002055 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002056 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 }
2058 }
2059 } finally {
2060 Binder.restoreCallingIdentity(callingId);
2061 }
2062 }
2063
2064 @Override
2065 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2068 final long callingId = Binder.clearCallingIdentity();
2069 try {
2070 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002072 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (task == null) {
2074 return;
2075 }
2076 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002077 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002078 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 }
2080 }
2081 } finally {
2082 Binder.restoreCallingIdentity(callingId);
2083 }
2084 }
2085
2086 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002087 public void restartActivityProcessIfVisible(IBinder activityToken) {
2088 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2089 final long callingId = Binder.clearCallingIdentity();
2090 try {
2091 synchronized (mGlobalLock) {
2092 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2093 if (r == null) {
2094 return;
2095 }
2096 r.restartProcessIfVisible();
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(callingId);
2100 }
2101 }
2102
2103 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 synchronized (mGlobalLock) {
2107 final long ident = Binder.clearCallingIdentity();
2108 try {
2109 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2110 "remove-task");
2111 } finally {
2112 Binder.restoreCallingIdentity(ident);
2113 }
2114 }
2115 }
2116
2117 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002118 public void removeAllVisibleRecentTasks() {
2119 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2120 synchronized (mGlobalLock) {
2121 final long ident = Binder.clearCallingIdentity();
2122 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002123 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002124 } finally {
2125 Binder.restoreCallingIdentity(ident);
2126 }
2127 }
2128 }
2129
2130 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2132 synchronized (mGlobalLock) {
2133 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2134 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002135 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 }
2137 }
2138 return false;
2139 }
2140
2141 @Override
2142 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2143 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002144
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002145 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002146 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2147 if (r != null) {
2148 return r.getActivityStack().navigateUpToLocked(
2149 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002150 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002151 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002152 }
2153 }
2154
2155 /**
2156 * Attempts to move a task backwards in z-order (the order of activities within the task is
2157 * unchanged).
2158 *
2159 * There are several possible results of this call:
2160 * - if the task is locked, then we will show the lock toast
2161 * - if there is a task behind the provided task, then that task is made visible and resumed as
2162 * this task is moved to the back
2163 * - otherwise, if there are no other tasks in the stack:
2164 * - if this task is in the pinned stack, then we remove the stack completely, which will
2165 * have the effect of moving the task to the top or bottom of the fullscreen stack
2166 * (depending on whether it is visible)
2167 * - otherwise, we simply return home and hide this task
2168 *
2169 * @param token A reference to the activity we wish to move
2170 * @param nonRoot If false then this only works if the activity is the root
2171 * of a task; if true it will work for any activity in a task.
2172 * @return Returns true if the move completed, false if not.
2173 */
2174 @Override
2175 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002176 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 synchronized (mGlobalLock) {
2178 final long origId = Binder.clearCallingIdentity();
2179 try {
2180 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002181 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 if (task != null) {
2183 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2184 }
2185 } finally {
2186 Binder.restoreCallingIdentity(origId);
2187 }
2188 }
2189 return false;
2190 }
2191
2192 @Override
2193 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 long ident = Binder.clearCallingIdentity();
2196 Rect rect = new Rect();
2197 try {
2198 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002199 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2201 if (task == null) {
2202 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2203 return rect;
2204 }
2205 if (task.getStack() != null) {
2206 // Return the bounds from window manager since it will be adjusted for various
2207 // things like the presense of a docked stack for tasks that aren't resizeable.
2208 task.getWindowContainerBounds(rect);
2209 } else {
2210 // Task isn't in window manager yet since it isn't associated with a stack.
2211 // Return the persist value from activity manager
2212 if (!task.matchParentBounds()) {
2213 rect.set(task.getBounds());
2214 } else if (task.mLastNonFullscreenBounds != null) {
2215 rect.set(task.mLastNonFullscreenBounds);
2216 }
2217 }
2218 }
2219 } finally {
2220 Binder.restoreCallingIdentity(ident);
2221 }
2222 return rect;
2223 }
2224
2225 @Override
2226 public ActivityManager.TaskDescription getTaskDescription(int id) {
2227 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002230 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002231 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2232 if (tr != null) {
2233 return tr.lastTaskDescription;
2234 }
2235 }
2236 return null;
2237 }
2238
2239 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002240 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2241 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2242 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2243 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2244 return;
2245 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002246 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002247 synchronized (mGlobalLock) {
2248 final long ident = Binder.clearCallingIdentity();
2249 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002250 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002251 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002252 if (task == null) {
2253 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2254 return;
2255 }
2256
2257 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2258 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2259
2260 if (!task.isActivityTypeStandardOrUndefined()) {
2261 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2262 + " non-standard task " + taskId + " to windowing mode="
2263 + windowingMode);
2264 }
2265
2266 final ActivityStack stack = task.getStack();
2267 if (toTop) {
2268 stack.moveToFront("setTaskWindowingMode", task);
2269 }
2270 stack.setWindowingMode(windowingMode);
2271 } finally {
2272 Binder.restoreCallingIdentity(ident);
2273 }
2274 }
2275 }
2276
2277 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002279 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 ActivityRecord r = getCallingRecordLocked(token);
2281 return r != null ? r.info.packageName : null;
2282 }
2283 }
2284
2285 @Override
2286 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002287 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 ActivityRecord r = getCallingRecordLocked(token);
2289 return r != null ? r.intent.getComponent() : null;
2290 }
2291 }
2292
2293 private ActivityRecord getCallingRecordLocked(IBinder token) {
2294 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2295 if (r == null) {
2296 return null;
2297 }
2298 return r.resultTo;
2299 }
2300
2301 @Override
2302 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002303 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304
2305 synchronized (mGlobalLock) {
2306 final long origId = Binder.clearCallingIdentity();
2307 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002308 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 } finally {
2310 Binder.restoreCallingIdentity(origId);
2311 }
2312 }
2313 }
2314
Mark Renouf446251d2019-04-26 10:22:41 -04002315 @Override
2316 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2317 synchronized (mGlobalLock) {
2318 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2319 if (r == null) {
2320 return;
2321 }
2322 ActivityStack stack = r.getActivityStack();
2323 if (stack != null && stack.isSingleTaskInstance()) {
2324 // Single-task stacks are used for activities which are presented in floating
2325 // windows above full screen activities. Instead of directly finishing the
2326 // task, a task change listener is used to notify SystemUI so the action can be
2327 // handled specially.
2328 final TaskRecord task = r.getTaskRecord();
2329 mTaskChangeNotificationController
2330 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2331 } else {
2332 try {
2333 callback.requestFinish();
2334 } catch (RemoteException e) {
2335 Slog.e(TAG, "Failed to invoke request finish callback", e);
2336 }
2337 }
2338 }
2339 }
2340
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002341 /**
2342 * TODO: Add mController hook
2343 */
2344 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002345 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2346 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002347 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348
2349 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2350 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2352 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002353 }
2354 }
2355
Ricky Waiaca8a772019-04-04 16:01:06 +01002356 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2357 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002359
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 final int callingPid = Binder.getCallingPid();
2361 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002362 if (!isSameApp(callingUid, callingPackage)) {
2363 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2364 + Binder.getCallingPid() + " as package " + callingPackage;
2365 Slog.w(TAG, msg);
2366 throw new SecurityException(msg);
2367 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 SafeActivityOptions.abort(options);
2370 return;
2371 }
2372 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 WindowProcessController callerApp = null;
2374 if (appThread != null) {
2375 callerApp = getProcessController(appThread);
2376 }
2377 final ActivityStarter starter = getActivityStartController().obtainStarter(
2378 null /* intent */, "moveTaskToFront");
2379 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2380 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002381 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002382 return;
2383 }
2384 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002386 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 if (task == null) {
2388 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002389 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 return;
2391 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002392 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002394 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 return;
2396 }
2397 ActivityOptions realOptions = options != null
2398 ? options.getOptions(mStackSupervisor)
2399 : null;
2400 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2401 false /* forceNonResizable */);
2402
2403 final ActivityRecord topActivity = task.getTopActivity();
2404 if (topActivity != null) {
2405
2406 // We are reshowing a task, use a starting window to hide the initial draw delay
2407 // so the transition can start earlier.
2408 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2409 true /* taskSwitch */, fromRecents);
2410 }
2411 } finally {
2412 Binder.restoreCallingIdentity(origId);
2413 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 }
2415
Ricky Waiaca8a772019-04-04 16:01:06 +01002416 /**
2417 * Return true if callingUid is system, or packageName belongs to that callingUid.
2418 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002419 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002420 try {
2421 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2422 if (packageName == null) {
2423 return false;
2424 }
2425 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2426 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2427 UserHandle.getUserId(callingUid));
2428 return UserHandle.isSameApp(callingUid, uid);
2429 }
2430 } catch (RemoteException e) {
2431 // Should not happen
2432 }
2433 return true;
2434 }
2435
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002436 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2437 int callingPid, int callingUid, String name) {
2438 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2439 return true;
2440 }
2441
2442 if (getRecentTasks().isCallerRecents(sourceUid)) {
2443 return true;
2444 }
2445
2446 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2447 if (perm == PackageManager.PERMISSION_GRANTED) {
2448 return true;
2449 }
2450 if (checkAllowAppSwitchUid(sourceUid)) {
2451 return true;
2452 }
2453
2454 // If the actual IPC caller is different from the logical source, then
2455 // also see if they are allowed to control app switches.
2456 if (callingUid != -1 && callingUid != sourceUid) {
2457 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2458 if (perm == PackageManager.PERMISSION_GRANTED) {
2459 return true;
2460 }
2461 if (checkAllowAppSwitchUid(callingUid)) {
2462 return true;
2463 }
2464 }
2465
2466 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2467 return false;
2468 }
2469
2470 private boolean checkAllowAppSwitchUid(int uid) {
2471 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2472 if (types != null) {
2473 for (int i = types.size() - 1; i >= 0; i--) {
2474 if (types.valueAt(i).intValue() == uid) {
2475 return true;
2476 }
2477 }
2478 }
2479 return false;
2480 }
2481
2482 @Override
2483 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2484 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2485 "setActivityController()");
2486 synchronized (mGlobalLock) {
2487 mController = controller;
2488 mControllerIsAMonkey = imAMonkey;
2489 Watchdog.getInstance().setActivityController(controller);
2490 }
2491 }
2492
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002493 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002494 synchronized (mGlobalLock) {
2495 return mController != null && mControllerIsAMonkey;
2496 }
2497 }
2498
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002499 @Override
2500 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2501 synchronized (mGlobalLock) {
2502 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2503 }
2504 }
2505
2506 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002507 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2508 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2509 }
2510
2511 @Override
2512 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2513 @WindowConfiguration.ActivityType int ignoreActivityType,
2514 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2515 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002516 final int callingPid = Binder.getCallingPid();
2517 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002518 final int[] profileIds = getUserManager().getProfileIds(
2519 UserHandle.getUserId(callingUid), true);
2520 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2521 for (int i = 0; i < profileIds.length; i++) {
2522 callingProfileIds.add(profileIds[i]);
2523 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002524 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2525
2526 synchronized (mGlobalLock) {
2527 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2528
Nicholas Sauer0259e532019-08-30 08:24:55 -07002529 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002530 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002531 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002532 }
2533
2534 return list;
2535 }
2536
2537 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2539 synchronized (mGlobalLock) {
2540 final long origId = Binder.clearCallingIdentity();
2541 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2542 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002543 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002544 }
2545 Binder.restoreCallingIdentity(origId);
2546 }
2547 }
2548
2549 @Override
2550 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002551 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002552 ActivityStack stack = ActivityRecord.getStackLocked(token);
2553 if (stack != null) {
2554 return stack.willActivityBeVisibleLocked(token);
2555 }
2556 return false;
2557 }
2558 }
2559
2560 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002561 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002562 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 synchronized (mGlobalLock) {
2564 final long ident = Binder.clearCallingIdentity();
2565 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002566 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 if (task == null) {
2568 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2569 return;
2570 }
2571
2572 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2573 + " to stackId=" + stackId + " toTop=" + toTop);
2574
Wale Ogunwaled32da472018-11-16 07:19:28 -08002575 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576 if (stack == null) {
2577 throw new IllegalStateException(
2578 "moveTaskToStack: No stack for stackId=" + stackId);
2579 }
2580 if (!stack.isActivityTypeStandardOrUndefined()) {
2581 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2582 + taskId + " to stack " + stackId);
2583 }
2584 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002585 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2587 }
2588 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2589 "moveTaskToStack");
2590 } finally {
2591 Binder.restoreCallingIdentity(ident);
2592 }
2593 }
2594 }
2595
2596 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002597 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2598 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599
2600 final long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002603 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2604 if (stack == null) {
2605 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2606 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002608 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2609 throw new IllegalArgumentException("Stack: " + stackId
2610 + " doesn't support animated resize.");
2611 }
2612 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2613 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002614 }
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
wilsonshih5c4cf522019-01-25 09:03:47 +08002620 @Override
2621 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2622 int animationDuration) {
2623 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2624
2625 final long ident = Binder.clearCallingIdentity();
2626 try {
2627 synchronized (mGlobalLock) {
2628 if (xOffset == 0 && yOffset == 0) {
2629 return;
2630 }
2631 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2632 if (stack == null) {
2633 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2634 return;
2635 }
2636 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2637 throw new IllegalArgumentException("Stack: " + stackId
2638 + " doesn't support animated resize.");
2639 }
2640 final Rect destBounds = new Rect();
2641 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002642 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002643 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2644 return;
2645 }
2646 destBounds.offset(xOffset, yOffset);
2647 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2648 animationDuration, false /* fromFullscreen */);
2649 }
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002654 /**
2655 * Moves the specified task to the primary-split-screen stack.
2656 *
2657 * @param taskId Id of task to move.
2658 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2659 * exist already. See
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2661 * and
2662 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2663 * @param toTop If the task and stack should be moved to the top.
2664 * @param animate Whether we should play an animation for the moving the task.
2665 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2666 * stack. Pass {@code null} to use default bounds.
2667 * @param showRecents If the recents activity should be shown on the other side of the task
2668 * going into split-screen mode.
2669 */
2670 @Override
2671 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2672 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 "setTaskWindowingModeSplitScreenPrimary()");
2675 synchronized (mGlobalLock) {
2676 final long ident = Binder.clearCallingIdentity();
2677 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002678 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002679 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 if (task == null) {
2681 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2682 return false;
2683 }
2684 if (DEBUG_STACK) Slog.d(TAG_STACK,
2685 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2686 + " to createMode=" + createMode + " toTop=" + toTop);
2687 if (!task.isActivityTypeStandardOrUndefined()) {
2688 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2689 + " non-standard task " + taskId + " to split-screen windowing mode");
2690 }
2691
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002692 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 final int windowingMode = task.getWindowingMode();
2694 final ActivityStack stack = task.getStack();
2695 if (toTop) {
2696 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2697 }
2698 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002699 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2700 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 return windowingMode != task.getWindowingMode();
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706 }
2707
2708 /**
2709 * Removes stacks in the input windowing modes from the system if they are of activity type
2710 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2711 */
2712 @Override
2713 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 "removeStacksInWindowingModes()");
2716
2717 synchronized (mGlobalLock) {
2718 final long ident = Binder.clearCallingIdentity();
2719 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 } finally {
2722 Binder.restoreCallingIdentity(ident);
2723 }
2724 }
2725 }
2726
2727 @Override
2728 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002729 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 "removeStacksWithActivityTypes()");
2731
2732 synchronized (mGlobalLock) {
2733 final long ident = Binder.clearCallingIdentity();
2734 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002735 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 } finally {
2737 Binder.restoreCallingIdentity(ident);
2738 }
2739 }
2740 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741
2742 @Override
2743 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2744 int userId) {
2745 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2747 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 final boolean detailed = checkGetTasksPermission(
2750 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2751 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 == PackageManager.PERMISSION_GRANTED;
2753
2754 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002755 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 callingUid);
2757 }
2758 }
2759
2760 @Override
2761 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 long ident = Binder.clearCallingIdentity();
2764 try {
2765 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772
2773 @Override
2774 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 long ident = Binder.clearCallingIdentity();
2777 try {
2778 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002779 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 }
2781 } finally {
2782 Binder.restoreCallingIdentity(ident);
2783 }
2784 }
2785
2786 @Override
2787 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 final long callingUid = Binder.getCallingUid();
2790 final long origId = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
2793 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002794 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2796 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(origId);
2800 }
2801 }
2802
2803 @Override
2804 public void startLockTaskModeByToken(IBinder token) {
2805 synchronized (mGlobalLock) {
2806 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2807 if (r == null) {
2808 return;
2809 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002810 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 }
2812 }
2813
2814 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002815 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 // This makes inner call to look as if it was initiated by system.
2818 long ident = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002821 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002822 MATCH_TASK_IN_STACKS_ONLY);
2823 if (task == null) {
2824 return;
2825 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826
2827 // When starting lock task mode the stack must be in front and focused
2828 task.getStack().moveToFront("startSystemLockTaskMode");
2829 startLockTaskModeLocked(task, true /* isSystemCaller */);
2830 }
2831 } finally {
2832 Binder.restoreCallingIdentity(ident);
2833 }
2834 }
2835
2836 @Override
2837 public void stopLockTaskModeByToken(IBinder token) {
2838 synchronized (mGlobalLock) {
2839 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2840 if (r == null) {
2841 return;
2842 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002843 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 }
2845 }
2846
2847 /**
2848 * This API should be called by SystemUI only when user perform certain action to dismiss
2849 * lock task mode. We should only dismiss pinned lock task mode in this case.
2850 */
2851 @Override
2852 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2855 }
2856
2857 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2858 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2859 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2860 return;
2861 }
2862
Wale Ogunwaled32da472018-11-16 07:19:28 -08002863 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 if (stack == null || task != stack.topTask()) {
2865 throw new IllegalArgumentException("Invalid task, not in foreground");
2866 }
2867
2868 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2869 // system or a specific app.
2870 // * System-initiated requests will only start the pinned mode (screen pinning)
2871 // * App-initiated requests
2872 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2873 // - will start the pinned mode, otherwise
2874 final int callingUid = Binder.getCallingUid();
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002878 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002880 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 } finally {
2882 Binder.restoreCallingIdentity(ident);
2883 }
2884 }
2885
2886 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2887 final int callingUid = Binder.getCallingUid();
2888 long ident = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002891 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 }
2893 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2894 // task and jumping straight into a call in the case of emergency call back.
2895 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2896 if (tm != null) {
2897 tm.showInCallScreen(false);
2898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(ident);
2901 }
2902 }
2903
2904 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002905 public void updateLockTaskPackages(int userId, String[] packages) {
2906 final int callingUid = Binder.getCallingUid();
2907 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2908 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2909 "updateLockTaskPackages()");
2910 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002911 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002912 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2913 + Arrays.toString(packages));
2914 getLockTaskController().updateLockTaskPackages(userId, packages);
2915 }
2916 }
2917
2918 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 public boolean isInLockTaskMode() {
2920 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2921 }
2922
2923 @Override
2924 public int getLockTaskModeState() {
2925 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002926 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929
2930 @Override
2931 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2932 synchronized (mGlobalLock) {
2933 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2934 if (r != null) {
2935 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002936 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002938 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941 }
2942
2943 @Override
2944 public Bundle getActivityOptions(IBinder token) {
2945 final long origId = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
2948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2949 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002950 final ActivityOptions activityOptions = r.takeOptionsLocked(
2951 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 return activityOptions == null ? null : activityOptions.toBundle();
2953 }
2954 return null;
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(origId);
2958 }
2959 }
2960
2961 @Override
2962 public List<IBinder> getAppTasks(String callingPackage) {
2963 int callingUid = Binder.getCallingUid();
2964 long ident = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002967 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 }
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
2974 @Override
2975 public void finishVoiceTask(IVoiceInteractionSession session) {
2976 synchronized (mGlobalLock) {
2977 final long origId = Binder.clearCallingIdentity();
2978 try {
2979 // TODO: VI Consider treating local voice interactions and voice tasks
2980 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002981 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 } finally {
2983 Binder.restoreCallingIdentity(origId);
2984 }
2985 }
2986
2987 }
2988
2989 @Override
2990 public boolean isTopOfTask(IBinder token) {
2991 synchronized (mGlobalLock) {
2992 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002993 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 }
2996
2997 @Override
2998 public void notifyLaunchTaskBehindComplete(IBinder token) {
2999 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3000 }
3001
3002 @Override
3003 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003004 mH.post(() -> {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003009 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 } catch (RemoteException e) {
3011 }
3012 }
3013 }
3014
3015 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 }
3017
3018 /** Called from an app when assist data is ready. */
3019 @Override
3020 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3021 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003022 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 synchronized (pae) {
3024 pae.result = extras;
3025 pae.structure = structure;
3026 pae.content = content;
3027 if (referrer != null) {
3028 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3029 }
3030 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003031 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003032 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3033 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 structure.setHomeActivity(pae.isHome);
3035 }
3036 pae.haveResult = true;
3037 pae.notifyAll();
3038 if (pae.intent == null && pae.receiver == null) {
3039 // Caller is just waiting for the result.
3040 return;
3041 }
3042 }
3043 // We are now ready to launch the assist activity.
3044 IAssistDataReceiver sendReceiver = null;
3045 Bundle sendBundle = null;
3046 synchronized (mGlobalLock) {
3047 buildAssistBundleLocked(pae, extras);
3048 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003049 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 if (!exists) {
3051 // Timed out.
3052 return;
3053 }
3054
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 // Caller wants result sent back to them.
3057 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003058 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3059 pae.activity.getTaskRecord().taskId);
3060 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3061 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3063 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3064 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3065 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3066 }
3067 }
3068 if (sendReceiver != null) {
3069 try {
3070 sendReceiver.onHandleAssistData(sendBundle);
3071 } catch (RemoteException e) {
3072 }
3073 return;
3074 }
3075
3076 final long ident = Binder.clearCallingIdentity();
3077 try {
3078 if (TextUtils.equals(pae.intent.getAction(),
3079 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003080 // Start voice interaction through VoiceInteractionManagerService.
3081 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3082 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 } else {
3084 pae.intent.replaceExtras(pae.extras);
3085 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3086 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3087 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003088 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089
3090 try {
3091 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3092 } catch (ActivityNotFoundException e) {
3093 Slog.w(TAG, "No activity to handle assist action.", e);
3094 }
3095 }
3096 } finally {
3097 Binder.restoreCallingIdentity(ident);
3098 }
3099 }
3100
3101 @Override
3102 public int addAppTask(IBinder activityToken, Intent intent,
3103 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3104 final int callingUid = Binder.getCallingUid();
3105 final long callingIdent = Binder.clearCallingIdentity();
3106
3107 try {
3108 synchronized (mGlobalLock) {
3109 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3110 if (r == null) {
3111 throw new IllegalArgumentException("Activity does not exist; token="
3112 + activityToken);
3113 }
3114 ComponentName comp = intent.getComponent();
3115 if (comp == null) {
3116 throw new IllegalArgumentException("Intent " + intent
3117 + " must specify explicit component");
3118 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003119 if (thumbnail.getWidth() != mThumbnailWidth
3120 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 throw new IllegalArgumentException("Bad thumbnail size: got "
3122 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 }
3125 if (intent.getSelector() != null) {
3126 intent.setSelector(null);
3127 }
3128 if (intent.getSourceBounds() != null) {
3129 intent.setSourceBounds(null);
3130 }
3131 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3132 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3133 // The caller has added this as an auto-remove task... that makes no
3134 // sense, so turn off auto-remove.
3135 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3136 }
3137 }
3138 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3139 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3140 if (ainfo.applicationInfo.uid != callingUid) {
3141 throw new SecurityException(
3142 "Can't add task for another application: target uid="
3143 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3144 }
3145
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003146 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003148 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003150 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 // The app has too many tasks already and we can't add any more
3152 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3153 return INVALID_TASK_ID;
3154 }
3155 task.lastTaskDescription.copyFrom(description);
3156
3157 // TODO: Send the thumbnail to WM to store it.
3158
3159 return task.taskId;
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(callingIdent);
3163 }
3164 }
3165
3166 @Override
3167 public Point getAppTaskThumbnailSize() {
3168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003169 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 }
3171 }
3172
3173 @Override
3174 public void setTaskResizeable(int taskId, int resizeableMode) {
3175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003176 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3178 if (task == null) {
3179 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3180 return;
3181 }
3182 task.setResizeMode(resizeableMode);
3183 }
3184 }
3185
3186 @Override
3187 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 long ident = Binder.clearCallingIdentity();
3190 try {
3191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003192 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003193 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 if (task == null) {
3195 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3196 return;
3197 }
3198 // Place the task in the right stack if it isn't there already based on
3199 // the requested bounds.
3200 // The stack transition logic is:
3201 // - a null bounds on a freeform task moves that task to fullscreen
3202 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3203 // that task to freeform
3204 // - otherwise the task is not moved
3205 ActivityStack stack = task.getStack();
3206 if (!task.getWindowConfiguration().canResizeTask()) {
3207 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3208 }
3209 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3210 stack = stack.getDisplay().getOrCreateStack(
3211 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3212 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3213 stack = stack.getDisplay().getOrCreateStack(
3214 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3215 }
3216
3217 // Reparent the task to the right stack if necessary
3218 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3219 if (stack != task.getStack()) {
3220 // Defer resume until the task is resized below
3221 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3222 DEFER_RESUME, "resizeTask");
3223 preserveWindow = false;
3224 }
3225
3226 // After reparenting (which only resizes the task to the stack bounds), resize the
3227 // task to the actual bounds provided
3228 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3229 }
3230 } finally {
3231 Binder.restoreCallingIdentity(ident);
3232 }
3233 }
3234
3235 @Override
3236 public boolean releaseActivityInstance(IBinder token) {
3237 synchronized (mGlobalLock) {
3238 final long origId = Binder.clearCallingIdentity();
3239 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003240 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3241 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 return false;
3243 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003244 r.destroyImmediately(true /* removeFromApp */, "app-req");
3245 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 } finally {
3247 Binder.restoreCallingIdentity(origId);
3248 }
3249 }
3250 }
3251
3252 @Override
3253 public void releaseSomeActivities(IApplicationThread appInt) {
3254 synchronized (mGlobalLock) {
3255 final long origId = Binder.clearCallingIdentity();
3256 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003257 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003258 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 } finally {
3260 Binder.restoreCallingIdentity(origId);
3261 }
3262 }
3263 }
3264
3265 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003266 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003267 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 != PackageManager.PERMISSION_GRANTED) {
3269 throw new SecurityException("Requires permission "
3270 + android.Manifest.permission.DEVICE_POWER);
3271 }
3272
3273 synchronized (mGlobalLock) {
3274 long ident = Binder.clearCallingIdentity();
3275 if (mKeyguardShown != keyguardShowing) {
3276 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003277 final Message msg = PooledLambda.obtainMessage(
3278 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3279 keyguardShowing);
3280 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 }
3282 try {
wilsonshih177261f2019-02-22 12:02:18 +08003283 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 } finally {
3285 Binder.restoreCallingIdentity(ident);
3286 }
3287 }
3288
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003289 mH.post(() -> {
3290 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3291 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3292 }
3293 });
3294 }
3295
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003296 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003297 mH.post(() -> {
3298 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3299 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3300 }
3301 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 }
3303
3304 @Override
3305 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003306 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3307 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308
3309 final File passedIconFile = new File(filePath);
3310 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3311 passedIconFile.getName());
3312 if (!legitIconFile.getPath().equals(filePath)
3313 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3314 throw new IllegalArgumentException("Bad file path: " + filePath
3315 + " passed for userId " + userId);
3316 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003317 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 }
3319
3320 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003321 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3323 final ActivityOptions activityOptions = safeOptions != null
3324 ? safeOptions.getOptions(mStackSupervisor)
3325 : null;
3326 if (activityOptions == null
3327 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3328 || activityOptions.getCustomInPlaceResId() == 0) {
3329 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3330 "with valid animation");
3331 }
lumark588a3e82018-07-20 18:53:54 +08003332 // Get top display of front most application.
3333 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3334 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003335 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3336 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3337 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003338 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003339 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003340 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 }
3342
3343 @Override
3344 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003345 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 synchronized (mGlobalLock) {
3347 final long ident = Binder.clearCallingIdentity();
3348 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003349 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 if (stack == null) {
3351 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3352 return;
3353 }
3354 if (!stack.isActivityTypeStandardOrUndefined()) {
3355 throw new IllegalArgumentException(
3356 "Removing non-standard stack is not allowed.");
3357 }
3358 mStackSupervisor.removeStack(stack);
3359 } finally {
3360 Binder.restoreCallingIdentity(ident);
3361 }
3362 }
3363 }
3364
3365 @Override
3366 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003367 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 synchronized (mGlobalLock) {
3370 final long ident = Binder.clearCallingIdentity();
3371 try {
3372 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3373 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003374 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379 }
3380
3381 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003382 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 synchronized (mGlobalLock) {
3384 long ident = Binder.clearCallingIdentity();
3385 try {
3386 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3387 if (r == null) {
3388 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003389 "toggleFreeformWindowingMode: No activity record matching token="
3390 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003393 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003394 if (stack == null) {
3395 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3396 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 }
3398
Yunfan Chend967af82019-01-17 18:30:18 +09003399 if (!stack.inFreeformWindowingMode()
3400 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3401 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3402 + "toggle between fullscreen and freeform.");
3403 }
3404
3405 if (stack.inFreeformWindowingMode()) {
3406 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003407 } else if (stack.getParent().inFreeformWindowingMode()) {
3408 // If the window is on a freeform display, set it to undefined. It will be
3409 // resolved to freeform and it can adjust windowing mode when the display mode
3410 // changes in runtime.
3411 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003412 } else {
3413 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3414 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 } finally {
3416 Binder.restoreCallingIdentity(ident);
3417 }
3418 }
3419 }
3420
3421 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3422 @Override
3423 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003426 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 }
3428
3429 /** Unregister a task stack listener so that it stops receiving callbacks. */
3430 @Override
3431 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003434 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 }
3436
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 @Override
3438 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3439 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3440 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3441 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3442 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3443 }
3444
3445 @Override
3446 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3447 IBinder activityToken, int flags) {
3448 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3449 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3450 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3451 }
3452
3453 @Override
3454 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3455 Bundle args) {
3456 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3457 true /* focused */, true /* newSessionId */, userHandle, args,
3458 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3459 }
3460
3461 @Override
3462 public Bundle getAssistContextExtras(int requestType) {
3463 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3464 null, null, true /* focused */, true /* newSessionId */,
3465 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3466 if (pae == null) {
3467 return null;
3468 }
3469 synchronized (pae) {
3470 while (!pae.haveResult) {
3471 try {
3472 pae.wait();
3473 } catch (InterruptedException e) {
3474 }
3475 }
3476 }
3477 synchronized (mGlobalLock) {
3478 buildAssistBundleLocked(pae, pae.result);
3479 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003480 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 }
3482 return pae.extras;
3483 }
3484
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003485 /**
3486 * Binder IPC calls go through the public entry point.
3487 * This can be called with or without the global lock held.
3488 */
3489 private static int checkCallingPermission(String permission) {
3490 return checkPermission(
3491 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3492 }
3493
3494 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003495 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003496 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3497 mAmInternal.enforceCallingPermission(permission, func);
3498 }
3499 }
3500
3501 @VisibleForTesting
3502 int checkGetTasksPermission(String permission, int pid, int uid) {
3503 return checkPermission(permission, pid, uid);
3504 }
3505
3506 static int checkPermission(String permission, int pid, int uid) {
3507 if (permission == null) {
3508 return PackageManager.PERMISSION_DENIED;
3509 }
3510 return checkComponentPermission(permission, pid, uid, -1, true);
3511 }
3512
Wale Ogunwale214f3482018-10-04 11:00:47 -07003513 public static int checkComponentPermission(String permission, int pid, int uid,
3514 int owningUid, boolean exported) {
3515 return ActivityManagerService.checkComponentPermission(
3516 permission, pid, uid, owningUid, exported);
3517 }
3518
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003519 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3520 if (getRecentTasks().isCallerRecents(callingUid)) {
3521 // Always allow the recents component to get tasks
3522 return true;
3523 }
3524
3525 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3526 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3527 if (!allowed) {
3528 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3529 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3530 // Temporary compatibility: some existing apps on the system image may
3531 // still be requesting the old permission and not switched to the new
3532 // one; if so, we'll still allow them full access. This means we need
3533 // to see if they are holding the old permission and are a system app.
3534 try {
3535 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3536 allowed = true;
3537 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3538 + " is using old GET_TASKS but privileged; allowing");
3539 }
3540 } catch (RemoteException e) {
3541 }
3542 }
3543 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3544 + " does not hold REAL_GET_TASKS; limiting output");
3545 }
3546 return allowed;
3547 }
3548
Nicholas Sauer0259e532019-08-30 08:24:55 -07003549 boolean isCrossUserAllowed(int pid, int uid) {
3550 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3551 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3555 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3556 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3557 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003558 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 "enqueueAssistContext()");
3560
3561 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003562 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 if (activity == null) {
3564 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3565 return null;
3566 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003567 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003568 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3569 return null;
3570 }
3571 if (focused) {
3572 if (activityToken != null) {
3573 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3574 if (activity != caller) {
3575 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3576 + " is not current top " + activity);
3577 return null;
3578 }
3579 }
3580 } else {
3581 activity = ActivityRecord.forTokenLocked(activityToken);
3582 if (activity == null) {
3583 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3584 + " couldn't be found");
3585 return null;
3586 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003587 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3589 return null;
3590 }
3591 }
3592
3593 PendingAssistExtras pae;
3594 Bundle extras = new Bundle();
3595 if (args != null) {
3596 extras.putAll(args);
3597 }
3598 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600
3601 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3602 userHandle);
3603 pae.isHome = activity.isActivityTypeHome();
3604
3605 // Increment the sessionId if necessary
3606 if (newSessionId) {
3607 mViSessionId++;
3608 }
3609 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003610 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3611 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003613 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 } catch (RemoteException e) {
3615 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3616 return null;
3617 }
3618 return pae;
3619 }
3620 }
3621
3622 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3623 if (result != null) {
3624 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3625 }
3626 if (pae.hint != null) {
3627 pae.extras.putBoolean(pae.hint, true);
3628 }
3629 }
3630
3631 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3632 IAssistDataReceiver receiver;
3633 synchronized (mGlobalLock) {
3634 mPendingAssistExtras.remove(pae);
3635 receiver = pae.receiver;
3636 }
3637 if (receiver != null) {
3638 // Caller wants result sent back to them.
3639 Bundle sendBundle = new Bundle();
3640 // At least return the receiver extras
3641 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3642 try {
3643 pae.receiver.onHandleAssistData(sendBundle);
3644 } catch (RemoteException e) {
3645 }
3646 }
3647 }
3648
3649 public class PendingAssistExtras extends Binder implements Runnable {
3650 public final ActivityRecord activity;
3651 public boolean isHome;
3652 public final Bundle extras;
3653 public final Intent intent;
3654 public final String hint;
3655 public final IAssistDataReceiver receiver;
3656 public final int userHandle;
3657 public boolean haveResult = false;
3658 public Bundle result = null;
3659 public AssistStructure structure = null;
3660 public AssistContent content = null;
3661 public Bundle receiverExtras;
3662
3663 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3664 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3665 int _userHandle) {
3666 activity = _activity;
3667 extras = _extras;
3668 intent = _intent;
3669 hint = _hint;
3670 receiver = _receiver;
3671 receiverExtras = _receiverExtras;
3672 userHandle = _userHandle;
3673 }
3674
3675 @Override
3676 public void run() {
3677 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3678 synchronized (this) {
3679 haveResult = true;
3680 notifyAll();
3681 }
3682 pendingAssistExtrasTimedOut(this);
3683 }
3684 }
3685
3686 @Override
3687 public boolean isAssistDataAllowedOnCurrentActivity() {
3688 int userId;
3689 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003690 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3692 return false;
3693 }
3694
3695 final ActivityRecord activity = focusedStack.getTopActivity();
3696 if (activity == null) {
3697 return false;
3698 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003699 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003700 }
3701 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3702 }
3703
3704 @Override
3705 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3706 long ident = Binder.clearCallingIdentity();
3707 try {
3708 synchronized (mGlobalLock) {
3709 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003710 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 if (top != caller) {
3712 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3713 + " is not current top " + top);
3714 return false;
3715 }
3716 if (!top.nowVisible) {
3717 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3718 + " is not visible");
3719 return false;
3720 }
3721 }
3722 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3723 token);
3724 } finally {
3725 Binder.restoreCallingIdentity(ident);
3726 }
3727 }
3728
3729 @Override
3730 public boolean isRootVoiceInteraction(IBinder token) {
3731 synchronized (mGlobalLock) {
3732 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3733 if (r == null) {
3734 return false;
3735 }
3736 return r.rootVoiceInteraction;
3737 }
3738 }
3739
Wale Ogunwalef6733932018-06-27 05:14:34 -07003740 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3741 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3742 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3743 if (activityToCallback == null) return;
3744 activityToCallback.setVoiceSessionLocked(voiceSession);
3745
3746 // Inform the activity
3747 try {
3748 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3749 voiceInteractor);
3750 long token = Binder.clearCallingIdentity();
3751 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003752 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003753 } finally {
3754 Binder.restoreCallingIdentity(token);
3755 }
3756 // TODO: VI Should we cache the activity so that it's easier to find later
3757 // rather than scan through all the stacks and activities?
3758 } catch (RemoteException re) {
3759 activityToCallback.clearVoiceSessionLocked();
3760 // TODO: VI Should this terminate the voice session?
3761 }
3762 }
3763
3764 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3765 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3766 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3767 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3768 boolean wasRunningVoice = mRunningVoice != null;
3769 mRunningVoice = session;
3770 if (!wasRunningVoice) {
3771 mVoiceWakeLock.acquire();
3772 updateSleepIfNeededLocked();
3773 }
3774 }
3775 }
3776
3777 void finishRunningVoiceLocked() {
3778 if (mRunningVoice != null) {
3779 mRunningVoice = null;
3780 mVoiceWakeLock.release();
3781 updateSleepIfNeededLocked();
3782 }
3783 }
3784
3785 @Override
3786 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3787 synchronized (mGlobalLock) {
3788 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3789 if (keepAwake) {
3790 mVoiceWakeLock.acquire();
3791 } else {
3792 mVoiceWakeLock.release();
3793 }
3794 }
3795 }
3796 }
3797
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003798 @Override
3799 public ComponentName getActivityClassForToken(IBinder token) {
3800 synchronized (mGlobalLock) {
3801 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3802 if (r == null) {
3803 return null;
3804 }
3805 return r.intent.getComponent();
3806 }
3807 }
3808
3809 @Override
3810 public String getPackageForToken(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3813 if (r == null) {
3814 return null;
3815 }
3816 return r.packageName;
3817 }
3818 }
3819
3820 @Override
3821 public void showLockTaskEscapeMessage(IBinder token) {
3822 synchronized (mGlobalLock) {
3823 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3824 if (r == null) {
3825 return;
3826 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003827 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 }
3829 }
3830
3831 @Override
3832 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003833 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 final long token = Binder.clearCallingIdentity();
3835 try {
3836 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003837 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839 } finally {
3840 Binder.restoreCallingIdentity(token);
3841 }
3842 }
3843
3844 /**
3845 * Try to place task to provided position. The final position might be different depending on
3846 * current user and stacks state. The task will be moved to target stack if it's currently in
3847 * different stack.
3848 */
3849 @Override
3850 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003851 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 synchronized (mGlobalLock) {
3853 long ident = Binder.clearCallingIdentity();
3854 try {
3855 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3856 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003857 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 if (task == null) {
3859 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3860 + taskId);
3861 }
3862
Wale Ogunwaled32da472018-11-16 07:19:28 -08003863 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864
3865 if (stack == null) {
3866 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3867 + stackId);
3868 }
3869 if (!stack.isActivityTypeStandardOrUndefined()) {
3870 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3871 + " the position of task " + taskId + " in/to non-standard stack");
3872 }
3873
3874 // TODO: Have the callers of this API call a separate reparent method if that is
3875 // what they intended to do vs. having this method also do reparenting.
3876 if (task.getStack() == stack) {
3877 // Change position in current stack.
3878 stack.positionChildAt(task, position);
3879 } else {
3880 // Reparent to new stack.
3881 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3882 !DEFER_RESUME, "positionTaskInStack");
3883 }
3884 } finally {
3885 Binder.restoreCallingIdentity(ident);
3886 }
3887 }
3888 }
3889
3890 @Override
3891 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3892 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3893 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003894 + Arrays.toString(horizontalSizeConfiguration) + " "
3895 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 synchronized (mGlobalLock) {
3897 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3898 if (record == null) {
3899 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3900 + "found for: " + token);
3901 }
3902 record.setSizeConfigurations(horizontalSizeConfiguration,
3903 verticalSizeConfigurations, smallestSizeConfigurations);
3904 }
3905 }
3906
3907 /**
3908 * Dismisses split-screen multi-window mode.
3909 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3910 */
3911 @Override
3912 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003913 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003914 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3915 final long ident = Binder.clearCallingIdentity();
3916 try {
3917 synchronized (mGlobalLock) {
3918 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003919 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 if (stack == null) {
3921 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3922 return;
3923 }
3924
3925 if (toTop) {
3926 // Caller wants the current split-screen primary stack to be the top stack after
3927 // it goes fullscreen, so move it to the front.
3928 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003929 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003931 // stack after it goes fullscreen, so we move the focus to the top-most
3932 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3934 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3935 if (otherStack != null) {
3936 otherStack.moveToFront("dismissSplitScreenMode_other");
3937 }
3938 }
3939
Evan Rosky10475742018-09-05 19:02:48 -07003940 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 }
3942 } finally {
3943 Binder.restoreCallingIdentity(ident);
3944 }
3945 }
3946
3947 /**
3948 * Dismisses Pip
3949 * @param animate True if the dismissal should be animated.
3950 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3951 * default animation duration should be used.
3952 */
3953 @Override
3954 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003955 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 final long ident = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003959 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003960 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 if (stack == null) {
3962 Slog.w(TAG, "dismissPip: pinned stack not found.");
3963 return;
3964 }
3965 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3966 throw new IllegalArgumentException("Stack: " + stack
3967 + " doesn't support animated resize.");
3968 }
3969 if (animate) {
3970 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3971 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3972 } else {
3973 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3974 }
3975 }
3976 } finally {
3977 Binder.restoreCallingIdentity(ident);
3978 }
3979 }
3980
3981 @Override
3982 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 synchronized (mGlobalLock) {
3985 mSuppressResizeConfigChanges = suppress;
3986 }
3987 }
3988
3989 /**
3990 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3991 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3992 * activity and clearing the task at the same time.
3993 */
3994 @Override
3995 // TODO: API should just be about changing windowing modes...
3996 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003997 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 "moveTasksToFullscreenStack()");
3999 synchronized (mGlobalLock) {
4000 final long origId = Binder.clearCallingIdentity();
4001 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004002 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 if (stack != null){
4004 if (!stack.isActivityTypeStandardOrUndefined()) {
4005 throw new IllegalArgumentException(
4006 "You can't move tasks from non-standard stacks.");
4007 }
4008 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4009 }
4010 } finally {
4011 Binder.restoreCallingIdentity(origId);
4012 }
4013 }
4014 }
4015
4016 /**
4017 * Moves the top activity in the input stackId to the pinned stack.
4018 *
4019 * @param stackId Id of stack to move the top activity to pinned stack.
4020 * @param bounds Bounds to use for pinned stack.
4021 *
4022 * @return True if the top activity of the input stack was successfully moved to the pinned
4023 * stack.
4024 */
4025 @Override
4026 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 "moveTopActivityToPinnedStack()");
4029 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4032 + "Device doesn't support picture-in-picture mode");
4033 }
4034
4035 long ident = Binder.clearCallingIdentity();
4036 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004037 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 } finally {
4039 Binder.restoreCallingIdentity(ident);
4040 }
4041 }
4042 }
4043
4044 @Override
4045 public boolean isInMultiWindowMode(IBinder token) {
4046 final long origId = Binder.clearCallingIdentity();
4047 try {
4048 synchronized (mGlobalLock) {
4049 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4050 if (r == null) {
4051 return false;
4052 }
4053 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4054 return r.inMultiWindowMode();
4055 }
4056 } finally {
4057 Binder.restoreCallingIdentity(origId);
4058 }
4059 }
4060
4061 @Override
4062 public boolean isInPictureInPictureMode(IBinder token) {
4063 final long origId = Binder.clearCallingIdentity();
4064 try {
4065 synchronized (mGlobalLock) {
4066 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4067 }
4068 } finally {
4069 Binder.restoreCallingIdentity(origId);
4070 }
4071 }
4072
4073 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004074 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4075 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 return false;
4077 }
4078
4079 // If we are animating to fullscreen then we have already dispatched the PIP mode
4080 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004081 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4082 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 }
4084
4085 @Override
4086 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4087 final long origId = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4091 "enterPictureInPictureMode", token, params);
4092
4093 // If the activity is already in picture in picture mode, then just return early
4094 if (isInPictureInPictureMode(r)) {
4095 return true;
4096 }
4097
4098 // Activity supports picture-in-picture, now check that we can enter PiP at this
4099 // point, if it is
4100 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4101 false /* beforeStopping */)) {
4102 return false;
4103 }
4104
4105 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 synchronized (mGlobalLock) {
4107 // Only update the saved args from the args that are set
4108 r.pictureInPictureArgs.copyOnlySet(params);
4109 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4110 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4111 // Adjust the source bounds by the insets for the transition down
4112 final Rect sourceBounds = new Rect(
4113 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004114 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004116 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004117 stack.setPictureInPictureAspectRatio(aspectRatio);
4118 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004119 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4120 r.info.applicationInfo.uid, r.shortComponentName,
4121 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 logPictureInPictureArgs(params);
4123 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 };
4125
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 // If the keyguard is showing or occluded, then try and dismiss it before
4128 // entering picture-in-picture (this will prompt the user to authenticate if the
4129 // device is currently locked).
4130 dismissKeyguard(token, new KeyguardDismissCallback() {
4131 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004132 public void onDismissSucceeded() {
4133 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 }
4135 }, null /* message */);
4136 } else {
4137 // Enter picture in picture immediately otherwise
4138 enterPipRunnable.run();
4139 }
4140 return true;
4141 }
4142 } finally {
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146
4147 @Override
4148 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4149 final long origId = Binder.clearCallingIdentity();
4150 try {
4151 synchronized (mGlobalLock) {
4152 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4153 "setPictureInPictureParams", token, params);
4154
4155 // Only update the saved args from the args that are set
4156 r.pictureInPictureArgs.copyOnlySet(params);
4157 if (r.inPinnedWindowingMode()) {
4158 // If the activity is already in picture-in-picture, update the pinned stack now
4159 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4160 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004161 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 if (!stack.isAnimatingBoundsToFullscreen()) {
4163 stack.setPictureInPictureAspectRatio(
4164 r.pictureInPictureArgs.getAspectRatio());
4165 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4166 }
4167 }
4168 logPictureInPictureArgs(params);
4169 }
4170 } finally {
4171 Binder.restoreCallingIdentity(origId);
4172 }
4173 }
4174
4175 @Override
4176 public int getMaxNumPictureInPictureActions(IBinder token) {
4177 // Currently, this is a static constant, but later, we may change this to be dependent on
4178 // the context of the activity
4179 return 3;
4180 }
4181
4182 private void logPictureInPictureArgs(PictureInPictureParams params) {
4183 if (params.hasSetActions()) {
4184 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4185 params.getActions().size());
4186 }
4187 if (params.hasSetAspectRatio()) {
4188 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4189 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4190 MetricsLogger.action(lm);
4191 }
4192 }
4193
4194 /**
4195 * Checks the state of the system and the activity associated with the given {@param token} to
4196 * verify that picture-in-picture is supported for that activity.
4197 *
4198 * @return the activity record for the given {@param token} if all the checks pass.
4199 */
4200 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4201 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004202 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 throw new IllegalStateException(caller
4204 + ": Device doesn't support picture-in-picture mode.");
4205 }
4206
4207 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4208 if (r == null) {
4209 throw new IllegalStateException(caller
4210 + ": Can't find activity for token=" + token);
4211 }
4212
4213 if (!r.supportsPictureInPicture()) {
4214 throw new IllegalStateException(caller
4215 + ": Current activity does not support picture-in-picture.");
4216 }
4217
4218 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004219 && !mWindowManager.isValidPictureInPictureAspectRatio(
4220 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 final float minAspectRatio = mContext.getResources().getFloat(
4222 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4223 final float maxAspectRatio = mContext.getResources().getFloat(
4224 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4225 throw new IllegalArgumentException(String.format(caller
4226 + ": Aspect ratio is too extreme (must be between %f and %f).",
4227 minAspectRatio, maxAspectRatio));
4228 }
4229
4230 // Truncate the number of actions if necessary
4231 params.truncateActions(getMaxNumPictureInPictureActions(token));
4232
4233 return r;
4234 }
4235
4236 @Override
4237 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004238 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 synchronized (mGlobalLock) {
4240 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4241 if (r == null) {
4242 throw new IllegalArgumentException("Activity does not exist; token="
4243 + activityToken);
4244 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004245 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 }
4247 }
4248
4249 @Override
4250 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4251 Rect tempDockedTaskInsetBounds,
4252 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 long ident = Binder.clearCallingIdentity();
4255 try {
4256 synchronized (mGlobalLock) {
4257 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4258 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4259 PRESERVE_WINDOWS);
4260 }
4261 } finally {
4262 Binder.restoreCallingIdentity(ident);
4263 }
4264 }
4265
4266 @Override
4267 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 final long ident = Binder.clearCallingIdentity();
4270 try {
4271 synchronized (mGlobalLock) {
4272 mStackSupervisor.setSplitScreenResizing(resizing);
4273 }
4274 } finally {
4275 Binder.restoreCallingIdentity(ident);
4276 }
4277 }
4278
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004279 /**
4280 * Check that we have the features required for VR-related API calls, and throw an exception if
4281 * not.
4282 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004283 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 if (!mContext.getPackageManager().hasSystemFeature(
4285 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4286 throw new UnsupportedOperationException("VR mode not supported on this device!");
4287 }
4288 }
4289
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290 @Override
4291 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293
4294 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4295
4296 ActivityRecord r;
4297 synchronized (mGlobalLock) {
4298 r = ActivityRecord.isInStackLocked(token);
4299 }
4300
4301 if (r == null) {
4302 throw new IllegalArgumentException();
4303 }
4304
4305 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004306 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 VrManagerInternal.NO_ERROR) {
4308 return err;
4309 }
4310
4311 // Clear the binder calling uid since this path may call moveToTask().
4312 final long callingId = Binder.clearCallingIdentity();
4313 try {
4314 synchronized (mGlobalLock) {
4315 r.requestedVrComponent = (enabled) ? packageName : null;
4316
4317 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004318 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004319 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 }
4321 return 0;
4322 }
4323 } finally {
4324 Binder.restoreCallingIdentity(callingId);
4325 }
4326 }
4327
4328 @Override
4329 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4330 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4331 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004332 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4334 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4335 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004336 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 || activity.voiceSession != null) {
4338 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4339 return;
4340 }
4341 if (activity.pendingVoiceInteractionStart) {
4342 Slog.w(TAG, "Pending start of voice interaction already.");
4343 return;
4344 }
4345 activity.pendingVoiceInteractionStart = true;
4346 }
4347 LocalServices.getService(VoiceInteractionManagerInternal.class)
4348 .startLocalVoiceInteraction(callingActivity, options);
4349 }
4350
4351 @Override
4352 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4353 LocalServices.getService(VoiceInteractionManagerInternal.class)
4354 .stopLocalVoiceInteraction(callingActivity);
4355 }
4356
4357 @Override
4358 public boolean supportsLocalVoiceInteraction() {
4359 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4360 .supportsLocalVoiceInteraction();
4361 }
4362
4363 /** Notifies all listeners when the pinned stack animation starts. */
4364 @Override
4365 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004366 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368
4369 /** Notifies all listeners when the pinned stack animation ends. */
4370 @Override
4371 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374
4375 @Override
4376 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 final long ident = Binder.clearCallingIdentity();
4379 try {
4380 synchronized (mGlobalLock) {
4381 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4382 }
4383 } finally {
4384 Binder.restoreCallingIdentity(ident);
4385 }
4386 }
4387
4388 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391
4392 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004393 if (mWindowManager == null) {
4394 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4395 return false;
4396 }
4397
4398 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 }
4402
Riddle Hsua0022cd2019-09-09 21:12:41 +08004403 mH.sendMessage(PooledLambda.obtainMessage(
4404 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4405 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406
4407 final long origId = Binder.clearCallingIdentity();
4408 try {
4409 if (values != null) {
4410 Settings.System.clearConfiguration(values);
4411 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 UserHandle.USER_NULL, false /* deferResume */,
4414 mTmpUpdateConfigurationResult);
4415 return mTmpUpdateConfigurationResult.changes != 0;
4416 } finally {
4417 Binder.restoreCallingIdentity(origId);
4418 }
4419 }
4420 }
4421
4422 @Override
4423 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4424 CharSequence message) {
4425 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4428 }
4429 final long callingId = Binder.clearCallingIdentity();
4430 try {
4431 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004432 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 }
4434 } finally {
4435 Binder.restoreCallingIdentity(callingId);
4436 }
4437 }
4438
4439 @Override
4440 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 "cancelTaskWindowTransition()");
4443 final long ident = Binder.clearCallingIdentity();
4444 try {
4445 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004446 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 MATCH_TASK_IN_STACKS_ONLY);
4448 if (task == null) {
4449 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4450 return;
4451 }
4452 task.cancelWindowTransition();
4453 }
4454 } finally {
4455 Binder.restoreCallingIdentity(ident);
4456 }
4457 }
4458
4459 @Override
4460 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 final long ident = Binder.clearCallingIdentity();
4463 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004464 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 } finally {
4466 Binder.restoreCallingIdentity(ident);
4467 }
4468 }
4469
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004470 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4471 boolean restoreFromDisk) {
4472 final TaskRecord task;
4473 synchronized (mGlobalLock) {
4474 task = mRootActivityContainer.anyTaskForId(taskId,
4475 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4476 if (task == null) {
4477 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4478 return null;
4479 }
4480 }
4481 // Don't call this while holding the lock as this operation might hit the disk.
4482 return task.getSnapshot(reducedResolution, restoreFromDisk);
4483 }
4484
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 @Override
4486 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4487 synchronized (mGlobalLock) {
4488 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4489 if (r == null) {
4490 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4491 + token);
4492 return;
4493 }
4494 final long origId = Binder.clearCallingIdentity();
4495 try {
4496 r.setDisablePreviewScreenshots(disable);
4497 } finally {
4498 Binder.restoreCallingIdentity(origId);
4499 }
4500 }
4501 }
4502
4503 /** Return the user id of the last resumed activity. */
4504 @Override
4505 public @UserIdInt
4506 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4509 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004510 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004511 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004512 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004513 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 }
4515 }
4516
4517 @Override
4518 public void updateLockTaskFeatures(int userId, int flags) {
4519 final int callingUid = Binder.getCallingUid();
4520 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 "updateLockTaskFeatures()");
4523 }
4524 synchronized (mGlobalLock) {
4525 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4526 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004527 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528 }
4529 }
4530
4531 @Override
4532 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4533 synchronized (mGlobalLock) {
4534 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4535 if (r == null) {
4536 return;
4537 }
4538 final long origId = Binder.clearCallingIdentity();
4539 try {
4540 r.setShowWhenLocked(showWhenLocked);
4541 } finally {
4542 Binder.restoreCallingIdentity(origId);
4543 }
4544 }
4545 }
4546
4547 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004548 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4549 synchronized (mGlobalLock) {
4550 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4551 if (r == null) {
4552 return;
4553 }
4554 final long origId = Binder.clearCallingIdentity();
4555 try {
4556 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4557 } finally {
4558 Binder.restoreCallingIdentity(origId);
4559 }
4560 }
4561 }
4562
4563 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4565 synchronized (mGlobalLock) {
4566 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4567 if (r == null) {
4568 return;
4569 }
4570 final long origId = Binder.clearCallingIdentity();
4571 try {
4572 r.setTurnScreenOn(turnScreenOn);
4573 } finally {
4574 Binder.restoreCallingIdentity(origId);
4575 }
4576 }
4577 }
4578
4579 @Override
4580 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004581 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004583 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004584 synchronized (mGlobalLock) {
4585 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4586 if (r == null) {
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.registerRemoteAnimations(definition);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
4598 @Override
4599 public void registerRemoteAnimationForNextActivityStart(String packageName,
4600 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004601 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004602 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004603 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004604 synchronized (mGlobalLock) {
4605 final long origId = Binder.clearCallingIdentity();
4606 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004607 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 packageName, adapter);
4609 } finally {
4610 Binder.restoreCallingIdentity(origId);
4611 }
4612 }
4613 }
4614
Evan Rosky966759f2019-01-15 10:33:58 -08004615 @Override
4616 public void registerRemoteAnimationsForDisplay(int displayId,
4617 RemoteAnimationDefinition definition) {
4618 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4619 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004620 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004621 synchronized (mGlobalLock) {
4622 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4623 if (display == null) {
4624 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4625 return;
4626 }
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
4629 display.mDisplayContent.registerRemoteAnimations(definition);
4630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
4635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004636 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4637 @Override
4638 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4639 synchronized (mGlobalLock) {
4640 final long origId = Binder.clearCallingIdentity();
4641 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004642 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 } finally {
4644 Binder.restoreCallingIdentity(origId);
4645 }
4646 }
4647 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004648
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 @Override
4650 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004651 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004653 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004654 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004655 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004656 }
4657 }
4658
4659 @Override
4660 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004661 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004662 != PERMISSION_GRANTED) {
4663 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4664 + Binder.getCallingPid()
4665 + ", uid=" + Binder.getCallingUid()
4666 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4667 Slog.w(TAG, msg);
4668 throw new SecurityException(msg);
4669 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004672 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004673 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004674 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 }
4676 }
4677
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004678 @Override
4679 public void stopAppSwitches() {
4680 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4681 synchronized (mGlobalLock) {
4682 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004683 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004684 mDidAppSwitch = false;
4685 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4686 }
4687 }
4688
4689 @Override
4690 public void resumeAppSwitches() {
4691 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4692 synchronized (mGlobalLock) {
4693 // Note that we don't execute any pending app switches... we will
4694 // let those wait until either the timeout, or the next start
4695 // activity request.
4696 mAppSwitchesAllowedTime = 0;
4697 }
4698 }
4699
Ricky Wai906af482019-06-03 17:25:28 +01004700 long getLastStopAppSwitchesTime() {
4701 return mLastStopAppSwitchesTime;
4702 }
4703
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004704 void onStartActivitySetDidAppSwitch() {
4705 if (mDidAppSwitch) {
4706 // This is the second allowed switch since we stopped switches, so now just generally
4707 // allow switches. Use case:
4708 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4709 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4710 // anyone to switch again).
4711 mAppSwitchesAllowedTime = 0;
4712 } else {
4713 mDidAppSwitch = true;
4714 }
4715 }
4716
4717 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 boolean shouldDisableNonVrUiLocked() {
4719 return mVrController.shouldDisableNonVrUiLocked();
4720 }
4721
Wale Ogunwale53783742018-09-16 10:21:51 -07004722 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 // 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 +00004724 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004726 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4727 + " to main display for VR");
4728 mRootActivityContainer.moveStackToDisplay(
4729 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 }
4731 mH.post(() -> {
4732 if (!mVrController.onVrModeChanged(r)) {
4733 return;
4734 }
4735 synchronized (mGlobalLock) {
4736 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4737 mWindowManager.disableNonVrUi(disableNonVrUi);
4738 if (disableNonVrUi) {
4739 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4740 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004741 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 }
4743 }
4744 });
4745 }
4746
Wale Ogunwale53783742018-09-16 10:21:51 -07004747 @Override
4748 public int getPackageScreenCompatMode(String packageName) {
4749 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4750 synchronized (mGlobalLock) {
4751 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4752 }
4753 }
4754
4755 @Override
4756 public void setPackageScreenCompatMode(String packageName, int mode) {
4757 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4758 "setPackageScreenCompatMode");
4759 synchronized (mGlobalLock) {
4760 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4761 }
4762 }
4763
4764 @Override
4765 public boolean getPackageAskScreenCompat(String packageName) {
4766 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4767 synchronized (mGlobalLock) {
4768 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4769 }
4770 }
4771
4772 @Override
4773 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4774 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4775 "setPackageAskScreenCompat");
4776 synchronized (mGlobalLock) {
4777 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4778 }
4779 }
4780
Wale Ogunwale64258362018-10-16 15:13:37 -07004781 public static String relaunchReasonToString(int relaunchReason) {
4782 switch (relaunchReason) {
4783 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4784 return "window_resize";
4785 case RELAUNCH_REASON_FREE_RESIZE:
4786 return "free_resize";
4787 default:
4788 return null;
4789 }
4790 }
4791
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004792 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004793 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004794 }
4795
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 /** Pokes the task persister. */
4797 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4798 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4799 }
4800
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004801 boolean isKeyguardLocked() {
4802 return mKeyguardController.isKeyguardLocked();
4803 }
4804
Garfield Tan01548632018-11-27 10:15:48 -08004805 /**
4806 * Clears launch params for the given package.
4807 * @param packageNames the names of the packages of which the launch params are to be cleared
4808 */
4809 @Override
4810 public void clearLaunchParamsForPackages(List<String> packageNames) {
4811 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4812 "clearLaunchParamsForPackages");
4813 synchronized (mGlobalLock) {
4814 for (int i = 0; i < packageNames.size(); ++i) {
4815 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4816 }
4817 }
4818 }
4819
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004820 /**
4821 * Makes the display with the given id a single task instance display. I.e the display can only
4822 * contain one task.
4823 */
4824 @Override
4825 public void setDisplayToSingleTaskInstance(int displayId) {
4826 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4827 "setDisplayToSingleTaskInstance");
4828 final long origId = Binder.clearCallingIdentity();
4829 try {
4830 final ActivityDisplay display =
4831 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4832 if (display != null) {
4833 display.setDisplayToSingleTaskInstance();
4834 }
4835 } finally {
4836 Binder.restoreCallingIdentity(origId);
4837 }
4838 }
4839
Wale Ogunwale31913b52018-10-13 08:29:31 -07004840 void dumpLastANRLocked(PrintWriter pw) {
4841 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4842 if (mLastANRState == null) {
4843 pw.println(" <no ANR has occurred since boot>");
4844 } else {
4845 pw.println(mLastANRState);
4846 }
4847 }
4848
4849 void dumpLastANRTracesLocked(PrintWriter pw) {
4850 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4851
4852 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4853 if (ArrayUtils.isEmpty(files)) {
4854 pw.println(" <no ANR has occurred since boot>");
4855 return;
4856 }
4857 // Find the latest file.
4858 File latest = null;
4859 for (File f : files) {
4860 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4861 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004862 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004863 }
4864 pw.print("File: ");
4865 pw.print(latest.getName());
4866 pw.println();
4867 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4868 String line;
4869 while ((line = in.readLine()) != null) {
4870 pw.println(line);
4871 }
4872 } catch (IOException e) {
4873 pw.print("Unable to read: ");
4874 pw.print(e);
4875 pw.println();
4876 }
4877 }
4878
4879 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4880 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4881 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4882 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4883 }
4884
4885 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4886 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4887 pw.println(header);
4888
Wale Ogunwaled32da472018-11-16 07:19:28 -08004889 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004890 dumpPackage);
4891 boolean needSep = printedAnything;
4892
4893 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004894 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004895 " ResumedActivity: ");
4896 if (printed) {
4897 printedAnything = true;
4898 needSep = false;
4899 }
4900
4901 if (dumpPackage == null) {
4902 if (needSep) {
4903 pw.println();
4904 }
4905 printedAnything = true;
4906 mStackSupervisor.dump(pw, " ");
4907 }
4908
4909 if (!printedAnything) {
4910 pw.println(" (nothing)");
4911 }
4912 }
4913
4914 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004915 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004916 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004917 pw.println(" ");
4918 }
4919
4920 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4921 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4922 getActivityStartController().dump(pw, "", dumpPackage);
4923 }
4924
4925 /**
4926 * There are three things that cmd can be:
4927 * - a flattened component name that matches an existing activity
4928 * - the cmd arg isn't the flattened component name of an existing activity:
4929 * dump all activity whose component contains the cmd as a substring
4930 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004931 * <p>
4932 * The caller should not hold lock when calling this method because it will wait for the
4933 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004934 *
4935 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4936 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4937 */
4938 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4939 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4940 ArrayList<ActivityRecord> activities;
4941
4942 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004943 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004944 dumpFocusedStackOnly);
4945 }
4946
4947 if (activities.size() <= 0) {
4948 return false;
4949 }
4950
4951 String[] newArgs = new String[args.length - opti];
4952 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4953
4954 TaskRecord lastTask = null;
4955 boolean needSep = false;
4956 for (int i = activities.size() - 1; i >= 0; i--) {
4957 ActivityRecord r = activities.get(i);
4958 if (needSep) {
4959 pw.println();
4960 }
4961 needSep = true;
4962 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004963 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 if (lastTask != task) {
4965 lastTask = task;
4966 pw.print("TASK "); pw.print(lastTask.affinity);
4967 pw.print(" id="); pw.print(lastTask.taskId);
4968 pw.print(" userId="); pw.println(lastTask.userId);
4969 if (dumpAll) {
4970 lastTask.dump(pw, " ");
4971 }
4972 }
4973 }
4974 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4975 }
4976 return true;
4977 }
4978
4979 /**
4980 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4981 * there is a thread associated with the activity.
4982 */
4983 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4984 final ActivityRecord r, String[] args, boolean dumpAll) {
4985 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004986 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 synchronized (mGlobalLock) {
4988 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4989 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4990 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004991 if (r.hasProcess()) {
4992 pw.println(r.app.getPid());
4993 appThread = r.app.getThread();
4994 } else {
4995 pw.println("(not running)");
4996 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 if (dumpAll) {
4998 r.dump(pw, innerPrefix);
4999 }
5000 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005001 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005002 // flush anything that is already in the PrintWriter since the thread is going
5003 // to write to the file descriptor directly
5004 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005005 try (TransferPipe tp = new TransferPipe()) {
5006 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5007 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005008 } catch (IOException e) {
5009 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5010 } catch (RemoteException e) {
5011 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005013 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005014 }
5015
sanryhuang498e77e2018-12-06 14:57:01 +08005016 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5017 boolean testPssMode) {
5018 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5019 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5020 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005021 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5023 st.toString());
5024 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5026 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5027 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005028 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5029 testPssMode);
5030 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005031 }
5032
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005033 int getCurrentUserId() {
5034 return mAmInternal.getCurrentUserId();
5035 }
5036
5037 private void enforceNotIsolatedCaller(String caller) {
5038 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5039 throw new SecurityException("Isolated process not allowed to call " + caller);
5040 }
5041 }
5042
Wale Ogunwalef6733932018-06-27 05:14:34 -07005043 public Configuration getConfiguration() {
5044 Configuration ci;
5045 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005046 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005047 ci.userSetLocale = false;
5048 }
5049 return ci;
5050 }
5051
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005052 /**
5053 * Current global configuration information. Contains general settings for the entire system,
5054 * also corresponds to the merged configuration of the default display.
5055 */
5056 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005057 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005058 }
5059
5060 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5061 boolean initLocale) {
5062 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5063 }
5064
5065 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5066 boolean initLocale, boolean deferResume) {
5067 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5068 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5069 UserHandle.USER_NULL, deferResume);
5070 }
5071
Wale Ogunwale59507092018-10-29 09:00:30 -07005072 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 final long origId = Binder.clearCallingIdentity();
5074 try {
5075 synchronized (mGlobalLock) {
5076 updateConfigurationLocked(values, null, false, true, userId,
5077 false /* deferResume */);
5078 }
5079 } finally {
5080 Binder.restoreCallingIdentity(origId);
5081 }
5082 }
5083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005084 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5085 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5086 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5087 deferResume, null /* result */);
5088 }
5089
5090 /**
5091 * Do either or both things: (1) change the current configuration, and (2)
5092 * make sure the given activity is running with the (now) current
5093 * configuration. Returns true if the activity has been left running, or
5094 * false if <var>starting</var> is being destroyed to match the new
5095 * configuration.
5096 *
5097 * @param userId is only used when persistent parameter is set to true to persist configuration
5098 * for that particular user
5099 */
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5102 ActivityTaskManagerService.UpdateConfigurationResult result) {
5103 int changes = 0;
5104 boolean kept = true;
5105
Riddle Hsua0022cd2019-09-09 21:12:41 +08005106 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005107 try {
5108 if (values != null) {
5109 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5110 deferResume);
5111 }
5112
5113 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5114 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005115 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 }
5117
5118 if (result != null) {
5119 result.changes = changes;
5120 result.activityRelaunched = !kept;
5121 }
5122 return kept;
5123 }
5124
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005126 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005127 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005128
5129 final ActivityDisplay defaultDisplay =
5130 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5131
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132 mTempConfig.setTo(getGlobalConfiguration());
5133 final int changes = mTempConfig.updateFrom(values);
5134 if (changes == 0) {
5135 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5136 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5137 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5138 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005139 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005140 return 0;
5141 }
5142
5143 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5144 "Updating global configuration to: " + values);
5145
5146 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5147 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5148 values.colorMode,
5149 values.densityDpi,
5150 values.fontScale,
5151 values.hardKeyboardHidden,
5152 values.keyboard,
5153 values.keyboardHidden,
5154 values.mcc,
5155 values.mnc,
5156 values.navigation,
5157 values.navigationHidden,
5158 values.orientation,
5159 values.screenHeightDp,
5160 values.screenLayout,
5161 values.screenWidthDp,
5162 values.smallestScreenWidthDp,
5163 values.touchscreen,
5164 values.uiMode);
5165
5166
5167 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5168 final LocaleList locales = values.getLocales();
5169 int bestLocaleIndex = 0;
5170 if (locales.size() > 1) {
5171 if (mSupportedSystemLocales == null) {
5172 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5173 }
5174 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5175 }
5176 SystemProperties.set("persist.sys.locale",
5177 locales.get(bestLocaleIndex).toLanguageTag());
5178 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005179
5180 final Message m = PooledLambda.obtainMessage(
5181 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5182 locales.get(bestLocaleIndex));
5183 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184 }
5185
Yunfan Chen75157d72018-07-27 14:47:21 +09005186 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005189 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5192 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005193 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194
5195 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005196 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197
5198 AttributeCache ac = AttributeCache.instance();
5199 if (ac != null) {
5200 ac.updateConfiguration(mTempConfig);
5201 }
5202
5203 // Make sure all resources in our process are updated right now, so that anyone who is going
5204 // to retrieve resource values after we return will be sure to get the new ones. This is
5205 // especially important during boot, where the first config change needs to guarantee all
5206 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005207 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005208
5209 // We need another copy of global config because we're scheduling some calls instead of
5210 // running them in place. We need to be sure that object we send will be handled unchanged.
5211 final Configuration configCopy = new Configuration(mTempConfig);
5212 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005213 final Message msg = PooledLambda.obtainMessage(
5214 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5215 this, userId, configCopy);
5216 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005217 }
5218
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005219 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5220 for (int i = pidMap.size() - 1; i >= 0; i--) {
5221 final int pid = pidMap.keyAt(i);
5222 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005223 if (DEBUG_CONFIGURATION) {
5224 Slog.v(TAG_CONFIGURATION, "Update process config of "
5225 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005227 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228 }
5229
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005230 final Message msg = PooledLambda.obtainMessage(
5231 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5232 mAmInternal, changes, initLocale);
5233 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234
5235 // Override configuration of the default display duplicates global config, so we need to
5236 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005237 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5238 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 return changes;
5241 }
5242
Riddle Hsua0022cd2019-09-09 21:12:41 +08005243 /** @see WindowSurfacePlacer#deferLayout */
5244 void deferWindowLayout() {
5245 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5246 // Reset the reasons at the first entrance because we only care about the changes in the
5247 // deferred scope.
5248 mLayoutReasons = 0;
5249 }
5250
5251 mWindowManager.mWindowPlacerLocked.deferLayout();
5252 }
5253
5254 /** @see WindowSurfacePlacer#continueLayout */
5255 void continueWindowLayout() {
5256 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5257 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5258 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5259 }
5260 }
5261
5262 /**
5263 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5264 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5265 * defer count is gone.
5266 */
5267 void addWindowLayoutReasons(@LayoutReason int reasons) {
5268 mLayoutReasons |= reasons;
5269 }
5270
Wale Ogunwalef6733932018-06-27 05:14:34 -07005271 private void updateEventDispatchingLocked(boolean booted) {
5272 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5273 }
5274
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005275 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5276 final ContentResolver resolver = mContext.getContentResolver();
5277 Settings.System.putConfigurationForUser(resolver, config, userId);
5278 }
5279
5280 private void sendLocaleToMountDaemonMsg(Locale l) {
5281 try {
5282 IBinder service = ServiceManager.getService("mount");
5283 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5284 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5285 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5286 } catch (RemoteException e) {
5287 Log.e(TAG, "Error storing locale for decryption UI", e);
5288 }
5289 }
5290
Alison Cichowlas3e340502018-08-07 17:15:01 -04005291 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5292 mStartActivitySources.remove(permissionToken);
5293 mExpiredStartAsCallerTokens.add(permissionToken);
5294 }
5295
5296 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5297 mExpiredStartAsCallerTokens.remove(permissionToken);
5298 }
5299
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005300 boolean isActivityStartsLoggingEnabled() {
5301 return mAmInternal.isActivityStartsLoggingEnabled();
5302 }
5303
Michal Karpinski8596ded2018-11-14 14:43:48 +00005304 boolean isBackgroundActivityStartsEnabled() {
5305 return mAmInternal.isBackgroundActivityStartsEnabled();
5306 }
5307
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 void enableScreenAfterBoot(boolean booted) {
5309 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5310 SystemClock.uptimeMillis());
5311 mWindowManager.enableScreenAfterBoot();
5312
5313 synchronized (mGlobalLock) {
5314 updateEventDispatchingLocked(booted);
5315 }
5316 }
5317
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005318 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5319 if (r == null || !r.hasProcess()) {
5320 return KEY_DISPATCHING_TIMEOUT_MS;
5321 }
5322 return getInputDispatchingTimeoutLocked(r.app);
5323 }
5324
5325 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005326 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005327 }
5328
Wale Ogunwalef6733932018-06-27 05:14:34 -07005329 /**
5330 * Decide based on the configuration whether we should show the ANR,
5331 * crash, etc dialogs. The idea is that if there is no affordance to
5332 * press the on-screen buttons, or the user experience would be more
5333 * greatly impacted than the crash itself, we shouldn't show the dialog.
5334 *
5335 * A thought: SystemUI might also want to get told about this, the Power
5336 * dialog / global actions also might want different behaviors.
5337 */
5338 private void updateShouldShowDialogsLocked(Configuration config) {
5339 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5340 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5341 && config.navigation == Configuration.NAVIGATION_NONAV);
5342 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5343 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5344 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5345 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5346 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5347 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5348 HIDE_ERROR_DIALOGS, 0) != 0;
5349 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5350 }
5351
5352 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5353 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5354 FONT_SCALE, 1.0f, userId);
5355
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005356 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 if (getGlobalConfiguration().fontScale == scaleFactor) {
5358 return;
5359 }
5360
5361 final Configuration configuration
5362 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5363 configuration.fontScale = scaleFactor;
5364 updatePersistentConfiguration(configuration, userId);
5365 }
5366 }
5367
5368 // Actually is sleeping or shutting down or whatever else in the future
5369 // is an inactive state.
5370 boolean isSleepingOrShuttingDownLocked() {
5371 return isSleepingLocked() || mShuttingDown;
5372 }
5373
5374 boolean isSleepingLocked() {
5375 return mSleeping;
5376 }
5377
Riddle Hsu16567132018-08-16 21:37:47 +08005378 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005379 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005380 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005381 if (task.isActivityTypeStandard()) {
5382 if (mCurAppTimeTracker != r.appTimeTracker) {
5383 // We are switching app tracking. Complete the current one.
5384 if (mCurAppTimeTracker != null) {
5385 mCurAppTimeTracker.stop();
5386 mH.obtainMessage(
5387 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005388 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005389 mCurAppTimeTracker = null;
5390 }
5391 if (r.appTimeTracker != null) {
5392 mCurAppTimeTracker = r.appTimeTracker;
5393 startTimeTrackingFocusedActivityLocked();
5394 }
5395 } else {
5396 startTimeTrackingFocusedActivityLocked();
5397 }
5398 } else {
5399 r.appTimeTracker = null;
5400 }
5401 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5402 // TODO: Probably not, because we don't want to resume voice on switching
5403 // back to this activity
5404 if (task.voiceInteractor != null) {
5405 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5406 } else {
5407 finishRunningVoiceLocked();
5408
5409 if (mLastResumedActivity != null) {
5410 final IVoiceInteractionSession session;
5411
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005412 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 if (lastResumedActivityTask != null
5414 && lastResumedActivityTask.voiceSession != null) {
5415 session = lastResumedActivityTask.voiceSession;
5416 } else {
5417 session = mLastResumedActivity.voiceSession;
5418 }
5419
5420 if (session != null) {
5421 // We had been in a voice interaction session, but now focused has
5422 // move to something different. Just finish the session, we can't
5423 // return to it and retain the proper state and synchronization with
5424 // the voice interaction service.
5425 finishVoiceTask(session);
5426 }
5427 }
5428 }
5429
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005430 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5431 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 }
5433 updateResumedAppTrace(r);
5434 mLastResumedActivity = r;
5435
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005436 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437
5438 applyUpdateLockStateLocked(r);
5439 applyUpdateVrModeLocked(r);
5440
5441 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005442 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 r == null ? "NULL" : r.shortComponentName,
5444 reason);
5445 }
5446
5447 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5448 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005449 final ActivityTaskManagerInternal.SleepToken token =
5450 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 updateSleepIfNeededLocked();
5452 return token;
5453 }
5454 }
5455
5456 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005457 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 final boolean wasSleeping = mSleeping;
5459 boolean updateOomAdj = false;
5460
5461 if (!shouldSleep) {
5462 // If wasSleeping is true, we need to wake up activity manager state from when
5463 // we started sleeping. In either case, we need to apply the sleep tokens, which
5464 // will wake up stacks or put them to sleep as appropriate.
5465 if (wasSleeping) {
5466 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005467 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5468 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 startTimeTrackingFocusedActivityLocked();
5470 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005471 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5473 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005474 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475 if (wasSleeping) {
5476 updateOomAdj = true;
5477 }
5478 } else if (!mSleeping && shouldSleep) {
5479 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005480 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5481 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482 if (mCurAppTimeTracker != null) {
5483 mCurAppTimeTracker.stop();
5484 }
5485 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005486 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005487 mStackSupervisor.goingToSleepLocked();
5488 updateResumedAppTrace(null /* resumed */);
5489 updateOomAdj = true;
5490 }
5491 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005492 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 }
5494 }
5495
5496 void updateOomAdj() {
5497 mH.post(mAmInternal::updateOomAdj);
5498 }
5499
Wale Ogunwale53783742018-09-16 10:21:51 -07005500 void updateCpuStats() {
5501 mH.post(mAmInternal::updateCpuStats);
5502 }
5503
Hui Yu03d12402018-12-06 18:00:37 -08005504 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5505 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005506 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5507 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005508 mH.sendMessage(m);
5509 }
5510
Hui Yu03d12402018-12-06 18:00:37 -08005511 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005512 ComponentName taskRoot = null;
5513 final TaskRecord task = activity.getTaskRecord();
5514 if (task != null) {
5515 final ActivityRecord rootActivity = task.getRootActivity();
5516 if (rootActivity != null) {
5517 taskRoot = rootActivity.mActivityComponent;
5518 }
5519 }
5520
Hui Yu03d12402018-12-06 18:00:37 -08005521 final Message m = PooledLambda.obtainMessage(
5522 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005523 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005524 mH.sendMessage(m);
5525 }
5526
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005527 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5528 String hostingType) {
5529 try {
5530 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5531 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5532 + activity.processName);
5533 }
5534 // Post message to start process to avoid possible deadlock of calling into AMS with the
5535 // ATMS lock held.
5536 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5537 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5538 isTop, hostingType, activity.intent.getComponent());
5539 mH.sendMessage(m);
5540 } finally {
5541 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5542 }
5543 }
5544
Wale Ogunwale53783742018-09-16 10:21:51 -07005545 void setBooting(boolean booting) {
5546 mAmInternal.setBooting(booting);
5547 }
5548
5549 boolean isBooting() {
5550 return mAmInternal.isBooting();
5551 }
5552
5553 void setBooted(boolean booted) {
5554 mAmInternal.setBooted(booted);
5555 }
5556
5557 boolean isBooted() {
5558 return mAmInternal.isBooted();
5559 }
5560
5561 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5562 mH.post(() -> {
5563 if (finishBooting) {
5564 mAmInternal.finishBooting();
5565 }
5566 if (enableScreen) {
5567 mInternal.enableScreenAfterBoot(isBooted());
5568 }
5569 });
5570 }
5571
5572 void setHeavyWeightProcess(ActivityRecord root) {
5573 mHeavyWeightProcess = root.app;
5574 final Message m = PooledLambda.obtainMessage(
5575 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005576 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005577 mH.sendMessage(m);
5578 }
5579
5580 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5581 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5582 return;
5583 }
5584
5585 mHeavyWeightProcess = null;
5586 final Message m = PooledLambda.obtainMessage(
5587 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5588 proc.mUserId);
5589 mH.sendMessage(m);
5590 }
5591
5592 private void cancelHeavyWeightProcessNotification(int userId) {
5593 final INotificationManager inm = NotificationManager.getService();
5594 if (inm == null) {
5595 return;
5596 }
5597 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005598 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005599 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5600 } catch (RuntimeException e) {
5601 Slog.w(TAG, "Error canceling notification for service", e);
5602 } catch (RemoteException e) {
5603 }
5604
5605 }
5606
5607 private void postHeavyWeightProcessNotification(
5608 WindowProcessController proc, Intent intent, int userId) {
5609 if (proc == null) {
5610 return;
5611 }
5612
5613 final INotificationManager inm = NotificationManager.getService();
5614 if (inm == null) {
5615 return;
5616 }
5617
5618 try {
5619 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5620 String text = mContext.getString(R.string.heavy_weight_notification,
5621 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5622 Notification notification =
5623 new Notification.Builder(context,
5624 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5625 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5626 .setWhen(0)
5627 .setOngoing(true)
5628 .setTicker(text)
5629 .setColor(mContext.getColor(
5630 com.android.internal.R.color.system_notification_accent_color))
5631 .setContentTitle(text)
5632 .setContentText(
5633 mContext.getText(R.string.heavy_weight_notification_detail))
5634 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5635 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5636 new UserHandle(userId)))
5637 .build();
5638 try {
5639 inm.enqueueNotificationWithTag("android", "android", null,
5640 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5641 } catch (RuntimeException e) {
5642 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5643 } catch (RemoteException e) {
5644 }
5645 } catch (PackageManager.NameNotFoundException e) {
5646 Slog.w(TAG, "Unable to create context for heavy notification", e);
5647 }
5648
5649 }
5650
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005651 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5652 IBinder token, String resultWho, int requestCode, Intent[] intents,
5653 String[] resolvedTypes, int flags, Bundle bOptions) {
5654
5655 ActivityRecord activity = null;
5656 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5657 activity = ActivityRecord.isInStackLocked(token);
5658 if (activity == null) {
5659 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5660 return null;
5661 }
5662 if (activity.finishing) {
5663 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5664 return null;
5665 }
5666 }
5667
5668 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5669 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5670 bOptions);
5671 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5672 if (noCreate) {
5673 return rec;
5674 }
5675 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5676 if (activity.pendingResults == null) {
5677 activity.pendingResults = new HashSet<>();
5678 }
5679 activity.pendingResults.add(rec.ref);
5680 }
5681 return rec;
5682 }
5683
Andrii Kulian52d255c2018-07-13 11:32:19 -07005684 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005685 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005686 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005687 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5688 mCurAppTimeTracker.start(resumedActivity.packageName);
5689 }
5690 }
5691
5692 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5693 if (mTracedResumedActivity != null) {
5694 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5695 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5696 }
5697 if (resumed != null) {
5698 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5699 constructResumedTraceName(resumed.packageName), 0);
5700 }
5701 mTracedResumedActivity = resumed;
5702 }
5703
5704 private String constructResumedTraceName(String packageName) {
5705 return "focused app: " + packageName;
5706 }
5707
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005708 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005709 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005710 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005711 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005712 // mainStack is null during startup.
5713 if (mainStack != null) {
5714 if (changes != 0 && starting == null) {
5715 // If the configuration changed, and the caller is not already
5716 // in the process of starting an activity, then find the top
5717 // activity to check if its configuration needs to change.
5718 starting = mainStack.topRunningActivityLocked();
5719 }
5720
5721 if (starting != null) {
5722 kept = starting.ensureActivityConfiguration(changes,
5723 false /* preserveWindow */);
5724 // And we need to make sure at this point that all other activities
5725 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005726 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005727 !PRESERVE_WINDOWS);
5728 }
5729 }
5730
5731 return kept;
5732 }
5733
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005734 void scheduleAppGcsLocked() {
5735 mH.post(() -> mAmInternal.scheduleAppGcs());
5736 }
5737
Wale Ogunwale53783742018-09-16 10:21:51 -07005738 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5739 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5740 }
5741
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005742 /**
5743 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5744 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5745 * on demand.
5746 */
5747 IPackageManager getPackageManager() {
5748 return AppGlobals.getPackageManager();
5749 }
5750
5751 PackageManagerInternal getPackageManagerInternalLocked() {
5752 if (mPmInternal == null) {
5753 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5754 }
5755 return mPmInternal;
5756 }
5757
Hai Zhangf4da9be2019-05-01 13:46:06 +08005758 PermissionPolicyInternal getPermissionPolicyInternal() {
5759 if (mPermissionPolicyInternal == null) {
5760 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5761 }
5762 return mPermissionPolicyInternal;
5763 }
5764
Wale Ogunwale008163e2018-07-23 23:11:08 -07005765 AppWarnings getAppWarningsLocked() {
5766 return mAppWarnings;
5767 }
5768
Wale Ogunwale214f3482018-10-04 11:00:47 -07005769 Intent getHomeIntent() {
5770 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5771 intent.setComponent(mTopComponent);
5772 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5773 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5774 intent.addCategory(Intent.CATEGORY_HOME);
5775 }
5776 return intent;
5777 }
5778
Chilun2ef71f72018-11-16 17:57:15 +08005779 /**
5780 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5781 * activities.
5782 *
5783 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5784 * component defined in config_secondaryHomeComponent.
5785 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5786 */
5787 Intent getSecondaryHomeIntent(String preferredPackage) {
5788 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005789 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5790 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5791 if (preferredPackage == null || useSystemProvidedLauncher) {
5792 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005793 final String secondaryHomeComponent = mContext.getResources().getString(
5794 com.android.internal.R.string.config_secondaryHomeComponent);
5795 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5796 } else {
5797 intent.setPackage(preferredPackage);
5798 }
5799 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5800 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5801 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5802 }
5803 return intent;
5804 }
5805
Wale Ogunwale214f3482018-10-04 11:00:47 -07005806 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5807 if (info == null) return null;
5808 ApplicationInfo newInfo = new ApplicationInfo(info);
5809 newInfo.initForUser(userId);
5810 return newInfo;
5811 }
5812
Wale Ogunwale9c103022018-10-18 07:44:54 -07005813 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005814 if (uid == SYSTEM_UID) {
5815 // The system gets to run in any process. If there are multiple processes with the same
5816 // uid, just pick the first (this should never happen).
5817 final SparseArray<WindowProcessController> procs =
5818 mProcessNames.getMap().get(processName);
5819 if (procs == null) return null;
5820 final int procCount = procs.size();
5821 for (int i = 0; i < procCount; i++) {
5822 final int procUid = procs.keyAt(i);
5823 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5824 // Don't use an app process or different user process for system component.
5825 continue;
5826 }
5827 return procs.valueAt(i);
5828 }
5829 }
5830
5831 return mProcessNames.get(processName, uid);
5832 }
5833
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005834 WindowProcessController getProcessController(IApplicationThread thread) {
5835 if (thread == null) {
5836 return null;
5837 }
5838
5839 final IBinder threadBinder = thread.asBinder();
5840 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5841 for (int i = pmap.size()-1; i >= 0; i--) {
5842 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5843 for (int j = procs.size() - 1; j >= 0; j--) {
5844 final WindowProcessController proc = procs.valueAt(j);
5845 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5846 return proc;
5847 }
5848 }
5849 }
5850
5851 return null;
5852 }
5853
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005854 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005855 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005856 if (proc == null) return null;
5857 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5858 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005859 }
5860 return null;
5861 }
5862
Riddle Hsua0536432019-02-16 00:38:59 +08005863 int getUidState(int uid) {
5864 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005865 }
5866
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005867 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005868 // A uid is considered to be foreground if it has a visible non-toast window.
5869 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005870 }
5871
Ricky Wai96f5c352019-04-10 18:40:17 +01005872 boolean isDeviceOwner(int uid) {
5873 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005874 }
5875
Ricky Wai96f5c352019-04-10 18:40:17 +01005876 void setDeviceOwnerUid(int uid) {
5877 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005878 }
5879
Wale Ogunwale9de19442018-10-18 19:05:03 -07005880 /**
5881 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5882 * the whitelist
5883 */
5884 String getPendingTempWhitelistTagForUidLocked(int uid) {
5885 return mPendingTempWhitelist.get(uid);
5886 }
5887
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005888 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5889 if (true || Build.IS_USER) {
5890 return;
5891 }
5892
5893 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5894 StrictMode.allowThreadDiskWrites();
5895 try {
5896 File tracesDir = new File("/data/anr");
5897 File tracesFile = null;
5898 try {
5899 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5900
5901 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005902 String timeString =
5903 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5904 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005905 sb.append(": ");
5906 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5907 sb.append(" since ");
5908 sb.append(msg);
5909 FileOutputStream fos = new FileOutputStream(tracesFile);
5910 fos.write(sb.toString().getBytes());
5911 if (app == null) {
5912 fos.write("\n*** No application process!".getBytes());
5913 }
5914 fos.close();
5915 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5916 } catch (IOException e) {
5917 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5918 return;
5919 }
5920
5921 if (app != null && app.getPid() > 0) {
5922 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5923 firstPids.add(app.getPid());
5924 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5925 }
5926
5927 File lastTracesFile = null;
5928 File curTracesFile = null;
5929 for (int i=9; i>=0; i--) {
5930 String name = String.format(Locale.US, "slow%02d.txt", i);
5931 curTracesFile = new File(tracesDir, name);
5932 if (curTracesFile.exists()) {
5933 if (lastTracesFile != null) {
5934 curTracesFile.renameTo(lastTracesFile);
5935 } else {
5936 curTracesFile.delete();
5937 }
5938 }
5939 lastTracesFile = curTracesFile;
5940 }
5941 tracesFile.renameTo(curTracesFile);
5942 } finally {
5943 StrictMode.setThreadPolicy(oldPolicy);
5944 }
5945 }
5946
Michal Karpinskida34cd42019-04-02 19:46:52 +01005947 boolean isAssociatedCompanionApp(int userId, int uid) {
5948 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5949 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005950 return false;
5951 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005952 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005953 }
5954
Issei Suzuki734bc942019-06-05 13:59:52 +02005955 void notifySingleTaskDisplayEmpty(int displayId) {
5956 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5957 }
5958
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005959 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005960 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005961
5962
Wale Ogunwale98875612018-10-12 07:53:02 -07005963 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5964 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005965
Riddle Hsud93a6c42018-11-29 21:50:06 +08005966 H(Looper looper) {
5967 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005968 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005969
5970 @Override
5971 public void handleMessage(Message msg) {
5972 switch (msg.what) {
5973 case REPORT_TIME_TRACKER_MSG: {
5974 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5975 tracker.deliverResult(mContext);
5976 } break;
5977 }
5978 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005979 }
5980
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005981 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005982 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005983
5984 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005985 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005986 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005987
5988 @Override
5989 public void handleMessage(Message msg) {
5990 switch (msg.what) {
5991 case DISMISS_DIALOG_UI_MSG: {
5992 final Dialog d = (Dialog) msg.obj;
5993 d.dismiss();
5994 break;
5995 }
5996 }
5997 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005998 }
5999
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000 final class LocalService extends ActivityTaskManagerInternal {
6001 @Override
6002 public SleepToken acquireSleepToken(String tag, int displayId) {
6003 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006004 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005 }
6006
6007 @Override
6008 public ComponentName getHomeActivityForUser(int userId) {
6009 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006010 final ActivityRecord homeActivity =
6011 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006012 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006013 }
6014 }
6015
6016 @Override
6017 public void onLocalVoiceInteractionStarted(IBinder activity,
6018 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6019 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006020 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006021 }
6022 }
6023
6024 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006025 public void notifyAppTransitionStarting(SparseIntArray reasons,
6026 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006027 synchronized (mGlobalLock) {
6028 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6029 reasons, timestamp);
6030 }
6031 }
6032
6033 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006034 public void notifySingleTaskDisplayDrawn(int displayId) {
6035 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6036 }
6037
6038 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 public void notifyAppTransitionFinished() {
6040 synchronized (mGlobalLock) {
6041 mStackSupervisor.notifyAppTransitionDone();
6042 }
6043 }
6044
6045 @Override
6046 public void notifyAppTransitionCancelled() {
6047 synchronized (mGlobalLock) {
6048 mStackSupervisor.notifyAppTransitionDone();
6049 }
6050 }
6051
6052 @Override
6053 public List<IBinder> getTopVisibleActivities() {
6054 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006055 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057 }
6058
6059 @Override
6060 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6061 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006062 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006063 }
6064 }
6065
6066 @Override
6067 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6068 Bundle bOptions) {
6069 Preconditions.checkNotNull(intents, "intents");
6070 final String[] resolvedTypes = new String[intents.length];
6071
6072 // UID of the package on user userId.
6073 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6074 // packageUid may not be initialized.
6075 int packageUid = 0;
6076 final long ident = Binder.clearCallingIdentity();
6077
6078 try {
6079 for (int i = 0; i < intents.length; i++) {
6080 resolvedTypes[i] =
6081 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6082 }
6083
6084 packageUid = AppGlobals.getPackageManager().getPackageUid(
6085 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6086 } catch (RemoteException e) {
6087 // Shouldn't happen.
6088 } finally {
6089 Binder.restoreCallingIdentity(ident);
6090 }
6091
Riddle Hsu591bf612019-02-14 17:55:31 +08006092 return getActivityStartController().startActivitiesInPackage(
6093 packageUid, packageName,
6094 intents, resolvedTypes, null /* resultTo */,
6095 SafeActivityOptions.fromBundle(bOptions), userId,
6096 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6097 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 }
6099
6100 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006101 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6102 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6103 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6104 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006105 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006106 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006107 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6108 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6109 userId, validateIncomingUser, originatingPendingIntent,
6110 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006111 }
6112 }
6113
6114 @Override
6115 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6116 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6117 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6118 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006119 PendingIntentRecord originatingPendingIntent,
6120 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006121 synchronized (mGlobalLock) {
6122 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6123 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6124 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006125 validateIncomingUser, originatingPendingIntent,
6126 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006127 }
6128 }
6129
6130 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6132 Intent intent, Bundle options, int userId) {
6133 return ActivityTaskManagerService.this.startActivityAsUser(
6134 caller, callerPacakge, intent,
6135 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6136 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6137 false /*validateIncomingUser*/);
6138 }
6139
6140 @Override
lumark588a3e82018-07-20 18:53:54 +08006141 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006142 synchronized (mGlobalLock) {
6143
6144 // We might change the visibilities here, so prepare an empty app transition which
6145 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006146 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006147 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006148 if (activityDisplay == null) {
6149 return;
6150 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006151 final DisplayContent dc = activityDisplay.mDisplayContent;
6152 final boolean wasTransitionSet =
6153 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006155 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006157 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006158
6159 // If there was a transition set already we don't want to interfere with it as we
6160 // might be starting it too early.
6161 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006162 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006163 }
6164 }
6165 if (callback != null) {
6166 callback.run();
6167 }
6168 }
6169
6170 @Override
6171 public void notifyKeyguardTrustedChanged() {
6172 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006173 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006174 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176 }
6177 }
6178
6179 /**
6180 * Called after virtual display Id is updated by
6181 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6182 * {@param vrVr2dDisplayId}.
6183 */
6184 @Override
6185 public void setVr2dDisplayId(int vr2dDisplayId) {
6186 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006188 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
6190 }
6191
6192 @Override
6193 public void setFocusedActivity(IBinder token) {
6194 synchronized (mGlobalLock) {
6195 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6196 if (r == null) {
6197 throw new IllegalArgumentException(
6198 "setFocusedActivity: No activity record matching token=" + token);
6199 }
Louis Chang19443452018-10-09 12:10:21 +08006200 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006201 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 }
6203 }
6204 }
6205
6206 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006208 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209 }
6210
6211 @Override
6212 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006213 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215
6216 @Override
6217 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006218 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 }
6220
6221 @Override
6222 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6223 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6224 }
6225
6226 @Override
6227 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006228 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006230
6231 @Override
6232 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6233 synchronized (mGlobalLock) {
6234 mActiveVoiceInteractionServiceComponent = component;
6235 }
6236 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006237
6238 @Override
6239 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6240 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6241 return;
6242 }
6243 synchronized (mGlobalLock) {
6244 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6245 if (types == null) {
6246 if (uid < 0) {
6247 return;
6248 }
6249 types = new ArrayMap<>();
6250 mAllowAppSwitchUids.put(userId, types);
6251 }
6252 if (uid < 0) {
6253 types.remove(type);
6254 } else {
6255 types.put(type, uid);
6256 }
6257 }
6258 }
6259
6260 @Override
6261 public void onUserStopped(int userId) {
6262 synchronized (mGlobalLock) {
6263 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6264 mAllowAppSwitchUids.remove(userId);
6265 }
6266 }
6267
6268 @Override
6269 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6270 synchronized (mGlobalLock) {
6271 return ActivityTaskManagerService.this.isGetTasksAllowed(
6272 caller, callingPid, callingUid);
6273 }
6274 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006275
Riddle Hsua0536432019-02-16 00:38:59 +08006276 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006277 @Override
6278 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006279 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006280 mProcessNames.put(proc.mName, proc.mUid, proc);
6281 }
6282 }
6283
Riddle Hsua0536432019-02-16 00:38:59 +08006284 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006285 @Override
6286 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006287 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006288 mProcessNames.remove(name, uid);
6289 }
6290 }
6291
Riddle Hsua0536432019-02-16 00:38:59 +08006292 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006293 @Override
6294 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006295 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006296 if (proc == mHomeProcess) {
6297 mHomeProcess = null;
6298 }
6299 if (proc == mPreviousProcess) {
6300 mPreviousProcess = null;
6301 }
6302 }
6303 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006304
Riddle Hsua0536432019-02-16 00:38:59 +08006305 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 @Override
6307 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006308 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 return mTopProcessState;
6310 }
6311 }
6312
Riddle Hsua0536432019-02-16 00:38:59 +08006313 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006314 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006315 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006316 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006317 return proc == mHeavyWeightProcess;
6318 }
6319 }
6320
Riddle Hsua0536432019-02-16 00:38:59 +08006321 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006322 @Override
6323 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006324 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006325 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6326 }
6327 }
6328
6329 @Override
6330 public void finishHeavyWeightApp() {
6331 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006332 if (mHeavyWeightProcess != null) {
6333 mHeavyWeightProcess.finishActivities();
6334 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006335 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6336 mHeavyWeightProcess);
6337 }
6338 }
6339
Riddle Hsua0536432019-02-16 00:38:59 +08006340 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006341 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006342 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006343 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006344 return isSleepingLocked();
6345 }
6346 }
6347
6348 @Override
6349 public boolean isShuttingDown() {
6350 synchronized (mGlobalLock) {
6351 return mShuttingDown;
6352 }
6353 }
6354
6355 @Override
6356 public boolean shuttingDown(boolean booted, int timeout) {
6357 synchronized (mGlobalLock) {
6358 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006359 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006360 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006361 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006362 return mStackSupervisor.shutdownLocked(timeout);
6363 }
6364 }
6365
6366 @Override
6367 public void enableScreenAfterBoot(boolean booted) {
6368 synchronized (mGlobalLock) {
6369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6370 SystemClock.uptimeMillis());
6371 mWindowManager.enableScreenAfterBoot();
6372 updateEventDispatchingLocked(booted);
6373 }
6374 }
6375
6376 @Override
6377 public boolean showStrictModeViolationDialog() {
6378 synchronized (mGlobalLock) {
6379 return mShowDialogs && !mSleeping && !mShuttingDown;
6380 }
6381 }
6382
6383 @Override
6384 public void showSystemReadyErrorDialogsIfNeeded() {
6385 synchronized (mGlobalLock) {
6386 try {
6387 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6388 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6389 + " data partition or your device will be unstable.");
6390 mUiHandler.post(() -> {
6391 if (mShowDialogs) {
6392 AlertDialog d = new BaseErrorDialog(mUiContext);
6393 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6394 d.setCancelable(false);
6395 d.setTitle(mUiContext.getText(R.string.android_system_label));
6396 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6397 d.setButton(DialogInterface.BUTTON_POSITIVE,
6398 mUiContext.getText(R.string.ok),
6399 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6400 d.show();
6401 }
6402 });
6403 }
6404 } catch (RemoteException e) {
6405 }
6406
6407 if (!Build.isBuildConsistent()) {
6408 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6409 mUiHandler.post(() -> {
6410 if (mShowDialogs) {
6411 AlertDialog d = new BaseErrorDialog(mUiContext);
6412 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6413 d.setCancelable(false);
6414 d.setTitle(mUiContext.getText(R.string.android_system_label));
6415 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6416 d.setButton(DialogInterface.BUTTON_POSITIVE,
6417 mUiContext.getText(R.string.ok),
6418 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6419 d.show();
6420 }
6421 });
6422 }
6423 }
6424 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006425
6426 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006427 public void onProcessMapped(int pid, WindowProcessController proc) {
6428 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006429 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006430 }
6431 }
6432
6433 @Override
6434 public void onProcessUnMapped(int pid) {
6435 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006436 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006437 }
6438 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006439
6440 @Override
6441 public void onPackageDataCleared(String name) {
6442 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006444 mAppWarnings.onPackageDataCleared(name);
6445 }
6446 }
6447
6448 @Override
6449 public void onPackageUninstalled(String name) {
6450 synchronized (mGlobalLock) {
6451 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006452 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006453 }
6454 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006455
6456 @Override
6457 public void onPackageAdded(String name, boolean replacing) {
6458 synchronized (mGlobalLock) {
6459 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6460 }
6461 }
6462
6463 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006464 public void onPackageReplaced(ApplicationInfo aInfo) {
6465 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006466 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006467 }
6468 }
6469
6470 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006471 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6472 synchronized (mGlobalLock) {
6473 return compatibilityInfoForPackageLocked(ai);
6474 }
6475 }
6476
Yunfan Chen75157d72018-07-27 14:47:21 +09006477 /**
6478 * Set the corresponding display information for the process global configuration. To be
6479 * called when we need to show IME on a different display.
6480 *
6481 * @param pid The process id associated with the IME window.
6482 * @param displayId The ID of the display showing the IME.
6483 */
6484 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006485 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006486 // Don't update process-level configuration for Multi-Client IME process since other
6487 // IMEs on other displays will also receive this configuration change due to IME
6488 // services use the same application config/context.
6489 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006490
Yunfan Chen75157d72018-07-27 14:47:21 +09006491 if (pid == MY_PID || pid < 0) {
6492 if (DEBUG_CONFIGURATION) {
6493 Slog.w(TAG,
6494 "Trying to update display configuration for system/invalid process.");
6495 }
6496 return;
6497 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006498 synchronized (mGlobalLock) {
6499 final ActivityDisplay activityDisplay =
6500 mRootActivityContainer.getActivityDisplay(displayId);
6501 if (activityDisplay == null) {
6502 // Call might come when display is not yet added or has been removed.
6503 if (DEBUG_CONFIGURATION) {
6504 Slog.w(TAG, "Trying to update display configuration for non-existing "
6505 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006506 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006507 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006508 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006509 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006510 if (process == null) {
6511 if (DEBUG_CONFIGURATION) {
6512 Slog.w(TAG, "Trying to update display configuration for invalid "
6513 + "process, pid=" + pid);
6514 }
6515 return;
6516 }
lumarkddc77fb2019-06-27 22:22:23 +08006517 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006518 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6519 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006520 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006521
6522 @Override
6523 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006524 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006525 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006526 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6527 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006528 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006529 }
6530 }
6531 }
6532
6533 @Override
6534 public void clearPendingResultForActivity(IBinder activityToken,
6535 WeakReference<PendingIntentRecord> pir) {
6536 synchronized (mGlobalLock) {
6537 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6538 if (r != null && r.pendingResults != null) {
6539 r.pendingResults.remove(pir);
6540 }
6541 }
6542 }
6543
6544 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006545 public ActivityTokens getTopActivityForTask(int taskId) {
6546 synchronized (mGlobalLock) {
6547 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6548 if (taskRecord == null) {
6549 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6550 + " Requested task not found");
6551 return null;
6552 }
6553 final ActivityRecord activity = taskRecord.getTopActivity();
6554 if (activity == null) {
6555 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6556 + " Requested activity not found");
6557 return null;
6558 }
6559 if (!activity.attachedToProcess()) {
6560 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6561 + activity);
6562 return null;
6563 }
6564 return new ActivityTokens(activity.appToken, activity.assistToken,
6565 activity.app.getThread());
6566 }
6567 }
6568
6569 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006570 public IIntentSender getIntentSender(int type, String packageName,
6571 int callingUid, int userId, IBinder token, String resultWho,
6572 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6573 Bundle bOptions) {
6574 synchronized (mGlobalLock) {
6575 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6576 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6577 }
6578 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006579
6580 @Override
6581 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6582 synchronized (mGlobalLock) {
6583 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6584 if (r == null) {
6585 return null;
6586 }
6587 if (r.mServiceConnectionsHolder == null) {
6588 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6589 ActivityTaskManagerService.this, r);
6590 }
6591
6592 return r.mServiceConnectionsHolder;
6593 }
6594 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006595
6596 @Override
6597 public Intent getHomeIntent() {
6598 synchronized (mGlobalLock) {
6599 return ActivityTaskManagerService.this.getHomeIntent();
6600 }
6601 }
6602
6603 @Override
6604 public boolean startHomeActivity(int userId, String reason) {
6605 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006606 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006607 }
6608 }
6609
6610 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006611 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006612 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006613 synchronized (mGlobalLock) {
6614 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006615 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006616 }
Chilun8b1f1be2019-03-13 17:14:36 +08006617 }
6618
6619 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006620 public boolean startHomeOnAllDisplays(int userId, String reason) {
6621 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006622 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006623 }
6624 }
6625
Riddle Hsua0536432019-02-16 00:38:59 +08006626 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006627 @Override
6628 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006629 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006630 if (mFactoryTest == FACTORY_TEST_OFF) {
6631 return false;
6632 }
6633 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6634 && wpc.mName.equals(mTopComponent.getPackageName())) {
6635 return true;
6636 }
6637 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6638 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6639 }
6640 }
6641
6642 @Override
6643 public void updateTopComponentForFactoryTest() {
6644 synchronized (mGlobalLock) {
6645 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6646 return;
6647 }
6648 final ResolveInfo ri = mContext.getPackageManager()
6649 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6650 final CharSequence errorMsg;
6651 if (ri != null) {
6652 final ActivityInfo ai = ri.activityInfo;
6653 final ApplicationInfo app = ai.applicationInfo;
6654 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6655 mTopAction = Intent.ACTION_FACTORY_TEST;
6656 mTopData = null;
6657 mTopComponent = new ComponentName(app.packageName, ai.name);
6658 errorMsg = null;
6659 } else {
6660 errorMsg = mContext.getResources().getText(
6661 com.android.internal.R.string.factorytest_not_system);
6662 }
6663 } else {
6664 errorMsg = mContext.getResources().getText(
6665 com.android.internal.R.string.factorytest_no_action);
6666 }
6667 if (errorMsg == null) {
6668 return;
6669 }
6670
6671 mTopAction = null;
6672 mTopData = null;
6673 mTopComponent = null;
6674 mUiHandler.post(() -> {
6675 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6676 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006677 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006678 });
6679 }
6680 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006681
Riddle Hsua0536432019-02-16 00:38:59 +08006682 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 @Override
6684 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6685 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006686 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006687 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006688 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689
6690 wpc.clearRecentTasks();
6691 wpc.clearActivities();
6692
6693 if (wpc.isInstrumenting()) {
6694 finishInstrumentationCallback.run();
6695 }
6696
Jorim Jaggid0752812018-10-16 16:07:20 +02006697 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006698 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006699 try {
6700 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6701 // If there was nothing to resume, and we are not already restarting
6702 // this process, but there is a visible activity that is hosted by the
6703 // process...then make sure all visible activities are running, taking
6704 // care of restarting this process.
6705 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6706 !PRESERVE_WINDOWS);
6707 }
6708 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006709 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006710 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006711 }
6712 }
6713 }
6714
6715 @Override
6716 public void closeSystemDialogs(String reason) {
6717 enforceNotIsolatedCaller("closeSystemDialogs");
6718
6719 final int pid = Binder.getCallingPid();
6720 final int uid = Binder.getCallingUid();
6721 final long origId = Binder.clearCallingIdentity();
6722 try {
6723 synchronized (mGlobalLock) {
6724 // Only allow this from foreground processes, so that background
6725 // applications can't abuse it to prevent system UI from being shown.
6726 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006727 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006728 if (!proc.isPerceptible()) {
6729 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6730 + " from background process " + proc);
6731 return;
6732 }
6733 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 mWindowManager.closeSystemDialogs(reason);
6735
Wale Ogunwaled32da472018-11-16 07:19:28 -08006736 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006738 // Call into AM outside the synchronized block.
6739 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 } finally {
6741 Binder.restoreCallingIdentity(origId);
6742 }
6743 }
6744
6745 @Override
6746 public void cleanupDisabledPackageComponents(
6747 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6748 synchronized (mGlobalLock) {
6749 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006750 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006752 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753 mStackSupervisor.scheduleIdleLocked();
6754 }
6755
6756 // Clean-up disabled tasks
6757 getRecentTasks().cleanupDisabledPackageTasksLocked(
6758 packageName, disabledClasses, userId);
6759 }
6760 }
6761
6762 @Override
6763 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6764 int userId) {
6765 synchronized (mGlobalLock) {
6766
6767 boolean didSomething =
6768 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006769 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 null, doit, evenPersistent, userId);
6771 return didSomething;
6772 }
6773 }
6774
6775 @Override
6776 public void resumeTopActivities(boolean scheduleIdle) {
6777 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006778 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 if (scheduleIdle) {
6780 mStackSupervisor.scheduleIdleLocked();
6781 }
6782 }
6783 }
6784
Riddle Hsua0536432019-02-16 00:38:59 +08006785 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 @Override
6787 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006788 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6790 }
6791 }
6792
Riddle Hsua0536432019-02-16 00:38:59 +08006793 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006794 @Override
6795 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006796 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 }
6799 }
6800
6801 @Override
6802 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6803 try {
6804 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6805 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6806 }
6807 } catch (RemoteException ex) {
6808 throw new SecurityException("Fail to check is caller a privileged app", ex);
6809 }
6810
6811 synchronized (mGlobalLock) {
6812 final long ident = Binder.clearCallingIdentity();
6813 try {
6814 if (mAmInternal.shouldConfirmCredentials(userId)) {
6815 if (mKeyguardController.isKeyguardLocked()) {
6816 // Showing launcher to avoid user entering credential twice.
6817 startHomeActivity(currentUserId, "notifyLockedProfile");
6818 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006819 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 } finally {
6822 Binder.restoreCallingIdentity(ident);
6823 }
6824 }
6825 }
6826
6827 @Override
6828 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6829 mAmInternal.enforceCallingPermission(
6830 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6831
6832 synchronized (mGlobalLock) {
6833 final long ident = Binder.clearCallingIdentity();
6834 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006835 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6836 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6839 UserHandle.CURRENT);
6840 } finally {
6841 Binder.restoreCallingIdentity(ident);
6842 }
6843 }
6844 }
6845
6846 @Override
6847 public void writeActivitiesToProto(ProtoOutputStream proto) {
6848 synchronized (mGlobalLock) {
6849 // The output proto of "activity --proto activities"
6850 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006851 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006852 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6853 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 }
6855 }
6856
6857 @Override
6858 public void saveANRState(String reason) {
6859 synchronized (mGlobalLock) {
6860 final StringWriter sw = new StringWriter();
6861 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6862 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6863 if (reason != null) {
6864 pw.println(" Reason: " + reason);
6865 }
6866 pw.println();
6867 getActivityStartController().dump(pw, " ", null);
6868 pw.println();
6869 pw.println("-------------------------------------------------------------------------------");
6870 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6871 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6872 "" /* header */);
6873 pw.println();
6874 pw.close();
6875
6876 mLastANRState = sw.toString();
6877 }
6878 }
6879
6880 @Override
6881 public void clearSavedANRState() {
6882 synchronized (mGlobalLock) {
6883 mLastANRState = null;
6884 }
6885 }
6886
6887 @Override
6888 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6889 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6890 synchronized (mGlobalLock) {
6891 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6892 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6893 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6894 dumpLastANRLocked(pw);
6895 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6896 dumpLastANRTracesLocked(pw);
6897 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6898 dumpActivityStarterLocked(pw, dumpPackage);
6899 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6900 dumpActivityContainersLocked(pw);
6901 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6902 if (getRecentTasks() != null) {
6903 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6904 }
6905 }
6906 }
6907 }
6908
6909 @Override
6910 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6911 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6912 int wakefulness) {
6913 synchronized (mGlobalLock) {
6914 if (mHomeProcess != null && (dumpPackage == null
6915 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6916 if (needSep) {
6917 pw.println();
6918 needSep = false;
6919 }
6920 pw.println(" mHomeProcess: " + mHomeProcess);
6921 }
6922 if (mPreviousProcess != null && (dumpPackage == null
6923 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6924 if (needSep) {
6925 pw.println();
6926 needSep = false;
6927 }
6928 pw.println(" mPreviousProcess: " + mPreviousProcess);
6929 }
6930 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6931 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6932 StringBuilder sb = new StringBuilder(128);
6933 sb.append(" mPreviousProcessVisibleTime: ");
6934 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6935 pw.println(sb);
6936 }
6937 if (mHeavyWeightProcess != null && (dumpPackage == null
6938 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6939 if (needSep) {
6940 pw.println();
6941 needSep = false;
6942 }
6943 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6944 }
6945 if (dumpPackage == null) {
6946 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006947 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006948 }
6949 if (dumpAll) {
6950 if (dumpPackage == null) {
6951 pw.println(" mConfigWillChange: "
6952 + getTopDisplayFocusedStack().mConfigWillChange);
6953 }
6954 if (mCompatModePackages.getPackages().size() > 0) {
6955 boolean printed = false;
6956 for (Map.Entry<String, Integer> entry
6957 : mCompatModePackages.getPackages().entrySet()) {
6958 String pkg = entry.getKey();
6959 int mode = entry.getValue();
6960 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6961 continue;
6962 }
6963 if (!printed) {
6964 pw.println(" mScreenCompatPackages:");
6965 printed = true;
6966 }
6967 pw.println(" " + pkg + ": " + mode);
6968 }
6969 }
6970 }
6971
6972 if (dumpPackage == null) {
6973 pw.println(" mWakefulness="
6974 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006975 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006976 if (mRunningVoice != null) {
6977 pw.println(" mRunningVoice=" + mRunningVoice);
6978 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6979 }
6980 pw.println(" mSleeping=" + mSleeping);
6981 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6982 pw.println(" mVrController=" + mVrController);
6983 }
6984 if (mCurAppTimeTracker != null) {
6985 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6986 }
6987 if (mAllowAppSwitchUids.size() > 0) {
6988 boolean printed = false;
6989 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6990 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6991 for (int j = 0; j < types.size(); j++) {
6992 if (dumpPackage == null ||
6993 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6994 if (needSep) {
6995 pw.println();
6996 needSep = false;
6997 }
6998 if (!printed) {
6999 pw.println(" mAllowAppSwitchUids:");
7000 printed = true;
7001 }
7002 pw.print(" User ");
7003 pw.print(mAllowAppSwitchUids.keyAt(i));
7004 pw.print(": Type ");
7005 pw.print(types.keyAt(j));
7006 pw.print(" = ");
7007 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7008 pw.println();
7009 }
7010 }
7011 }
7012 }
7013 if (dumpPackage == null) {
7014 if (mController != null) {
7015 pw.println(" mController=" + mController
7016 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7017 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007018 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7019 pw.println(" mLaunchingActivityWakeLock="
7020 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007021 }
7022
7023 return needSep;
7024 }
7025 }
7026
7027 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007028 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7029 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 synchronized (mGlobalLock) {
7031 if (dumpPackage == null) {
7032 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7033 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007034 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7035 if (mRunningVoice != null) {
7036 final long vrToken = proto.start(
7037 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7038 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7039 mRunningVoice.toString());
7040 mVoiceWakeLock.writeToProto(
7041 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7042 proto.end(vrToken);
7043 }
7044 mVrController.writeToProto(proto,
7045 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007046 if (mController != null) {
7047 final long token = proto.start(CONTROLLER);
7048 proto.write(CONTROLLER, mController.toString());
7049 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7050 proto.end(token);
7051 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007052 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7053 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7054 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007055 }
7056
7057 if (mHomeProcess != null && (dumpPackage == null
7058 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007059 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007060 }
7061
7062 if (mPreviousProcess != null && (dumpPackage == null
7063 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007064 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007065 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7066 }
7067
7068 if (mHeavyWeightProcess != null && (dumpPackage == null
7069 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007070 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007071 }
7072
7073 for (Map.Entry<String, Integer> entry
7074 : mCompatModePackages.getPackages().entrySet()) {
7075 String pkg = entry.getKey();
7076 int mode = entry.getValue();
7077 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7078 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7079 proto.write(PACKAGE, pkg);
7080 proto.write(MODE, mode);
7081 proto.end(compatToken);
7082 }
7083 }
7084
7085 if (mCurAppTimeTracker != null) {
7086 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7087 }
7088
7089 }
7090 }
7091
7092 @Override
7093 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7094 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7095 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007096 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7097 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 }
7099
7100 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007101 public void dumpForOom(PrintWriter pw) {
7102 synchronized (mGlobalLock) {
7103 pw.println(" mHomeProcess: " + mHomeProcess);
7104 pw.println(" mPreviousProcess: " + mPreviousProcess);
7105 if (mHeavyWeightProcess != null) {
7106 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7107 }
7108 }
7109 }
7110
7111 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 public boolean canGcNow() {
7113 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007114 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 }
7116 }
7117
Riddle Hsua0536432019-02-16 00:38:59 +08007118 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 @Override
7120 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007121 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007122 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007123 return top != null ? top.app : null;
7124 }
7125 }
7126
Riddle Hsua0536432019-02-16 00:38:59 +08007127 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007128 @Override
7129 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007130 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007131 if (mRootActivityContainer != null) {
7132 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007133 }
7134 }
7135 }
7136
7137 @Override
7138 public void scheduleDestroyAllActivities(String reason) {
7139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007140 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 }
7142 }
7143
7144 @Override
7145 public void removeUser(int userId) {
7146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007147 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007148 }
7149 }
7150
7151 @Override
7152 public boolean switchUser(int userId, UserState userState) {
7153 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007154 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 }
7156 }
7157
7158 @Override
7159 public void onHandleAppCrash(WindowProcessController wpc) {
7160 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007161 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 }
7163 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007164
7165 @Override
7166 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7167 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007168 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007169 }
7170 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007171
Riddle Hsua0536432019-02-16 00:38:59 +08007172 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007173 @Override
7174 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007175 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007176 }
7177
Riddle Hsua0536432019-02-16 00:38:59 +08007178 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007179 @Override
7180 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007181 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007182 }
7183
Riddle Hsua0536432019-02-16 00:38:59 +08007184 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007185 @Override
7186 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007187 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007188 }
7189
Riddle Hsua0536432019-02-16 00:38:59 +08007190 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007191 @Override
7192 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007193 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007194 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007195
7196 @Override
7197 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007198 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007199 mPendingTempWhitelist.put(uid, tag);
7200 }
7201 }
7202
7203 @Override
7204 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007205 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007206 mPendingTempWhitelist.remove(uid);
7207 }
7208 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007209
7210 @Override
7211 public boolean handleAppCrashInActivityController(String processName, int pid,
7212 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7213 Runnable killCrashingAppCallback) {
7214 synchronized (mGlobalLock) {
7215 if (mController == null) {
7216 return false;
7217 }
7218
7219 try {
7220 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7221 stackTrace)) {
7222 killCrashingAppCallback.run();
7223 return true;
7224 }
7225 } catch (RemoteException e) {
7226 mController = null;
7227 Watchdog.getInstance().setActivityController(null);
7228 }
7229 return false;
7230 }
7231 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007232
7233 @Override
7234 public void removeRecentTasksByPackageName(String packageName, int userId) {
7235 synchronized (mGlobalLock) {
7236 mRecentTasks.removeTasksByPackageName(packageName, userId);
7237 }
7238 }
7239
7240 @Override
7241 public void cleanupRecentTasksForUser(int userId) {
7242 synchronized (mGlobalLock) {
7243 mRecentTasks.cleanupLocked(userId);
7244 }
7245 }
7246
7247 @Override
7248 public void loadRecentTasksForUser(int userId) {
7249 synchronized (mGlobalLock) {
7250 mRecentTasks.loadUserRecentsLocked(userId);
7251 }
7252 }
7253
7254 @Override
7255 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7256 synchronized (mGlobalLock) {
7257 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7258 }
7259 }
7260
7261 @Override
7262 public void flushRecentTasks() {
7263 mRecentTasks.flush();
7264 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007265
7266 @Override
7267 public WindowProcessController getHomeProcess() {
7268 synchronized (mGlobalLock) {
7269 return mHomeProcess;
7270 }
7271 }
7272
7273 @Override
7274 public WindowProcessController getPreviousProcess() {
7275 synchronized (mGlobalLock) {
7276 return mPreviousProcess;
7277 }
7278 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007279
7280 @Override
7281 public void clearLockedTasks(String reason) {
7282 synchronized (mGlobalLock) {
7283 getLockTaskController().clearLockedTasks(reason);
7284 }
7285 }
7286
7287 @Override
7288 public void updateUserConfiguration() {
7289 synchronized (mGlobalLock) {
7290 final Configuration configuration = new Configuration(getGlobalConfiguration());
7291 final int currentUserId = mAmInternal.getCurrentUserId();
7292 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7293 configuration, currentUserId, Settings.System.canWrite(mContext));
7294 updateConfigurationLocked(configuration, null /* starting */,
7295 false /* initLocale */, false /* persistent */, currentUserId,
7296 false /* deferResume */);
7297 }
7298 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007299
7300 @Override
7301 public boolean canShowErrorDialogs() {
7302 synchronized (mGlobalLock) {
7303 return mShowDialogs && !mSleeping && !mShuttingDown
7304 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7305 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7306 mAmInternal.getCurrentUserId())
7307 && !(UserManager.isDeviceInDemoMode(mContext)
7308 && mAmInternal.getCurrentUser().isDemo());
7309 }
7310 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007311
7312 @Override
7313 public void setProfileApp(String profileApp) {
7314 synchronized (mGlobalLock) {
7315 mProfileApp = profileApp;
7316 }
7317 }
7318
7319 @Override
7320 public void setProfileProc(WindowProcessController wpc) {
7321 synchronized (mGlobalLock) {
7322 mProfileProc = wpc;
7323 }
7324 }
7325
7326 @Override
7327 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7328 synchronized (mGlobalLock) {
7329 mProfilerInfo = profilerInfo;
7330 }
7331 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007332
7333 @Override
7334 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7335 synchronized (mGlobalLock) {
7336 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7337 }
7338 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007339
7340 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007341 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7342 boolean reducedResolution) {
7343 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7344 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007345 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007346
7347 @Override
7348 public boolean isUidForeground(int uid) {
7349 synchronized (mGlobalLock) {
7350 return ActivityTaskManagerService.this.isUidForeground(uid);
7351 }
7352 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007353
7354 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007355 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007356 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007357 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007358 }
7359 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007360
7361 @Override
7362 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007363 // Translate package names into UIDs
7364 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007365 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007366 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7367 if (uid >= 0) {
7368 result.add(uid);
7369 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007370 }
7371 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007372 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007373 }
7374 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007375 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007376}