blob: ed7e12c005157ac62b71dc31f9b716eb8767697a [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 Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070087import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
88import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
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;
552 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
574
575 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
576
577 // VR Vr2d Display Id.
578 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700579
Wale Ogunwalef6733932018-06-27 05:14:34 -0700580 /**
581 * Set while we are wanting to sleep, to prevent any
582 * activities from being started/resumed.
583 *
584 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
585 *
586 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
587 * while in the sleep state until there is a pending transition out of sleep, in which case
588 * mSleeping is set to false, and remains false while awake.
589 *
590 * Whether mSleeping can quickly toggled between true/false without the device actually
591 * display changing states is undefined.
592 */
593 private boolean mSleeping = false;
594
595 /**
596 * The process state used for processes that are running the top activities.
597 * This changes between TOP and TOP_SLEEPING to following mSleeping.
598 */
599 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
600
601 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
602 // automatically. Important for devices without direct input devices.
603 private boolean mShowDialogs = true;
604
605 /** Set if we are shutting down the system, similar to sleeping. */
606 boolean mShuttingDown = false;
607
608 /**
609 * We want to hold a wake lock while running a voice interaction session, since
610 * this may happen with the screen off and we need to keep the CPU running to
611 * be able to continue to interact with the user.
612 */
613 PowerManager.WakeLock mVoiceWakeLock;
614
615 /**
616 * Set while we are running a voice interaction. This overrides sleeping while it is active.
617 */
618 IVoiceInteractionSession mRunningVoice;
619
620 /**
621 * The last resumed activity. This is identical to the current resumed activity most
622 * of the time but could be different when we're pausing one activity before we resume
623 * another activity.
624 */
625 ActivityRecord mLastResumedActivity;
626
627 /**
628 * The activity that is currently being traced as the active resumed activity.
629 *
630 * @see #updateResumedAppTrace
631 */
632 private @Nullable ActivityRecord mTracedResumedActivity;
633
634 /** If non-null, we are tracking the time the user spends in the currently focused app. */
635 AppTimeTracker mCurAppTimeTracker;
636
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700637 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700638
Wale Ogunwale53783742018-09-16 10:21:51 -0700639 /**
640 * Packages that the user has asked to have run in screen size
641 * compatibility mode instead of filling the screen.
642 */
643 CompatModePackages mCompatModePackages;
644
Wale Ogunwalef6733932018-06-27 05:14:34 -0700645 private FontScaleSettingObserver mFontScaleSettingObserver;
646
Ricky Wai96f5c352019-04-10 18:40:17 +0100647 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000648
Wale Ogunwalef6733932018-06-27 05:14:34 -0700649 private final class FontScaleSettingObserver extends ContentObserver {
650 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
651 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
652
653 public FontScaleSettingObserver() {
654 super(mH);
655 final ContentResolver resolver = mContext.getContentResolver();
656 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
657 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
658 UserHandle.USER_ALL);
659 }
660
661 @Override
662 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
663 if (mFontScaleUri.equals(uri)) {
664 updateFontScaleIfNeeded(userId);
665 } else if (mHideErrorDialogsUri.equals(uri)) {
666 synchronized (mGlobalLock) {
667 updateShouldShowDialogsLocked(getGlobalConfiguration());
668 }
669 }
670 }
671 }
672
Riddle Hsua0536432019-02-16 00:38:59 +0800673 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
674 @Target(ElementType.METHOD)
675 @Retention(RetentionPolicy.SOURCE)
676 @interface HotPath {
677 int NONE = 0;
678 int OOM_ADJUSTMENT = 1;
679 int LRU_UPDATE = 2;
680 int PROCESS_CHANGE = 3;
681 int caller() default NONE;
682 }
683
Charles Chen8d98dd22018-12-26 17:36:54 +0800684 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
685 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700686 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700687 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700688 mSystemThread = ActivityThread.currentActivityThread();
689 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700690 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800691 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700692 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700693 }
694
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 public void onSystemReady() {
696 synchronized (mGlobalLock) {
697 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
698 PackageManager.FEATURE_CANT_SAVE_STATE);
699 mAssistUtils = new AssistUtils(mContext);
700 mVrController.onSystemReady();
701 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700702 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700703 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700704 }
705
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700706 public void onInitPowerManagement() {
707 synchronized (mGlobalLock) {
708 mStackSupervisor.initPowerManagement();
709 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
710 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
711 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
712 mVoiceWakeLock.setReferenceCounted(false);
713 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700714 }
715
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700716 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700717 mFontScaleSettingObserver = new FontScaleSettingObserver();
718 }
719
Wale Ogunwale59507092018-10-29 09:00:30 -0700720 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700721 final boolean freeformWindowManagement =
722 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
723 || Settings.Global.getInt(
724 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
725
726 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
727 final boolean supportsPictureInPicture = supportsMultiWindow &&
728 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
729 final boolean supportsSplitScreenMultiWindow =
730 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
731 final boolean supportsMultiDisplay = mContext.getPackageManager()
732 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
734 final boolean forceResizable = Settings.Global.getInt(
735 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
736
737 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900738 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700739
740 final Configuration configuration = new Configuration();
741 Settings.System.getConfiguration(resolver, configuration);
742 if (forceRtl) {
743 // This will take care of setting the correct layout direction flags
744 configuration.setLayoutDirection(configuration.locale);
745 }
746
747 synchronized (mGlobalLock) {
748 mForceResizableActivities = forceResizable;
749 final boolean multiWindowFormEnabled = freeformWindowManagement
750 || supportsSplitScreenMultiWindow
751 || supportsPictureInPicture
752 || supportsMultiDisplay;
753 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
754 mSupportsMultiWindow = true;
755 mSupportsFreeformWindowManagement = freeformWindowManagement;
756 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
757 mSupportsPictureInPicture = supportsPictureInPicture;
758 mSupportsMultiDisplay = supportsMultiDisplay;
759 } else {
760 mSupportsMultiWindow = false;
761 mSupportsFreeformWindowManagement = false;
762 mSupportsSplitScreenMultiWindow = false;
763 mSupportsPictureInPicture = false;
764 mSupportsMultiDisplay = false;
765 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700766 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767 // This happens before any activities are started, so we can change global configuration
768 // in-place.
769 updateConfigurationLocked(configuration, null, true);
770 final Configuration globalConfig = getGlobalConfiguration();
771 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
772
773 // Load resources only after the current configuration has been set.
774 final Resources res = mContext.getResources();
775 mThumbnailWidth = res.getDimensionPixelSize(
776 com.android.internal.R.dimen.thumbnail_width);
777 mThumbnailHeight = res.getDimensionPixelSize(
778 com.android.internal.R.dimen.thumbnail_height);
779
780 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
781 mFullscreenThumbnailScale = (float) res
782 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
783 (float) globalConfig.screenWidthDp;
784 } else {
785 mFullscreenThumbnailScale = res.getFraction(
786 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
787 }
788 }
789 }
790
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800791 public WindowManagerGlobalLock getGlobalLock() {
792 return mGlobalLock;
793 }
794
Yunfan Chen585f2932019-01-29 16:04:45 +0900795 /** For test purpose only. */
796 @VisibleForTesting
797 public ActivityTaskManagerInternal getAtmInternal() {
798 return mInternal;
799 }
800
Riddle Hsud93a6c42018-11-29 21:50:06 +0800801 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
802 Looper looper) {
803 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700804 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700806 final File systemDir = SystemServiceManager.ensureSystemDir();
807 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
808 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700809 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700810
811 mTempConfig.setToDefaults();
812 mTempConfig.setLocales(LocaleList.getDefault());
813 mConfigurationSeq = mTempConfig.seq = 1;
814 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer = new RootActivityContainer(this);
816 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700818 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700819 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700820 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700821 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700822 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700823 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700824 mKeyguardController = mStackSupervisor.getKeyguardController();
825 }
826
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700827 public void onActivityManagerInternalAdded() {
828 synchronized (mGlobalLock) {
829 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
830 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
831 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700832 }
833
Yunfan Chen75157d72018-07-27 14:47:21 +0900834 int increaseConfigurationSeqLocked() {
835 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
836 return mConfigurationSeq;
837 }
838
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 protected ActivityStackSupervisor createStackSupervisor() {
840 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
841 supervisor.initialize();
842 return supervisor;
843 }
844
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700845 public void setWindowManager(WindowManagerService wm) {
846 synchronized (mGlobalLock) {
847 mWindowManager = wm;
848 mLockTaskController.setWindowManager(wm);
849 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800850 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700852 }
853
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700854 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
855 synchronized (mGlobalLock) {
856 mUsageStatsInternal = usageStatsManager;
857 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700858 }
859
Wale Ogunwalef6733932018-06-27 05:14:34 -0700860 UserManagerService getUserManager() {
861 if (mUserManager == null) {
862 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
863 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
864 }
865 return mUserManager;
866 }
867
868 AppOpsService getAppOpsService() {
869 if (mAppOpsService == null) {
870 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
871 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
872 }
873 return mAppOpsService;
874 }
875
876 boolean hasUserRestriction(String restriction, int userId) {
877 return getUserManager().hasUserRestriction(restriction, userId);
878 }
879
Michal Karpinski15486842019-04-25 17:33:42 +0100880 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
881 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
882 callingUid, callingPackage);
883 if (mode == AppOpsManager.MODE_DEFAULT) {
884 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
885 == PERMISSION_GRANTED;
886 }
887 return mode == AppOpsManager.MODE_ALLOWED;
888 }
889
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700890 @VisibleForTesting
891 protected void setRecentTasks(RecentTasks recentTasks) {
892 mRecentTasks = recentTasks;
893 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700894 }
895
896 RecentTasks getRecentTasks() {
897 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700898 }
899
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700900 ClientLifecycleManager getLifecycleManager() {
901 return mLifecycleManager;
902 }
903
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700904 ActivityStartController getActivityStartController() {
905 return mActivityStartController;
906 }
907
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700908 TaskChangeNotificationController getTaskChangeNotificationController() {
909 return mTaskChangeNotificationController;
910 }
911
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700912 LockTaskController getLockTaskController() {
913 return mLockTaskController;
914 }
915
Yunfan Chen75157d72018-07-27 14:47:21 +0900916 /**
917 * Return the global configuration used by the process corresponding to the input pid. This is
918 * usually the global configuration with some overrides specific to that process.
919 */
920 Configuration getGlobalConfigurationForCallingPid() {
921 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800922 return getGlobalConfigurationForPid(pid);
923 }
924
925 /**
926 * Return the global configuration used by the process corresponding to the given pid.
927 */
928 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 if (pid == MY_PID || pid < 0) {
930 return getGlobalConfiguration();
931 }
932 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100933 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900934 return app != null ? app.getConfiguration() : getGlobalConfiguration();
935 }
936 }
937
938 /**
939 * Return the device configuration info used by the process corresponding to the input pid.
940 * The value is consistent with the global configuration for the process.
941 */
942 @Override
943 public ConfigurationInfo getDeviceConfigurationInfo() {
944 ConfigurationInfo config = new ConfigurationInfo();
945 synchronized (mGlobalLock) {
946 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
947 config.reqTouchScreen = globalConfig.touchscreen;
948 config.reqKeyboardType = globalConfig.keyboard;
949 config.reqNavigation = globalConfig.navigation;
950 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
951 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
953 }
954 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
955 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
956 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
957 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700958 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900959 }
960 return config;
961 }
962
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700963 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700964 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700965 }
966
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700967 public static final class Lifecycle extends SystemService {
968 private final ActivityTaskManagerService mService;
969
970 public Lifecycle(Context context) {
971 super(context);
972 mService = new ActivityTaskManagerService(context);
973 }
974
975 @Override
976 public void onStart() {
977 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700978 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700979 }
980
Garfield Tan891146c2018-10-09 12:14:00 -0700981 @Override
982 public void onUnlockUser(int userId) {
983 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800984 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700985 }
986 }
987
988 @Override
989 public void onCleanupUser(int userId) {
990 synchronized (mService.getGlobalLock()) {
991 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
992 }
993 }
994
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700995 public ActivityTaskManagerService getService() {
996 return mService;
997 }
998 }
999
1000 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001001 public final int startActivity(IApplicationThread caller, String callingPackage,
1002 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1003 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1004 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1005 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1006 UserHandle.getCallingUserId());
1007 }
1008
1009 @Override
1010 public final int startActivities(IApplicationThread caller, String callingPackage,
1011 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1012 int userId) {
1013 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001014 enforceNotIsolatedCaller(reason);
1015 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001017 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1018 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1019 reason, null /* originatingPendingIntent */,
1020 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 }
1022
1023 @Override
1024 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1025 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1026 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1027 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1028 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1029 true /*validateIncomingUser*/);
1030 }
1031
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001032 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1034 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1035 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001036 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1040
1041 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001042 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 .setCaller(caller)
1044 .setCallingPackage(callingPackage)
1045 .setResolvedType(resolvedType)
1046 .setResultTo(resultTo)
1047 .setResultWho(resultWho)
1048 .setRequestCode(requestCode)
1049 .setStartFlags(startFlags)
1050 .setProfilerInfo(profilerInfo)
1051 .setActivityOptions(bOptions)
1052 .setMayWait(userId)
1053 .execute();
1054
1055 }
1056
1057 @Override
1058 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1059 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001060 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1061 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 // Refuse possible leaked file descriptors
1063 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1064 throw new IllegalArgumentException("File descriptors passed in Intent");
1065 }
1066
1067 if (!(target instanceof PendingIntentRecord)) {
1068 throw new IllegalArgumentException("Bad PendingIntent object");
1069 }
1070
1071 PendingIntentRecord pir = (PendingIntentRecord)target;
1072
1073 synchronized (mGlobalLock) {
1074 // If this is coming from the currently resumed activity, it is
1075 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001076 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 if (stack.mResumedActivity != null &&
1078 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001079 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 }
1085
1086 @Override
1087 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1088 Bundle bOptions) {
1089 // Refuse possible leaked file descriptors
1090 if (intent != null && intent.hasFileDescriptors()) {
1091 throw new IllegalArgumentException("File descriptors passed in Intent");
1092 }
1093 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1094
1095 synchronized (mGlobalLock) {
1096 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1097 if (r == null) {
1098 SafeActivityOptions.abort(options);
1099 return false;
1100 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001101 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 // The caller is not running... d'oh!
1103 SafeActivityOptions.abort(options);
1104 return false;
1105 }
1106 intent = new Intent(intent);
1107 // The caller is not allowed to change the data.
1108 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1109 // And we are resetting to find the next component...
1110 intent.setComponent(null);
1111
1112 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1113
1114 ActivityInfo aInfo = null;
1115 try {
1116 List<ResolveInfo> resolves =
1117 AppGlobals.getPackageManager().queryIntentActivities(
1118 intent, r.resolvedType,
1119 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1120 UserHandle.getCallingUserId()).getList();
1121
1122 // Look for the original activity in the list...
1123 final int N = resolves != null ? resolves.size() : 0;
1124 for (int i=0; i<N; i++) {
1125 ResolveInfo rInfo = resolves.get(i);
1126 if (rInfo.activityInfo.packageName.equals(r.packageName)
1127 && rInfo.activityInfo.name.equals(r.info.name)) {
1128 // We found the current one... the next matching is
1129 // after it.
1130 i++;
1131 if (i<N) {
1132 aInfo = resolves.get(i).activityInfo;
1133 }
1134 if (debug) {
1135 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1136 + "/" + r.info.name);
1137 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1138 ? "null" : aInfo.packageName + "/" + aInfo.name));
1139 }
1140 break;
1141 }
1142 }
1143 } catch (RemoteException e) {
1144 }
1145
1146 if (aInfo == null) {
1147 // Nobody who is next!
1148 SafeActivityOptions.abort(options);
1149 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1150 return false;
1151 }
1152
1153 intent.setComponent(new ComponentName(
1154 aInfo.applicationInfo.packageName, aInfo.name));
1155 intent.setFlags(intent.getFlags()&~(
1156 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1157 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1158 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1159 FLAG_ACTIVITY_NEW_TASK));
1160
1161 // Okay now we need to start the new activity, replacing the currently running activity.
1162 // This is a little tricky because we want to start the new one as if the current one is
1163 // finished, but not finish the current one first so that there is no flicker.
1164 // And thus...
1165 final boolean wasFinishing = r.finishing;
1166 r.finishing = true;
1167
1168 // Propagate reply information over to the new activity.
1169 final ActivityRecord resultTo = r.resultTo;
1170 final String resultWho = r.resultWho;
1171 final int requestCode = r.requestCode;
1172 r.resultTo = null;
1173 if (resultTo != null) {
1174 resultTo.removeResultsLocked(r, resultWho, requestCode);
1175 }
1176
1177 final long origId = Binder.clearCallingIdentity();
1178 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001179 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001181 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 .setResolvedType(r.resolvedType)
1183 .setActivityInfo(aInfo)
1184 .setResultTo(resultTo != null ? resultTo.appToken : null)
1185 .setResultWho(resultWho)
1186 .setRequestCode(requestCode)
1187 .setCallingPid(-1)
1188 .setCallingUid(r.launchedFromUid)
1189 .setCallingPackage(r.launchedFromPackage)
1190 .setRealCallingPid(-1)
1191 .setRealCallingUid(r.launchedFromUid)
1192 .setActivityOptions(options)
1193 .execute();
1194 Binder.restoreCallingIdentity(origId);
1195
1196 r.finishing = wasFinishing;
1197 if (res != ActivityManager.START_SUCCESS) {
1198 return false;
1199 }
1200 return true;
1201 }
1202 }
1203
1204 @Override
1205 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1206 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1207 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1208 final WaitResult res = new WaitResult();
1209 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001210 enforceNotIsolatedCaller("startActivityAndWait");
1211 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1212 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001214 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 .setCaller(caller)
1216 .setCallingPackage(callingPackage)
1217 .setResolvedType(resolvedType)
1218 .setResultTo(resultTo)
1219 .setResultWho(resultWho)
1220 .setRequestCode(requestCode)
1221 .setStartFlags(startFlags)
1222 .setActivityOptions(bOptions)
1223 .setMayWait(userId)
1224 .setProfilerInfo(profilerInfo)
1225 .setWaitResult(res)
1226 .execute();
1227 }
1228 return res;
1229 }
1230
1231 @Override
1232 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1233 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1234 int startFlags, Configuration config, Bundle bOptions, int userId) {
1235 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001236 enforceNotIsolatedCaller("startActivityWithConfig");
1237 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1238 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001240 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001241 .setCaller(caller)
1242 .setCallingPackage(callingPackage)
1243 .setResolvedType(resolvedType)
1244 .setResultTo(resultTo)
1245 .setResultWho(resultWho)
1246 .setRequestCode(requestCode)
1247 .setStartFlags(startFlags)
1248 .setGlobalConfiguration(config)
1249 .setActivityOptions(bOptions)
1250 .setMayWait(userId)
1251 .execute();
1252 }
1253 }
1254
Alison Cichowlas3e340502018-08-07 17:15:01 -04001255
1256 @Override
1257 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1258 int callingUid = Binder.getCallingUid();
1259 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1260 throw new SecurityException("Only the system process can request a permission token, "
1261 + "received request from uid: " + callingUid);
1262 }
1263 IBinder permissionToken = new Binder();
1264 synchronized (mGlobalLock) {
1265 mStartActivitySources.put(permissionToken, delegatorToken);
1266 }
1267
1268 Message expireMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1271
1272 Message forgetMsg = PooledLambda.obtainMessage(
1273 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1274 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1275
1276 return permissionToken;
1277 }
1278
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 @Override
1280 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1281 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1283 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285 // permission grants) as any app that may launch one of your own activities. So we only
1286 // allow this in two cases:
1287 // 1) The caller is an activity that is part of the core framework, and then only when it
1288 // is running as the system.
1289 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1290 // can only be requested by a system activity, which may then delegate this call to
1291 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 final ActivityRecord sourceRecord;
1293 final int targetUid;
1294 final String targetPackage;
1295 final boolean isResolver;
1296 synchronized (mGlobalLock) {
1297 if (resultTo == null) {
1298 throw new SecurityException("Must be called from an activity");
1299 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001300 final IBinder sourceToken;
1301 if (permissionToken != null) {
1302 // To even attempt to use a permissionToken, an app must also have this signature
1303 // permission.
1304 mAmInternal.enforceCallingPermission(
1305 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1306 "startActivityAsCaller");
1307 // If called with a permissionToken, we want the sourceRecord from the delegator
1308 // activity that requested this token.
1309 sourceToken = mStartActivitySources.remove(permissionToken);
1310 if (sourceToken == null) {
1311 // Invalid permissionToken, check if it recently expired.
1312 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1313 throw new SecurityException("Called with expired permission token: "
1314 + permissionToken);
1315 } else {
1316 throw new SecurityException("Called with invalid permission token: "
1317 + permissionToken);
1318 }
1319 }
1320 } else {
1321 // This method was called directly by the source.
1322 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001324
Wale Ogunwaled32da472018-11-16 07:19:28 -08001325 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001326 if (sourceRecord == null) {
1327 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001328 }
1329 if (sourceRecord.app == null) {
1330 throw new SecurityException("Called without a process attached to activity");
1331 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001332
1333 // Whether called directly or from a delegate, the source activity must be from the
1334 // android package.
1335 if (!sourceRecord.info.packageName.equals("android")) {
1336 throw new SecurityException("Must be called from an activity that is "
1337 + "declared in the android package");
1338 }
1339
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 // This is still okay, as long as this activity is running under the
1342 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001343 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001345 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 + " must be system uid or original calling uid "
1347 + sourceRecord.launchedFromUid);
1348 }
1349 }
1350 if (ignoreTargetSecurity) {
1351 if (intent.getComponent() == null) {
1352 throw new SecurityException(
1353 "Component must be specified with ignoreTargetSecurity");
1354 }
1355 if (intent.getSelector() != null) {
1356 throw new SecurityException(
1357 "Selector not allowed with ignoreTargetSecurity");
1358 }
1359 }
1360 targetUid = sourceRecord.launchedFromUid;
1361 targetPackage = sourceRecord.launchedFromPackage;
1362 isResolver = sourceRecord.isResolverOrChildActivity();
1363 }
1364
1365 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001366 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 }
1368
1369 // TODO: Switch to user app stacks here.
1370 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001371 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 .setCallingUid(targetUid)
1373 .setCallingPackage(targetPackage)
1374 .setResolvedType(resolvedType)
1375 .setResultTo(resultTo)
1376 .setResultWho(resultWho)
1377 .setRequestCode(requestCode)
1378 .setStartFlags(startFlags)
1379 .setActivityOptions(bOptions)
1380 .setMayWait(userId)
1381 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1382 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001383 // The target may well be in the background, which would normally prevent it
1384 // from starting an activity. Here we definitely want the start to succeed.
1385 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 .execute();
1387 } catch (SecurityException e) {
1388 // XXX need to figure out how to propagate to original app.
1389 // A SecurityException here is generally actually a fault of the original
1390 // calling activity (such as a fairly granting permissions), so propagate it
1391 // back to them.
1392 /*
1393 StringBuilder msg = new StringBuilder();
1394 msg.append("While launching");
1395 msg.append(intent.toString());
1396 msg.append(": ");
1397 msg.append(e.getMessage());
1398 */
1399 throw e;
1400 }
1401 }
1402
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001403 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1404 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1405 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1406 }
1407
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 @Override
1409 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1410 Intent intent, String resolvedType, IVoiceInteractionSession session,
1411 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1412 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 if (session == null || interactor == null) {
1415 throw new NullPointerException("null session or interactor");
1416 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001417 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001419 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 .setCallingUid(callingUid)
1421 .setCallingPackage(callingPackage)
1422 .setResolvedType(resolvedType)
1423 .setVoiceSession(session)
1424 .setVoiceInteractor(interactor)
1425 .setStartFlags(startFlags)
1426 .setProfilerInfo(profilerInfo)
1427 .setActivityOptions(bOptions)
1428 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001429 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 .execute();
1431 }
1432
1433 @Override
1434 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1437 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001439 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 .setCallingUid(callingUid)
1441 .setCallingPackage(callingPackage)
1442 .setResolvedType(resolvedType)
1443 .setActivityOptions(bOptions)
1444 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001445 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .execute();
1447 }
1448
Riddle Hsu609a8e22019-06-27 16:46:29 -06001449 /**
1450 * Start the recents activity to perform the recents animation.
1451 *
1452 * @param intent The intent to start the recents activity.
1453 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1454 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001456 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1457 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001460 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 final long origId = Binder.clearCallingIdentity();
1462 try {
1463 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001464 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1465 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001466 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467
1468 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001469 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001470 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001471 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001472 if (recentsAnimationRunner == null) {
1473 anim.preloadRecentsActivity();
1474 } else {
1475 anim.startRecentsActivity(recentsAnimationRunner);
1476 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 }
1478 } finally {
1479 Binder.restoreCallingIdentity(origId);
1480 }
1481 }
1482
1483 @Override
1484 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001485 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486 "startActivityFromRecents()");
1487
1488 final int callingPid = Binder.getCallingPid();
1489 final int callingUid = Binder.getCallingUid();
1490 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1491 final long origId = Binder.clearCallingIdentity();
1492 try {
1493 synchronized (mGlobalLock) {
1494 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1495 safeOptions);
1496 }
1497 } finally {
1498 Binder.restoreCallingIdentity(origId);
1499 }
1500 }
1501
1502 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001503 * Public API to check if the client is allowed to start an activity on specified display.
1504 *
1505 * If the target display is private or virtual, some restrictions will apply.
1506 *
1507 * @param displayId Target display id.
1508 * @param intent Intent used to launch the activity.
1509 * @param resolvedType The MIME type of the intent.
1510 * @param userId The id of the user for whom the call is made.
1511 * @return {@code true} if a call to start an activity on the target display should succeed and
1512 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1513 */
1514 @Override
1515 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1516 String resolvedType, int userId) {
1517 final int callingUid = Binder.getCallingUid();
1518 final int callingPid = Binder.getCallingPid();
1519 final long origId = Binder.clearCallingIdentity();
1520
1521 try {
1522 // Collect information about the target of the Intent.
1523 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1524 0 /* startFlags */, null /* profilerInfo */, userId,
1525 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1526 UserHandle.USER_NULL));
1527 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1528
1529 synchronized (mGlobalLock) {
1530 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1531 aInfo);
1532 }
1533 } finally {
1534 Binder.restoreCallingIdentity(origId);
1535 }
1536 }
1537
1538 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 * This is the internal entry point for handling Activity.finish().
1540 *
1541 * @param token The Binder token referencing the Activity we want to finish.
1542 * @param resultCode Result code, if any, from this Activity.
1543 * @param resultData Result data (Intent), if any, from this Activity.
1544 * @param finishTask Whether to finish the task associated with this Activity.
1545 *
1546 * @return Returns true if the activity successfully finished, or false if it is still running.
1547 */
1548 @Override
1549 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1550 int finishTask) {
1551 // Refuse possible leaked file descriptors
1552 if (resultData != null && resultData.hasFileDescriptors()) {
1553 throw new IllegalArgumentException("File descriptors passed in Intent");
1554 }
1555
1556 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001557 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 if (r == null) {
1559 return true;
1560 }
1561 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001562 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001563 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564 if (rootR == null) {
1565 Slog.w(TAG, "Finishing task with all activities already finished");
1566 }
1567 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1568 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001569 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 return false;
1571 }
1572
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001573 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1574 // We should consolidate.
1575 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001577 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 if (next != null) {
1579 // ask watcher if this is allowed
1580 boolean resumeOK = true;
1581 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001582 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001584 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 Watchdog.getInstance().setActivityController(null);
1586 }
1587
1588 if (!resumeOK) {
1589 Slog.i(TAG, "Not finishing activity because controller resumed");
1590 return false;
1591 }
1592 }
1593 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001594
1595 // note down that the process has finished an activity and is in background activity
1596 // starts grace period
1597 if (r.app != null) {
1598 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1599 }
1600
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 final long origId = Binder.clearCallingIdentity();
1602 try {
1603 boolean res;
1604 final boolean finishWithRootActivity =
1605 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1606 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1607 || (finishWithRootActivity && r == rootR)) {
1608 // If requested, remove the task that is associated to this activity only if it
1609 // was the root activity in the task. The result code and data is ignored
1610 // because we don't support returning them across task boundaries. Also, to
1611 // keep backwards compatibility we remove the task from recents when finishing
1612 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001613 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 finishWithRootActivity, "finish-activity");
1615 if (!res) {
1616 Slog.i(TAG, "Removing task failed to finish activity");
1617 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001618 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001619 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001621 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001622 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 if (!res) {
1624 Slog.i(TAG, "Failed to finish by app-request");
1625 }
1626 }
1627 return res;
1628 } finally {
1629 Binder.restoreCallingIdentity(origId);
1630 }
1631 }
1632 }
1633
1634 @Override
1635 public boolean finishActivityAffinity(IBinder token) {
1636 synchronized (mGlobalLock) {
1637 final long origId = Binder.clearCallingIdentity();
1638 try {
1639 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1640 if (r == null) {
1641 return false;
1642 }
1643
1644 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1645 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001646 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 return false;
1648 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001649 r.finishActivityAffinity();
1650 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 } finally {
1652 Binder.restoreCallingIdentity(origId);
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1659 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001660 try {
1661 WindowProcessController proc = null;
1662 synchronized (mGlobalLock) {
1663 ActivityStack stack = ActivityRecord.getStackLocked(token);
1664 if (stack == null) {
1665 return;
1666 }
1667 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1668 false /* fromTimeout */, false /* processPausingActivities */, config);
1669 if (r != null) {
1670 proc = r.app;
1671 }
1672 if (stopProfiling && proc != null) {
1673 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
1675 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001676 } finally {
1677 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 }
1680
1681 @Override
1682 public final void activityResumed(IBinder token) {
1683 final long origId = Binder.clearCallingIdentity();
1684 synchronized (mGlobalLock) {
1685 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001686 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 }
1688 Binder.restoreCallingIdentity(origId);
1689 }
1690
1691 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001692 public final void activityTopResumedStateLost() {
1693 final long origId = Binder.clearCallingIdentity();
1694 synchronized (mGlobalLock) {
1695 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1696 }
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699
1700 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 public final void activityPaused(IBinder token) {
1702 final long origId = Binder.clearCallingIdentity();
1703 synchronized (mGlobalLock) {
1704 ActivityStack stack = ActivityRecord.getStackLocked(token);
1705 if (stack != null) {
1706 stack.activityPausedLocked(token, false);
1707 }
1708 }
1709 Binder.restoreCallingIdentity(origId);
1710 }
1711
1712 @Override
1713 public final void activityStopped(IBinder token, Bundle icicle,
1714 PersistableBundle persistentState, CharSequence description) {
1715 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1716
1717 // Refuse possible leaked file descriptors
1718 if (icicle != null && icicle.hasFileDescriptors()) {
1719 throw new IllegalArgumentException("File descriptors passed in Bundle");
1720 }
1721
1722 final long origId = Binder.clearCallingIdentity();
1723
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001724 String restartingName = null;
1725 int restartingUid = 0;
1726 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001728 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 if (r.attachedToProcess()
1731 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1732 // The activity was requested to restart from
1733 // {@link #restartActivityProcessIfVisible}.
1734 restartingName = r.app.mName;
1735 restartingUid = r.app.mUid;
1736 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 r.activityStoppedLocked(icicle, persistentState, description);
1738 }
1739 }
1740
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001741 if (restartingName != null) {
1742 // In order to let the foreground activity can be restarted with its saved state from
1743 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1744 // until the activity reports stopped with the state. And the activity record will be
1745 // kept because the record state is restarting, then the activity will be restarted
1746 // immediately if it is still the top one.
1747 mStackSupervisor.removeRestartTimeouts(r);
1748 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1749 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001750 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751
1752 Binder.restoreCallingIdentity(origId);
1753 }
1754
1755 @Override
1756 public final void activityDestroyed(IBinder token) {
1757 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1758 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001759 final long origId = Binder.clearCallingIdentity();
1760 try {
1761 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1762 if (activity != null) {
1763 activity.destroyed("activityDestroyed");
1764 }
1765 } finally {
1766 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 }
1768 }
1769 }
1770
1771 @Override
1772 public final void activityRelaunched(IBinder token) {
1773 final long origId = Binder.clearCallingIdentity();
1774 synchronized (mGlobalLock) {
1775 mStackSupervisor.activityRelaunchedLocked(token);
1776 }
1777 Binder.restoreCallingIdentity(origId);
1778 }
1779
1780 public final void activitySlept(IBinder token) {
1781 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1782
1783 final long origId = Binder.clearCallingIdentity();
1784
1785 synchronized (mGlobalLock) {
1786 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r != null) {
1788 mStackSupervisor.activitySleptLocked(r);
1789 }
1790 }
1791
1792 Binder.restoreCallingIdentity(origId);
1793 }
1794
1795 @Override
1796 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1797 synchronized (mGlobalLock) {
1798 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1799 if (r == null) {
1800 return;
1801 }
1802 final long origId = Binder.clearCallingIdentity();
1803 try {
1804 r.setRequestedOrientation(requestedOrientation);
1805 } finally {
1806 Binder.restoreCallingIdentity(origId);
1807 }
1808 }
1809 }
1810
1811 @Override
1812 public int getRequestedOrientation(IBinder token) {
1813 synchronized (mGlobalLock) {
1814 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1815 if (r == null) {
1816 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1817 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001818 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 }
1820 }
1821
1822 @Override
1823 public void setImmersive(IBinder token, boolean immersive) {
1824 synchronized (mGlobalLock) {
1825 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1826 if (r == null) {
1827 throw new IllegalArgumentException();
1828 }
1829 r.immersive = immersive;
1830
1831 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001832 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001834 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 }
1836 }
1837 }
1838
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 void applyUpdateLockStateLocked(ActivityRecord r) {
1840 // Modifications to the UpdateLock state are done on our handler, outside
1841 // the activity manager's locks. The new state is determined based on the
1842 // state *now* of the relevant activity record. The object is passed to
1843 // the handler solely for logging detail, not to be consulted/modified.
1844 final boolean nextState = r != null && r.immersive;
1845 mH.post(() -> {
1846 if (mUpdateLock.isHeld() != nextState) {
1847 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1848 "Applying new update lock state '" + nextState + "' for " + r);
1849 if (nextState) {
1850 mUpdateLock.acquire();
1851 } else {
1852 mUpdateLock.release();
1853 }
1854 }
1855 });
1856 }
1857
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 @Override
1859 public boolean isImmersive(IBinder token) {
1860 synchronized (mGlobalLock) {
1861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1862 if (r == null) {
1863 throw new IllegalArgumentException();
1864 }
1865 return r.immersive;
1866 }
1867 }
1868
1869 @Override
1870 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001873 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 return (r != null) ? r.immersive : false;
1875 }
1876 }
1877
1878 @Override
1879 public void overridePendingTransition(IBinder token, String packageName,
1880 int enterAnim, int exitAnim) {
1881 synchronized (mGlobalLock) {
1882 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1883 if (self == null) {
1884 return;
1885 }
1886
1887 final long origId = Binder.clearCallingIdentity();
1888
1889 if (self.isState(
1890 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001891 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001892 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001903 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 if (r == null) {
1905 return ActivityManager.COMPAT_MODE_UNKNOWN;
1906 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001907 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001908 }
1909 }
1910
1911 @Override
1912 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001913 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001917 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 if (r == null) {
1919 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1920 return;
1921 }
1922 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001923 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 }
1925 }
1926
1927 @Override
1928 public int getLaunchedFromUid(IBinder activityToken) {
1929 ActivityRecord srec;
1930 synchronized (mGlobalLock) {
1931 srec = ActivityRecord.forTokenLocked(activityToken);
1932 }
1933 if (srec == null) {
1934 return -1;
1935 }
1936 return srec.launchedFromUid;
1937 }
1938
1939 @Override
1940 public String getLaunchedFromPackage(IBinder activityToken) {
1941 ActivityRecord srec;
1942 synchronized (mGlobalLock) {
1943 srec = ActivityRecord.forTokenLocked(activityToken);
1944 }
1945 if (srec == null) {
1946 return null;
1947 }
1948 return srec.launchedFromPackage;
1949 }
1950
1951 @Override
1952 public boolean convertFromTranslucent(IBinder token) {
1953 final long origId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
1956 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1957 if (r == null) {
1958 return false;
1959 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001960 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 }
1962 } finally {
1963 Binder.restoreCallingIdentity(origId);
1964 }
1965 }
1966
1967 @Override
1968 public boolean convertToTranslucent(IBinder token, Bundle options) {
1969 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1970 final long origId = Binder.clearCallingIdentity();
1971 try {
1972 synchronized (mGlobalLock) {
1973 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1974 if (r == null) {
1975 return false;
1976 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001977 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 int index = task.mActivities.lastIndexOf(r);
1979 if (index > 0) {
1980 ActivityRecord under = task.mActivities.get(index - 1);
1981 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1982 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001983 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001984 }
1985 } finally {
1986 Binder.restoreCallingIdentity(origId);
1987 }
1988 }
1989
1990 @Override
1991 public void notifyActivityDrawn(IBinder token) {
1992 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1993 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001994 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001996 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 }
1998 }
1999 }
2000
2001 @Override
2002 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2003 synchronized (mGlobalLock) {
2004 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2005 if (r == null) {
2006 return;
2007 }
2008 r.reportFullyDrawnLocked(restoredFromBundle);
2009 }
2010 }
2011
2012 @Override
2013 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2014 synchronized (mGlobalLock) {
2015 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2016 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2017 return stack.mDisplayId;
2018 }
2019 return DEFAULT_DISPLAY;
2020 }
2021 }
2022
2023 @Override
2024 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002025 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 long ident = Binder.clearCallingIdentity();
2027 try {
2028 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002029 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002031 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 }
2033 return null;
2034 }
2035 } finally {
2036 Binder.restoreCallingIdentity(ident);
2037 }
2038 }
2039
2040 @Override
2041 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002042 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2044 final long callingId = Binder.clearCallingIdentity();
2045 try {
2046 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002047 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 if (stack == null) {
2049 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2050 return;
2051 }
2052 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002053 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002054 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 }
2056 }
2057 } finally {
2058 Binder.restoreCallingIdentity(callingId);
2059 }
2060 }
2061
2062 @Override
2063 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002064 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002065 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2066 final long callingId = Binder.clearCallingIdentity();
2067 try {
2068 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002069 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002070 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 if (task == null) {
2072 return;
2073 }
2074 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002075 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002076 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 }
2078 }
2079 } finally {
2080 Binder.restoreCallingIdentity(callingId);
2081 }
2082 }
2083
2084 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002085 public void restartActivityProcessIfVisible(IBinder activityToken) {
2086 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2087 final long callingId = Binder.clearCallingIdentity();
2088 try {
2089 synchronized (mGlobalLock) {
2090 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2091 if (r == null) {
2092 return;
2093 }
2094 r.restartProcessIfVisible();
2095 }
2096 } finally {
2097 Binder.restoreCallingIdentity(callingId);
2098 }
2099 }
2100
2101 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002102 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002103 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 synchronized (mGlobalLock) {
2105 final long ident = Binder.clearCallingIdentity();
2106 try {
2107 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2108 "remove-task");
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
2112 }
2113 }
2114
2115 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002116 public void removeAllVisibleRecentTasks() {
2117 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2118 synchronized (mGlobalLock) {
2119 final long ident = Binder.clearCallingIdentity();
2120 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002121 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002122 } finally {
2123 Binder.restoreCallingIdentity(ident);
2124 }
2125 }
2126 }
2127
2128 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002129 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2130 synchronized (mGlobalLock) {
2131 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2132 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002133 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 }
2135 }
2136 return false;
2137 }
2138
2139 @Override
2140 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2141 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002142
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002143 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002144 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2145 if (r != null) {
2146 return r.getActivityStack().navigateUpToLocked(
2147 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002148 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002149 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002150 }
2151 }
2152
2153 /**
2154 * Attempts to move a task backwards in z-order (the order of activities within the task is
2155 * unchanged).
2156 *
2157 * There are several possible results of this call:
2158 * - if the task is locked, then we will show the lock toast
2159 * - if there is a task behind the provided task, then that task is made visible and resumed as
2160 * this task is moved to the back
2161 * - otherwise, if there are no other tasks in the stack:
2162 * - if this task is in the pinned stack, then we remove the stack completely, which will
2163 * have the effect of moving the task to the top or bottom of the fullscreen stack
2164 * (depending on whether it is visible)
2165 * - otherwise, we simply return home and hide this task
2166 *
2167 * @param token A reference to the activity we wish to move
2168 * @param nonRoot If false then this only works if the activity is the root
2169 * of a task; if true it will work for any activity in a task.
2170 * @return Returns true if the move completed, false if not.
2171 */
2172 @Override
2173 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002174 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 synchronized (mGlobalLock) {
2176 final long origId = Binder.clearCallingIdentity();
2177 try {
2178 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002179 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 if (task != null) {
2181 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2182 }
2183 } finally {
2184 Binder.restoreCallingIdentity(origId);
2185 }
2186 }
2187 return false;
2188 }
2189
2190 @Override
2191 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002192 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 long ident = Binder.clearCallingIdentity();
2194 Rect rect = new Rect();
2195 try {
2196 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002197 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2199 if (task == null) {
2200 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2201 return rect;
2202 }
2203 if (task.getStack() != null) {
2204 // Return the bounds from window manager since it will be adjusted for various
2205 // things like the presense of a docked stack for tasks that aren't resizeable.
2206 task.getWindowContainerBounds(rect);
2207 } else {
2208 // Task isn't in window manager yet since it isn't associated with a stack.
2209 // Return the persist value from activity manager
2210 if (!task.matchParentBounds()) {
2211 rect.set(task.getBounds());
2212 } else if (task.mLastNonFullscreenBounds != null) {
2213 rect.set(task.mLastNonFullscreenBounds);
2214 }
2215 }
2216 }
2217 } finally {
2218 Binder.restoreCallingIdentity(ident);
2219 }
2220 return rect;
2221 }
2222
2223 @Override
2224 public ActivityManager.TaskDescription getTaskDescription(int id) {
2225 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002226 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002228 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2230 if (tr != null) {
2231 return tr.lastTaskDescription;
2232 }
2233 }
2234 return null;
2235 }
2236
2237 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002238 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2239 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2240 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2241 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2242 return;
2243 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002244 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002245 synchronized (mGlobalLock) {
2246 final long ident = Binder.clearCallingIdentity();
2247 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002248 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002249 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 if (task == null) {
2251 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2252 return;
2253 }
2254
2255 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2256 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2257
2258 if (!task.isActivityTypeStandardOrUndefined()) {
2259 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2260 + " non-standard task " + taskId + " to windowing mode="
2261 + windowingMode);
2262 }
2263
2264 final ActivityStack stack = task.getStack();
2265 if (toTop) {
2266 stack.moveToFront("setTaskWindowingMode", task);
2267 }
2268 stack.setWindowingMode(windowingMode);
2269 } finally {
2270 Binder.restoreCallingIdentity(ident);
2271 }
2272 }
2273 }
2274
2275 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002276 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002277 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 ActivityRecord r = getCallingRecordLocked(token);
2279 return r != null ? r.info.packageName : null;
2280 }
2281 }
2282
2283 @Override
2284 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 ActivityRecord r = getCallingRecordLocked(token);
2287 return r != null ? r.intent.getComponent() : null;
2288 }
2289 }
2290
2291 private ActivityRecord getCallingRecordLocked(IBinder token) {
2292 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2293 if (r == null) {
2294 return null;
2295 }
2296 return r.resultTo;
2297 }
2298
2299 @Override
2300 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002301 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002302
2303 synchronized (mGlobalLock) {
2304 final long origId = Binder.clearCallingIdentity();
2305 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002306 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 } finally {
2308 Binder.restoreCallingIdentity(origId);
2309 }
2310 }
2311 }
2312
Mark Renouf446251d2019-04-26 10:22:41 -04002313 @Override
2314 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2315 synchronized (mGlobalLock) {
2316 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2317 if (r == null) {
2318 return;
2319 }
2320 ActivityStack stack = r.getActivityStack();
2321 if (stack != null && stack.isSingleTaskInstance()) {
2322 // Single-task stacks are used for activities which are presented in floating
2323 // windows above full screen activities. Instead of directly finishing the
2324 // task, a task change listener is used to notify SystemUI so the action can be
2325 // handled specially.
2326 final TaskRecord task = r.getTaskRecord();
2327 mTaskChangeNotificationController
2328 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2329 } else {
2330 try {
2331 callback.requestFinish();
2332 } catch (RemoteException e) {
2333 Slog.e(TAG, "Failed to invoke request finish callback", e);
2334 }
2335 }
2336 }
2337 }
2338
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 /**
2340 * TODO: Add mController hook
2341 */
2342 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002343 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2344 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002345 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002346
2347 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2348 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002349 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2350 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 }
2352 }
2353
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2355 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002357
Ricky Waiaca8a772019-04-04 16:01:06 +01002358 final int callingPid = Binder.getCallingPid();
2359 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002360 if (!isSameApp(callingUid, callingPackage)) {
2361 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2362 + Binder.getCallingPid() + " as package " + callingPackage;
2363 Slog.w(TAG, msg);
2364 throw new SecurityException(msg);
2365 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 SafeActivityOptions.abort(options);
2368 return;
2369 }
2370 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 WindowProcessController callerApp = null;
2372 if (appThread != null) {
2373 callerApp = getProcessController(appThread);
2374 }
2375 final ActivityStarter starter = getActivityStartController().obtainStarter(
2376 null /* intent */, "moveTaskToFront");
2377 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2378 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002379 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 return;
2381 }
2382 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002384 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 if (task == null) {
2386 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002387 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 return;
2389 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002390 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002392 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 return;
2394 }
2395 ActivityOptions realOptions = options != null
2396 ? options.getOptions(mStackSupervisor)
2397 : null;
2398 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2399 false /* forceNonResizable */);
2400
2401 final ActivityRecord topActivity = task.getTopActivity();
2402 if (topActivity != null) {
2403
2404 // We are reshowing a task, use a starting window to hide the initial draw delay
2405 // so the transition can start earlier.
2406 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2407 true /* taskSwitch */, fromRecents);
2408 }
2409 } finally {
2410 Binder.restoreCallingIdentity(origId);
2411 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 }
2413
Ricky Waiaca8a772019-04-04 16:01:06 +01002414 /**
2415 * Return true if callingUid is system, or packageName belongs to that callingUid.
2416 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002417 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002418 try {
2419 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2420 if (packageName == null) {
2421 return false;
2422 }
2423 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2424 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2425 UserHandle.getUserId(callingUid));
2426 return UserHandle.isSameApp(callingUid, uid);
2427 }
2428 } catch (RemoteException e) {
2429 // Should not happen
2430 }
2431 return true;
2432 }
2433
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002434 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2435 int callingPid, int callingUid, String name) {
2436 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2437 return true;
2438 }
2439
2440 if (getRecentTasks().isCallerRecents(sourceUid)) {
2441 return true;
2442 }
2443
2444 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2445 if (perm == PackageManager.PERMISSION_GRANTED) {
2446 return true;
2447 }
2448 if (checkAllowAppSwitchUid(sourceUid)) {
2449 return true;
2450 }
2451
2452 // If the actual IPC caller is different from the logical source, then
2453 // also see if they are allowed to control app switches.
2454 if (callingUid != -1 && callingUid != sourceUid) {
2455 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2456 if (perm == PackageManager.PERMISSION_GRANTED) {
2457 return true;
2458 }
2459 if (checkAllowAppSwitchUid(callingUid)) {
2460 return true;
2461 }
2462 }
2463
2464 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2465 return false;
2466 }
2467
2468 private boolean checkAllowAppSwitchUid(int uid) {
2469 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2470 if (types != null) {
2471 for (int i = types.size() - 1; i >= 0; i--) {
2472 if (types.valueAt(i).intValue() == uid) {
2473 return true;
2474 }
2475 }
2476 }
2477 return false;
2478 }
2479
2480 @Override
2481 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2482 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2483 "setActivityController()");
2484 synchronized (mGlobalLock) {
2485 mController = controller;
2486 mControllerIsAMonkey = imAMonkey;
2487 Watchdog.getInstance().setActivityController(controller);
2488 }
2489 }
2490
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002491 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002492 synchronized (mGlobalLock) {
2493 return mController != null && mControllerIsAMonkey;
2494 }
2495 }
2496
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002497 @Override
2498 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2499 synchronized (mGlobalLock) {
2500 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2501 }
2502 }
2503
2504 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2506 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2507 }
2508
2509 @Override
2510 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2511 @WindowConfiguration.ActivityType int ignoreActivityType,
2512 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2513 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002514 final int callingPid = Binder.getCallingPid();
2515 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002516 final int[] profileIds = getUserManager().getProfileIds(
2517 UserHandle.getUserId(callingUid), true);
2518 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2519 for (int i = 0; i < profileIds.length; i++) {
2520 callingProfileIds.add(profileIds[i]);
2521 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2523
2524 synchronized (mGlobalLock) {
2525 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2526
Nicholas Sauer0259e532019-08-30 08:24:55 -07002527 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002528 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002529 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002530 }
2531
2532 return list;
2533 }
2534
2535 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2537 synchronized (mGlobalLock) {
2538 final long origId = Binder.clearCallingIdentity();
2539 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2540 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002541 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 }
2543 Binder.restoreCallingIdentity(origId);
2544 }
2545 }
2546
2547 @Override
2548 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002549 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 ActivityStack stack = ActivityRecord.getStackLocked(token);
2551 if (stack != null) {
2552 return stack.willActivityBeVisibleLocked(token);
2553 }
2554 return false;
2555 }
2556 }
2557
2558 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002560 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002561 synchronized (mGlobalLock) {
2562 final long ident = Binder.clearCallingIdentity();
2563 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002564 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 if (task == null) {
2566 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2567 return;
2568 }
2569
2570 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2571 + " to stackId=" + stackId + " toTop=" + toTop);
2572
Wale Ogunwaled32da472018-11-16 07:19:28 -08002573 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002574 if (stack == null) {
2575 throw new IllegalStateException(
2576 "moveTaskToStack: No stack for stackId=" + stackId);
2577 }
2578 if (!stack.isActivityTypeStandardOrUndefined()) {
2579 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2580 + taskId + " to stack " + stackId);
2581 }
2582 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002583 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002584 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2585 }
2586 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2587 "moveTaskToStack");
2588 } finally {
2589 Binder.restoreCallingIdentity(ident);
2590 }
2591 }
2592 }
2593
2594 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002595 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2596 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002597
2598 final long ident = Binder.clearCallingIdentity();
2599 try {
2600 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002601 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2602 if (stack == null) {
2603 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2604 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002606 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2607 throw new IllegalArgumentException("Stack: " + stackId
2608 + " doesn't support animated resize.");
2609 }
2610 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2611 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
wilsonshih5c4cf522019-01-25 09:03:47 +08002618 @Override
2619 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2620 int animationDuration) {
2621 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2622
2623 final long ident = Binder.clearCallingIdentity();
2624 try {
2625 synchronized (mGlobalLock) {
2626 if (xOffset == 0 && yOffset == 0) {
2627 return;
2628 }
2629 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2630 if (stack == null) {
2631 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2632 return;
2633 }
2634 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2635 throw new IllegalArgumentException("Stack: " + stackId
2636 + " doesn't support animated resize.");
2637 }
2638 final Rect destBounds = new Rect();
2639 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002640 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002641 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2642 return;
2643 }
2644 destBounds.offset(xOffset, yOffset);
2645 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2646 animationDuration, false /* fromFullscreen */);
2647 }
2648 } finally {
2649 Binder.restoreCallingIdentity(ident);
2650 }
2651 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002652 /**
2653 * Moves the specified task to the primary-split-screen stack.
2654 *
2655 * @param taskId Id of task to move.
2656 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2657 * exist already. See
2658 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2659 * and
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2661 * @param toTop If the task and stack should be moved to the top.
2662 * @param animate Whether we should play an animation for the moving the task.
2663 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2664 * stack. Pass {@code null} to use default bounds.
2665 * @param showRecents If the recents activity should be shown on the other side of the task
2666 * going into split-screen mode.
2667 */
2668 @Override
2669 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2670 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002671 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 "setTaskWindowingModeSplitScreenPrimary()");
2673 synchronized (mGlobalLock) {
2674 final long ident = Binder.clearCallingIdentity();
2675 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002676 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002677 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 if (task == null) {
2679 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2680 return false;
2681 }
2682 if (DEBUG_STACK) Slog.d(TAG_STACK,
2683 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2684 + " to createMode=" + createMode + " toTop=" + toTop);
2685 if (!task.isActivityTypeStandardOrUndefined()) {
2686 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2687 + " non-standard task " + taskId + " to split-screen windowing mode");
2688 }
2689
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002690 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 final int windowingMode = task.getWindowingMode();
2692 final ActivityStack stack = task.getStack();
2693 if (toTop) {
2694 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2695 }
2696 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002697 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2698 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 return windowingMode != task.getWindowingMode();
2700 } finally {
2701 Binder.restoreCallingIdentity(ident);
2702 }
2703 }
2704 }
2705
2706 /**
2707 * Removes stacks in the input windowing modes from the system if they are of activity type
2708 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2709 */
2710 @Override
2711 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 "removeStacksInWindowingModes()");
2714
2715 synchronized (mGlobalLock) {
2716 final long ident = Binder.clearCallingIdentity();
2717 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002718 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 } finally {
2720 Binder.restoreCallingIdentity(ident);
2721 }
2722 }
2723 }
2724
2725 @Override
2726 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002727 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002728 "removeStacksWithActivityTypes()");
2729
2730 synchronized (mGlobalLock) {
2731 final long ident = Binder.clearCallingIdentity();
2732 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002733 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 } finally {
2735 Binder.restoreCallingIdentity(ident);
2736 }
2737 }
2738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739
2740 @Override
2741 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2742 int userId) {
2743 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2745 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002747 final boolean detailed = checkGetTasksPermission(
2748 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2749 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 == PackageManager.PERMISSION_GRANTED;
2751
2752 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002753 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 callingUid);
2755 }
2756 }
2757
2758 @Override
2759 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 long ident = Binder.clearCallingIdentity();
2762 try {
2763 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002764 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 }
2766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770
2771 @Override
2772 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002777 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 @Override
2785 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 final long callingUid = Binder.getCallingUid();
2788 final long origId = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
2791 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002792 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2794 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(origId);
2798 }
2799 }
2800
2801 @Override
2802 public void startLockTaskModeByToken(IBinder token) {
2803 synchronized (mGlobalLock) {
2804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2805 if (r == null) {
2806 return;
2807 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002808 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 }
2811
2812 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002813 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 // This makes inner call to look as if it was initiated by system.
2816 long ident = Binder.clearCallingIdentity();
2817 try {
2818 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002819 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002820 MATCH_TASK_IN_STACKS_ONLY);
2821 if (task == null) {
2822 return;
2823 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824
2825 // When starting lock task mode the stack must be in front and focused
2826 task.getStack().moveToFront("startSystemLockTaskMode");
2827 startLockTaskModeLocked(task, true /* isSystemCaller */);
2828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public void stopLockTaskModeByToken(IBinder token) {
2836 synchronized (mGlobalLock) {
2837 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2838 if (r == null) {
2839 return;
2840 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002841 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 }
2844
2845 /**
2846 * This API should be called by SystemUI only when user perform certain action to dismiss
2847 * lock task mode. We should only dismiss pinned lock task mode in this case.
2848 */
2849 @Override
2850 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2853 }
2854
2855 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2856 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2857 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2858 return;
2859 }
2860
Wale Ogunwaled32da472018-11-16 07:19:28 -08002861 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 if (stack == null || task != stack.topTask()) {
2863 throw new IllegalArgumentException("Invalid task, not in foreground");
2864 }
2865
2866 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2867 // system or a specific app.
2868 // * System-initiated requests will only start the pinned mode (screen pinning)
2869 // * App-initiated requests
2870 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2871 // - will start the pinned mode, otherwise
2872 final int callingUid = Binder.getCallingUid();
2873 long ident = Binder.clearCallingIdentity();
2874 try {
2875 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002876 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002878 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883
2884 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2885 final int callingUid = Binder.getCallingUid();
2886 long ident = Binder.clearCallingIdentity();
2887 try {
2888 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002889 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 }
2891 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2892 // task and jumping straight into a call in the case of emergency call back.
2893 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2894 if (tm != null) {
2895 tm.showInCallScreen(false);
2896 }
2897 } finally {
2898 Binder.restoreCallingIdentity(ident);
2899 }
2900 }
2901
2902 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002903 public void updateLockTaskPackages(int userId, String[] packages) {
2904 final int callingUid = Binder.getCallingUid();
2905 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2906 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2907 "updateLockTaskPackages()");
2908 }
2909 synchronized (this) {
2910 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2911 + Arrays.toString(packages));
2912 getLockTaskController().updateLockTaskPackages(userId, packages);
2913 }
2914 }
2915
2916 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 public boolean isInLockTaskMode() {
2918 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2919 }
2920
2921 @Override
2922 public int getLockTaskModeState() {
2923 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002924 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 }
2926 }
2927
2928 @Override
2929 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2932 if (r != null) {
2933 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002934 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002936 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939 }
2940
2941 @Override
2942 public Bundle getActivityOptions(IBinder token) {
2943 final long origId = Binder.clearCallingIdentity();
2944 try {
2945 synchronized (mGlobalLock) {
2946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2947 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002948 final ActivityOptions activityOptions = r.takeOptionsLocked(
2949 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 return activityOptions == null ? null : activityOptions.toBundle();
2951 }
2952 return null;
2953 }
2954 } finally {
2955 Binder.restoreCallingIdentity(origId);
2956 }
2957 }
2958
2959 @Override
2960 public List<IBinder> getAppTasks(String callingPackage) {
2961 int callingUid = Binder.getCallingUid();
2962 long ident = Binder.clearCallingIdentity();
2963 try {
2964 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002965 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 }
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
2970 }
2971
2972 @Override
2973 public void finishVoiceTask(IVoiceInteractionSession session) {
2974 synchronized (mGlobalLock) {
2975 final long origId = Binder.clearCallingIdentity();
2976 try {
2977 // TODO: VI Consider treating local voice interactions and voice tasks
2978 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002979 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 } finally {
2981 Binder.restoreCallingIdentity(origId);
2982 }
2983 }
2984
2985 }
2986
2987 @Override
2988 public boolean isTopOfTask(IBinder token) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002991 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void notifyLaunchTaskBehindComplete(IBinder token) {
2997 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2998 }
2999
3000 @Override
3001 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003002 mH.post(() -> {
3003 synchronized (mGlobalLock) {
3004 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003005 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 } catch (RemoteException e) {
3009 }
3010 }
3011 }
3012
3013 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015
3016 /** Called from an app when assist data is ready. */
3017 @Override
3018 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3019 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003020 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 synchronized (pae) {
3022 pae.result = extras;
3023 pae.structure = structure;
3024 pae.content = content;
3025 if (referrer != null) {
3026 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3027 }
3028 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003029 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003030 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3031 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 structure.setHomeActivity(pae.isHome);
3033 }
3034 pae.haveResult = true;
3035 pae.notifyAll();
3036 if (pae.intent == null && pae.receiver == null) {
3037 // Caller is just waiting for the result.
3038 return;
3039 }
3040 }
3041 // We are now ready to launch the assist activity.
3042 IAssistDataReceiver sendReceiver = null;
3043 Bundle sendBundle = null;
3044 synchronized (mGlobalLock) {
3045 buildAssistBundleLocked(pae, extras);
3046 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003047 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 if (!exists) {
3049 // Timed out.
3050 return;
3051 }
3052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003053 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 // Caller wants result sent back to them.
3055 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003056 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3057 pae.activity.getTaskRecord().taskId);
3058 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3059 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3061 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3062 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3063 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3064 }
3065 }
3066 if (sendReceiver != null) {
3067 try {
3068 sendReceiver.onHandleAssistData(sendBundle);
3069 } catch (RemoteException e) {
3070 }
3071 return;
3072 }
3073
3074 final long ident = Binder.clearCallingIdentity();
3075 try {
3076 if (TextUtils.equals(pae.intent.getAction(),
3077 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003078 // Start voice interaction through VoiceInteractionManagerService.
3079 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3080 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 } else {
3082 pae.intent.replaceExtras(pae.extras);
3083 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3084 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3085 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003086 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087
3088 try {
3089 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3090 } catch (ActivityNotFoundException e) {
3091 Slog.w(TAG, "No activity to handle assist action.", e);
3092 }
3093 }
3094 } finally {
3095 Binder.restoreCallingIdentity(ident);
3096 }
3097 }
3098
3099 @Override
3100 public int addAppTask(IBinder activityToken, Intent intent,
3101 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3102 final int callingUid = Binder.getCallingUid();
3103 final long callingIdent = Binder.clearCallingIdentity();
3104
3105 try {
3106 synchronized (mGlobalLock) {
3107 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3108 if (r == null) {
3109 throw new IllegalArgumentException("Activity does not exist; token="
3110 + activityToken);
3111 }
3112 ComponentName comp = intent.getComponent();
3113 if (comp == null) {
3114 throw new IllegalArgumentException("Intent " + intent
3115 + " must specify explicit component");
3116 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003117 if (thumbnail.getWidth() != mThumbnailWidth
3118 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 throw new IllegalArgumentException("Bad thumbnail size: got "
3120 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 }
3123 if (intent.getSelector() != null) {
3124 intent.setSelector(null);
3125 }
3126 if (intent.getSourceBounds() != null) {
3127 intent.setSourceBounds(null);
3128 }
3129 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3130 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3131 // The caller has added this as an auto-remove task... that makes no
3132 // sense, so turn off auto-remove.
3133 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3134 }
3135 }
3136 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3137 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3138 if (ainfo.applicationInfo.uid != callingUid) {
3139 throw new SecurityException(
3140 "Can't add task for another application: target uid="
3141 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3142 }
3143
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003144 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003146 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003148 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 // The app has too many tasks already and we can't add any more
3150 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3151 return INVALID_TASK_ID;
3152 }
3153 task.lastTaskDescription.copyFrom(description);
3154
3155 // TODO: Send the thumbnail to WM to store it.
3156
3157 return task.taskId;
3158 }
3159 } finally {
3160 Binder.restoreCallingIdentity(callingIdent);
3161 }
3162 }
3163
3164 @Override
3165 public Point getAppTaskThumbnailSize() {
3166 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003167 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 }
3169 }
3170
3171 @Override
3172 public void setTaskResizeable(int taskId, int resizeableMode) {
3173 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003174 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3176 if (task == null) {
3177 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3178 return;
3179 }
3180 task.setResizeMode(resizeableMode);
3181 }
3182 }
3183
3184 @Override
3185 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 long ident = Binder.clearCallingIdentity();
3188 try {
3189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003190 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003191 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 if (task == null) {
3193 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3194 return;
3195 }
3196 // Place the task in the right stack if it isn't there already based on
3197 // the requested bounds.
3198 // The stack transition logic is:
3199 // - a null bounds on a freeform task moves that task to fullscreen
3200 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3201 // that task to freeform
3202 // - otherwise the task is not moved
3203 ActivityStack stack = task.getStack();
3204 if (!task.getWindowConfiguration().canResizeTask()) {
3205 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3206 }
3207 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3208 stack = stack.getDisplay().getOrCreateStack(
3209 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3210 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3211 stack = stack.getDisplay().getOrCreateStack(
3212 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3213 }
3214
3215 // Reparent the task to the right stack if necessary
3216 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3217 if (stack != task.getStack()) {
3218 // Defer resume until the task is resized below
3219 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3220 DEFER_RESUME, "resizeTask");
3221 preserveWindow = false;
3222 }
3223
3224 // After reparenting (which only resizes the task to the stack bounds), resize the
3225 // task to the actual bounds provided
3226 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3227 }
3228 } finally {
3229 Binder.restoreCallingIdentity(ident);
3230 }
3231 }
3232
3233 @Override
3234 public boolean releaseActivityInstance(IBinder token) {
3235 synchronized (mGlobalLock) {
3236 final long origId = Binder.clearCallingIdentity();
3237 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003238 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3239 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 return false;
3241 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003242 r.destroyImmediately(true /* removeFromApp */, "app-req");
3243 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 } finally {
3245 Binder.restoreCallingIdentity(origId);
3246 }
3247 }
3248 }
3249
3250 @Override
3251 public void releaseSomeActivities(IApplicationThread appInt) {
3252 synchronized (mGlobalLock) {
3253 final long origId = Binder.clearCallingIdentity();
3254 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003255 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003256 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 } finally {
3258 Binder.restoreCallingIdentity(origId);
3259 }
3260 }
3261 }
3262
3263 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003264 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 != PackageManager.PERMISSION_GRANTED) {
3267 throw new SecurityException("Requires permission "
3268 + android.Manifest.permission.DEVICE_POWER);
3269 }
3270
3271 synchronized (mGlobalLock) {
3272 long ident = Binder.clearCallingIdentity();
3273 if (mKeyguardShown != keyguardShowing) {
3274 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003275 final Message msg = PooledLambda.obtainMessage(
3276 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3277 keyguardShowing);
3278 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 }
3280 try {
wilsonshih177261f2019-02-22 12:02:18 +08003281 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003282 } finally {
3283 Binder.restoreCallingIdentity(ident);
3284 }
3285 }
3286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003287 mH.post(() -> {
3288 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3289 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3290 }
3291 });
3292 }
3293
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003294 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003295 mH.post(() -> {
3296 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3297 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3298 }
3299 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003300 }
3301
3302 @Override
3303 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003304 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3305 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306
3307 final File passedIconFile = new File(filePath);
3308 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3309 passedIconFile.getName());
3310 if (!legitIconFile.getPath().equals(filePath)
3311 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3312 throw new IllegalArgumentException("Bad file path: " + filePath
3313 + " passed for userId " + userId);
3314 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003315 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 }
3317
3318 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3321 final ActivityOptions activityOptions = safeOptions != null
3322 ? safeOptions.getOptions(mStackSupervisor)
3323 : null;
3324 if (activityOptions == null
3325 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3326 || activityOptions.getCustomInPlaceResId() == 0) {
3327 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3328 "with valid animation");
3329 }
lumark588a3e82018-07-20 18:53:54 +08003330 // Get top display of front most application.
3331 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3332 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003333 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3334 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3335 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003336 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003337 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003338 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003339 }
3340
3341 @Override
3342 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003343 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 synchronized (mGlobalLock) {
3345 final long ident = Binder.clearCallingIdentity();
3346 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003347 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 if (stack == null) {
3349 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3350 return;
3351 }
3352 if (!stack.isActivityTypeStandardOrUndefined()) {
3353 throw new IllegalArgumentException(
3354 "Removing non-standard stack is not allowed.");
3355 }
3356 mStackSupervisor.removeStack(stack);
3357 } finally {
3358 Binder.restoreCallingIdentity(ident);
3359 }
3360 }
3361 }
3362
3363 @Override
3364 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003365 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366
3367 synchronized (mGlobalLock) {
3368 final long ident = Binder.clearCallingIdentity();
3369 try {
3370 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3371 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003372 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373 } finally {
3374 Binder.restoreCallingIdentity(ident);
3375 }
3376 }
3377 }
3378
3379 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003380 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 synchronized (mGlobalLock) {
3382 long ident = Binder.clearCallingIdentity();
3383 try {
3384 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3385 if (r == null) {
3386 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003387 "toggleFreeformWindowingMode: No activity record matching token="
3388 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 }
3390
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003391 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003392 if (stack == null) {
3393 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3394 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396
Yunfan Chend967af82019-01-17 18:30:18 +09003397 if (!stack.inFreeformWindowingMode()
3398 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3399 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3400 + "toggle between fullscreen and freeform.");
3401 }
3402
3403 if (stack.inFreeformWindowingMode()) {
3404 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003405 } else if (stack.getParent().inFreeformWindowingMode()) {
3406 // If the window is on a freeform display, set it to undefined. It will be
3407 // resolved to freeform and it can adjust windowing mode when the display mode
3408 // changes in runtime.
3409 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003410 } else {
3411 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3412 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
3416 }
3417 }
3418
3419 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3420 @Override
3421 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003422 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003424 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 }
3426
3427 /** Unregister a task stack listener so that it stops receiving callbacks. */
3428 @Override
3429 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003432 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 }
3434
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 @Override
3436 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3437 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3438 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3439 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3440 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3441 }
3442
3443 @Override
3444 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3445 IBinder activityToken, int flags) {
3446 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3447 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3448 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3449 }
3450
3451 @Override
3452 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3453 Bundle args) {
3454 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3455 true /* focused */, true /* newSessionId */, userHandle, args,
3456 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3457 }
3458
3459 @Override
3460 public Bundle getAssistContextExtras(int requestType) {
3461 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3462 null, null, true /* focused */, true /* newSessionId */,
3463 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3464 if (pae == null) {
3465 return null;
3466 }
3467 synchronized (pae) {
3468 while (!pae.haveResult) {
3469 try {
3470 pae.wait();
3471 } catch (InterruptedException e) {
3472 }
3473 }
3474 }
3475 synchronized (mGlobalLock) {
3476 buildAssistBundleLocked(pae, pae.result);
3477 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003478 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 }
3480 return pae.extras;
3481 }
3482
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003483 /**
3484 * Binder IPC calls go through the public entry point.
3485 * This can be called with or without the global lock held.
3486 */
3487 private static int checkCallingPermission(String permission) {
3488 return checkPermission(
3489 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3490 }
3491
3492 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003493 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003494 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3495 mAmInternal.enforceCallingPermission(permission, func);
3496 }
3497 }
3498
3499 @VisibleForTesting
3500 int checkGetTasksPermission(String permission, int pid, int uid) {
3501 return checkPermission(permission, pid, uid);
3502 }
3503
3504 static int checkPermission(String permission, int pid, int uid) {
3505 if (permission == null) {
3506 return PackageManager.PERMISSION_DENIED;
3507 }
3508 return checkComponentPermission(permission, pid, uid, -1, true);
3509 }
3510
Wale Ogunwale214f3482018-10-04 11:00:47 -07003511 public static int checkComponentPermission(String permission, int pid, int uid,
3512 int owningUid, boolean exported) {
3513 return ActivityManagerService.checkComponentPermission(
3514 permission, pid, uid, owningUid, exported);
3515 }
3516
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003517 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3518 if (getRecentTasks().isCallerRecents(callingUid)) {
3519 // Always allow the recents component to get tasks
3520 return true;
3521 }
3522
3523 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3524 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3525 if (!allowed) {
3526 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3527 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3528 // Temporary compatibility: some existing apps on the system image may
3529 // still be requesting the old permission and not switched to the new
3530 // one; if so, we'll still allow them full access. This means we need
3531 // to see if they are holding the old permission and are a system app.
3532 try {
3533 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3534 allowed = true;
3535 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3536 + " is using old GET_TASKS but privileged; allowing");
3537 }
3538 } catch (RemoteException e) {
3539 }
3540 }
3541 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3542 + " does not hold REAL_GET_TASKS; limiting output");
3543 }
3544 return allowed;
3545 }
3546
Nicholas Sauer0259e532019-08-30 08:24:55 -07003547 boolean isCrossUserAllowed(int pid, int uid) {
3548 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3549 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3550 }
3551
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3553 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3554 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3555 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003556 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 "enqueueAssistContext()");
3558
3559 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003560 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003561 if (activity == null) {
3562 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3563 return null;
3564 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003565 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3567 return null;
3568 }
3569 if (focused) {
3570 if (activityToken != null) {
3571 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3572 if (activity != caller) {
3573 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3574 + " is not current top " + activity);
3575 return null;
3576 }
3577 }
3578 } else {
3579 activity = ActivityRecord.forTokenLocked(activityToken);
3580 if (activity == null) {
3581 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3582 + " couldn't be found");
3583 return null;
3584 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003585 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003586 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3587 return null;
3588 }
3589 }
3590
3591 PendingAssistExtras pae;
3592 Bundle extras = new Bundle();
3593 if (args != null) {
3594 extras.putAll(args);
3595 }
3596 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003597 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598
3599 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3600 userHandle);
3601 pae.isHome = activity.isActivityTypeHome();
3602
3603 // Increment the sessionId if necessary
3604 if (newSessionId) {
3605 mViSessionId++;
3606 }
3607 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003608 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3609 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003611 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 } catch (RemoteException e) {
3613 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3614 return null;
3615 }
3616 return pae;
3617 }
3618 }
3619
3620 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3621 if (result != null) {
3622 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3623 }
3624 if (pae.hint != null) {
3625 pae.extras.putBoolean(pae.hint, true);
3626 }
3627 }
3628
3629 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3630 IAssistDataReceiver receiver;
3631 synchronized (mGlobalLock) {
3632 mPendingAssistExtras.remove(pae);
3633 receiver = pae.receiver;
3634 }
3635 if (receiver != null) {
3636 // Caller wants result sent back to them.
3637 Bundle sendBundle = new Bundle();
3638 // At least return the receiver extras
3639 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3640 try {
3641 pae.receiver.onHandleAssistData(sendBundle);
3642 } catch (RemoteException e) {
3643 }
3644 }
3645 }
3646
3647 public class PendingAssistExtras extends Binder implements Runnable {
3648 public final ActivityRecord activity;
3649 public boolean isHome;
3650 public final Bundle extras;
3651 public final Intent intent;
3652 public final String hint;
3653 public final IAssistDataReceiver receiver;
3654 public final int userHandle;
3655 public boolean haveResult = false;
3656 public Bundle result = null;
3657 public AssistStructure structure = null;
3658 public AssistContent content = null;
3659 public Bundle receiverExtras;
3660
3661 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3662 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3663 int _userHandle) {
3664 activity = _activity;
3665 extras = _extras;
3666 intent = _intent;
3667 hint = _hint;
3668 receiver = _receiver;
3669 receiverExtras = _receiverExtras;
3670 userHandle = _userHandle;
3671 }
3672
3673 @Override
3674 public void run() {
3675 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3676 synchronized (this) {
3677 haveResult = true;
3678 notifyAll();
3679 }
3680 pendingAssistExtrasTimedOut(this);
3681 }
3682 }
3683
3684 @Override
3685 public boolean isAssistDataAllowedOnCurrentActivity() {
3686 int userId;
3687 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003688 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3690 return false;
3691 }
3692
3693 final ActivityRecord activity = focusedStack.getTopActivity();
3694 if (activity == null) {
3695 return false;
3696 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003697 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003698 }
3699 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3700 }
3701
3702 @Override
3703 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3704 long ident = Binder.clearCallingIdentity();
3705 try {
3706 synchronized (mGlobalLock) {
3707 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003708 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 if (top != caller) {
3710 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3711 + " is not current top " + top);
3712 return false;
3713 }
3714 if (!top.nowVisible) {
3715 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3716 + " is not visible");
3717 return false;
3718 }
3719 }
3720 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3721 token);
3722 } finally {
3723 Binder.restoreCallingIdentity(ident);
3724 }
3725 }
3726
3727 @Override
3728 public boolean isRootVoiceInteraction(IBinder token) {
3729 synchronized (mGlobalLock) {
3730 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3731 if (r == null) {
3732 return false;
3733 }
3734 return r.rootVoiceInteraction;
3735 }
3736 }
3737
Wale Ogunwalef6733932018-06-27 05:14:34 -07003738 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3739 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3740 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3741 if (activityToCallback == null) return;
3742 activityToCallback.setVoiceSessionLocked(voiceSession);
3743
3744 // Inform the activity
3745 try {
3746 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3747 voiceInteractor);
3748 long token = Binder.clearCallingIdentity();
3749 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003750 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003751 } finally {
3752 Binder.restoreCallingIdentity(token);
3753 }
3754 // TODO: VI Should we cache the activity so that it's easier to find later
3755 // rather than scan through all the stacks and activities?
3756 } catch (RemoteException re) {
3757 activityToCallback.clearVoiceSessionLocked();
3758 // TODO: VI Should this terminate the voice session?
3759 }
3760 }
3761
3762 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3763 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3764 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3765 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3766 boolean wasRunningVoice = mRunningVoice != null;
3767 mRunningVoice = session;
3768 if (!wasRunningVoice) {
3769 mVoiceWakeLock.acquire();
3770 updateSleepIfNeededLocked();
3771 }
3772 }
3773 }
3774
3775 void finishRunningVoiceLocked() {
3776 if (mRunningVoice != null) {
3777 mRunningVoice = null;
3778 mVoiceWakeLock.release();
3779 updateSleepIfNeededLocked();
3780 }
3781 }
3782
3783 @Override
3784 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3785 synchronized (mGlobalLock) {
3786 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3787 if (keepAwake) {
3788 mVoiceWakeLock.acquire();
3789 } else {
3790 mVoiceWakeLock.release();
3791 }
3792 }
3793 }
3794 }
3795
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 @Override
3797 public ComponentName getActivityClassForToken(IBinder token) {
3798 synchronized (mGlobalLock) {
3799 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3800 if (r == null) {
3801 return null;
3802 }
3803 return r.intent.getComponent();
3804 }
3805 }
3806
3807 @Override
3808 public String getPackageForToken(IBinder token) {
3809 synchronized (mGlobalLock) {
3810 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3811 if (r == null) {
3812 return null;
3813 }
3814 return r.packageName;
3815 }
3816 }
3817
3818 @Override
3819 public void showLockTaskEscapeMessage(IBinder token) {
3820 synchronized (mGlobalLock) {
3821 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3822 if (r == null) {
3823 return;
3824 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003825 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 }
3827 }
3828
3829 @Override
3830 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003831 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 final long token = Binder.clearCallingIdentity();
3833 try {
3834 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003835 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 }
3837 } finally {
3838 Binder.restoreCallingIdentity(token);
3839 }
3840 }
3841
3842 /**
3843 * Try to place task to provided position. The final position might be different depending on
3844 * current user and stacks state. The task will be moved to target stack if it's currently in
3845 * different stack.
3846 */
3847 @Override
3848 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003849 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 synchronized (mGlobalLock) {
3851 long ident = Binder.clearCallingIdentity();
3852 try {
3853 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3854 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003855 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003856 if (task == null) {
3857 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3858 + taskId);
3859 }
3860
Wale Ogunwaled32da472018-11-16 07:19:28 -08003861 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862
3863 if (stack == null) {
3864 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3865 + stackId);
3866 }
3867 if (!stack.isActivityTypeStandardOrUndefined()) {
3868 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3869 + " the position of task " + taskId + " in/to non-standard stack");
3870 }
3871
3872 // TODO: Have the callers of this API call a separate reparent method if that is
3873 // what they intended to do vs. having this method also do reparenting.
3874 if (task.getStack() == stack) {
3875 // Change position in current stack.
3876 stack.positionChildAt(task, position);
3877 } else {
3878 // Reparent to new stack.
3879 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3880 !DEFER_RESUME, "positionTaskInStack");
3881 }
3882 } finally {
3883 Binder.restoreCallingIdentity(ident);
3884 }
3885 }
3886 }
3887
3888 @Override
3889 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3890 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3891 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003892 + Arrays.toString(horizontalSizeConfiguration) + " "
3893 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 synchronized (mGlobalLock) {
3895 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3896 if (record == null) {
3897 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3898 + "found for: " + token);
3899 }
3900 record.setSizeConfigurations(horizontalSizeConfiguration,
3901 verticalSizeConfigurations, smallestSizeConfigurations);
3902 }
3903 }
3904
3905 /**
3906 * Dismisses split-screen multi-window mode.
3907 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3908 */
3909 @Override
3910 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3913 final long ident = Binder.clearCallingIdentity();
3914 try {
3915 synchronized (mGlobalLock) {
3916 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003917 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 if (stack == null) {
3919 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3920 return;
3921 }
3922
3923 if (toTop) {
3924 // Caller wants the current split-screen primary stack to be the top stack after
3925 // it goes fullscreen, so move it to the front.
3926 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003927 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003929 // stack after it goes fullscreen, so we move the focus to the top-most
3930 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3932 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3933 if (otherStack != null) {
3934 otherStack.moveToFront("dismissSplitScreenMode_other");
3935 }
3936 }
3937
Evan Rosky10475742018-09-05 19:02:48 -07003938 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 }
3940 } finally {
3941 Binder.restoreCallingIdentity(ident);
3942 }
3943 }
3944
3945 /**
3946 * Dismisses Pip
3947 * @param animate True if the dismissal should be animated.
3948 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3949 * default animation duration should be used.
3950 */
3951 @Override
3952 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003953 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 final long ident = Binder.clearCallingIdentity();
3955 try {
3956 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003957 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003958 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 if (stack == null) {
3960 Slog.w(TAG, "dismissPip: pinned stack not found.");
3961 return;
3962 }
3963 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3964 throw new IllegalArgumentException("Stack: " + stack
3965 + " doesn't support animated resize.");
3966 }
3967 if (animate) {
3968 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3969 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3970 } else {
3971 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3972 }
3973 }
3974 } finally {
3975 Binder.restoreCallingIdentity(ident);
3976 }
3977 }
3978
3979 @Override
3980 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003981 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 synchronized (mGlobalLock) {
3983 mSuppressResizeConfigChanges = suppress;
3984 }
3985 }
3986
3987 /**
3988 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3989 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3990 * activity and clearing the task at the same time.
3991 */
3992 @Override
3993 // TODO: API should just be about changing windowing modes...
3994 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 "moveTasksToFullscreenStack()");
3997 synchronized (mGlobalLock) {
3998 final long origId = Binder.clearCallingIdentity();
3999 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004000 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 if (stack != null){
4002 if (!stack.isActivityTypeStandardOrUndefined()) {
4003 throw new IllegalArgumentException(
4004 "You can't move tasks from non-standard stacks.");
4005 }
4006 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4007 }
4008 } finally {
4009 Binder.restoreCallingIdentity(origId);
4010 }
4011 }
4012 }
4013
4014 /**
4015 * Moves the top activity in the input stackId to the pinned stack.
4016 *
4017 * @param stackId Id of stack to move the top activity to pinned stack.
4018 * @param bounds Bounds to use for pinned stack.
4019 *
4020 * @return True if the top activity of the input stack was successfully moved to the pinned
4021 * stack.
4022 */
4023 @Override
4024 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004025 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026 "moveTopActivityToPinnedStack()");
4027 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004028 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4030 + "Device doesn't support picture-in-picture mode");
4031 }
4032
4033 long ident = Binder.clearCallingIdentity();
4034 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004035 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 } finally {
4037 Binder.restoreCallingIdentity(ident);
4038 }
4039 }
4040 }
4041
4042 @Override
4043 public boolean isInMultiWindowMode(IBinder token) {
4044 final long origId = Binder.clearCallingIdentity();
4045 try {
4046 synchronized (mGlobalLock) {
4047 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4048 if (r == null) {
4049 return false;
4050 }
4051 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4052 return r.inMultiWindowMode();
4053 }
4054 } finally {
4055 Binder.restoreCallingIdentity(origId);
4056 }
4057 }
4058
4059 @Override
4060 public boolean isInPictureInPictureMode(IBinder token) {
4061 final long origId = Binder.clearCallingIdentity();
4062 try {
4063 synchronized (mGlobalLock) {
4064 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4065 }
4066 } finally {
4067 Binder.restoreCallingIdentity(origId);
4068 }
4069 }
4070
4071 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004072 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4073 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 return false;
4075 }
4076
4077 // If we are animating to fullscreen then we have already dispatched the PIP mode
4078 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004079 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4080 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 }
4082
4083 @Override
4084 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4085 final long origId = Binder.clearCallingIdentity();
4086 try {
4087 synchronized (mGlobalLock) {
4088 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4089 "enterPictureInPictureMode", token, params);
4090
4091 // If the activity is already in picture in picture mode, then just return early
4092 if (isInPictureInPictureMode(r)) {
4093 return true;
4094 }
4095
4096 // Activity supports picture-in-picture, now check that we can enter PiP at this
4097 // point, if it is
4098 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4099 false /* beforeStopping */)) {
4100 return false;
4101 }
4102
4103 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004104 synchronized (mGlobalLock) {
4105 // Only update the saved args from the args that are set
4106 r.pictureInPictureArgs.copyOnlySet(params);
4107 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4108 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4109 // Adjust the source bounds by the insets for the transition down
4110 final Rect sourceBounds = new Rect(
4111 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004112 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004113 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004114 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 stack.setPictureInPictureAspectRatio(aspectRatio);
4116 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004117 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4118 r.info.applicationInfo.uid, r.shortComponentName,
4119 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 logPictureInPictureArgs(params);
4121 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 };
4123
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004124 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 // If the keyguard is showing or occluded, then try and dismiss it before
4126 // entering picture-in-picture (this will prompt the user to authenticate if the
4127 // device is currently locked).
4128 dismissKeyguard(token, new KeyguardDismissCallback() {
4129 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004130 public void onDismissSucceeded() {
4131 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 }
4133 }, null /* message */);
4134 } else {
4135 // Enter picture in picture immediately otherwise
4136 enterPipRunnable.run();
4137 }
4138 return true;
4139 }
4140 } finally {
4141 Binder.restoreCallingIdentity(origId);
4142 }
4143 }
4144
4145 @Override
4146 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4147 final long origId = Binder.clearCallingIdentity();
4148 try {
4149 synchronized (mGlobalLock) {
4150 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4151 "setPictureInPictureParams", token, params);
4152
4153 // Only update the saved args from the args that are set
4154 r.pictureInPictureArgs.copyOnlySet(params);
4155 if (r.inPinnedWindowingMode()) {
4156 // If the activity is already in picture-in-picture, update the pinned stack now
4157 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4158 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004159 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 if (!stack.isAnimatingBoundsToFullscreen()) {
4161 stack.setPictureInPictureAspectRatio(
4162 r.pictureInPictureArgs.getAspectRatio());
4163 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4164 }
4165 }
4166 logPictureInPictureArgs(params);
4167 }
4168 } finally {
4169 Binder.restoreCallingIdentity(origId);
4170 }
4171 }
4172
4173 @Override
4174 public int getMaxNumPictureInPictureActions(IBinder token) {
4175 // Currently, this is a static constant, but later, we may change this to be dependent on
4176 // the context of the activity
4177 return 3;
4178 }
4179
4180 private void logPictureInPictureArgs(PictureInPictureParams params) {
4181 if (params.hasSetActions()) {
4182 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4183 params.getActions().size());
4184 }
4185 if (params.hasSetAspectRatio()) {
4186 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4187 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4188 MetricsLogger.action(lm);
4189 }
4190 }
4191
4192 /**
4193 * Checks the state of the system and the activity associated with the given {@param token} to
4194 * verify that picture-in-picture is supported for that activity.
4195 *
4196 * @return the activity record for the given {@param token} if all the checks pass.
4197 */
4198 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4199 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004200 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 throw new IllegalStateException(caller
4202 + ": Device doesn't support picture-in-picture mode.");
4203 }
4204
4205 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4206 if (r == null) {
4207 throw new IllegalStateException(caller
4208 + ": Can't find activity for token=" + token);
4209 }
4210
4211 if (!r.supportsPictureInPicture()) {
4212 throw new IllegalStateException(caller
4213 + ": Current activity does not support picture-in-picture.");
4214 }
4215
4216 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004217 && !mWindowManager.isValidPictureInPictureAspectRatio(
4218 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 final float minAspectRatio = mContext.getResources().getFloat(
4220 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4221 final float maxAspectRatio = mContext.getResources().getFloat(
4222 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4223 throw new IllegalArgumentException(String.format(caller
4224 + ": Aspect ratio is too extreme (must be between %f and %f).",
4225 minAspectRatio, maxAspectRatio));
4226 }
4227
4228 // Truncate the number of actions if necessary
4229 params.truncateActions(getMaxNumPictureInPictureActions(token));
4230
4231 return r;
4232 }
4233
4234 @Override
4235 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 synchronized (mGlobalLock) {
4238 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4239 if (r == null) {
4240 throw new IllegalArgumentException("Activity does not exist; token="
4241 + activityToken);
4242 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004243 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 }
4245 }
4246
4247 @Override
4248 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4249 Rect tempDockedTaskInsetBounds,
4250 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 long ident = Binder.clearCallingIdentity();
4253 try {
4254 synchronized (mGlobalLock) {
4255 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4256 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4257 PRESERVE_WINDOWS);
4258 }
4259 } finally {
4260 Binder.restoreCallingIdentity(ident);
4261 }
4262 }
4263
4264 @Override
4265 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004266 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 final long ident = Binder.clearCallingIdentity();
4268 try {
4269 synchronized (mGlobalLock) {
4270 mStackSupervisor.setSplitScreenResizing(resizing);
4271 }
4272 } finally {
4273 Binder.restoreCallingIdentity(ident);
4274 }
4275 }
4276
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004277 /**
4278 * Check that we have the features required for VR-related API calls, and throw an exception if
4279 * not.
4280 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004281 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 if (!mContext.getPackageManager().hasSystemFeature(
4283 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4284 throw new UnsupportedOperationException("VR mode not supported on this device!");
4285 }
4286 }
4287
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 @Override
4289 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004290 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291
4292 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4293
4294 ActivityRecord r;
4295 synchronized (mGlobalLock) {
4296 r = ActivityRecord.isInStackLocked(token);
4297 }
4298
4299 if (r == null) {
4300 throw new IllegalArgumentException();
4301 }
4302
4303 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004304 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305 VrManagerInternal.NO_ERROR) {
4306 return err;
4307 }
4308
4309 // Clear the binder calling uid since this path may call moveToTask().
4310 final long callingId = Binder.clearCallingIdentity();
4311 try {
4312 synchronized (mGlobalLock) {
4313 r.requestedVrComponent = (enabled) ? packageName : null;
4314
4315 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004316 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004317 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
4319 return 0;
4320 }
4321 } finally {
4322 Binder.restoreCallingIdentity(callingId);
4323 }
4324 }
4325
4326 @Override
4327 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4328 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4329 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004330 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004331 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4332 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4333 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004334 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335 || activity.voiceSession != null) {
4336 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4337 return;
4338 }
4339 if (activity.pendingVoiceInteractionStart) {
4340 Slog.w(TAG, "Pending start of voice interaction already.");
4341 return;
4342 }
4343 activity.pendingVoiceInteractionStart = true;
4344 }
4345 LocalServices.getService(VoiceInteractionManagerInternal.class)
4346 .startLocalVoiceInteraction(callingActivity, options);
4347 }
4348
4349 @Override
4350 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4351 LocalServices.getService(VoiceInteractionManagerInternal.class)
4352 .stopLocalVoiceInteraction(callingActivity);
4353 }
4354
4355 @Override
4356 public boolean supportsLocalVoiceInteraction() {
4357 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4358 .supportsLocalVoiceInteraction();
4359 }
4360
4361 /** Notifies all listeners when the pinned stack animation starts. */
4362 @Override
4363 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004364 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 }
4366
4367 /** Notifies all listeners when the pinned stack animation ends. */
4368 @Override
4369 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004370 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 }
4372
4373 @Override
4374 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 final long ident = Binder.clearCallingIdentity();
4377 try {
4378 synchronized (mGlobalLock) {
4379 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4380 }
4381 } finally {
4382 Binder.restoreCallingIdentity(ident);
4383 }
4384 }
4385
4386 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389
4390 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 }
4395
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004396 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004397 final Message msg = PooledLambda.obtainMessage(
4398 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4399 DEFAULT_DISPLAY);
4400 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 }
4402
4403 final long origId = Binder.clearCallingIdentity();
4404 try {
4405 if (values != null) {
4406 Settings.System.clearConfiguration(values);
4407 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 UserHandle.USER_NULL, false /* deferResume */,
4410 mTmpUpdateConfigurationResult);
4411 return mTmpUpdateConfigurationResult.changes != 0;
4412 } finally {
4413 Binder.restoreCallingIdentity(origId);
4414 }
4415 }
4416 }
4417
4418 @Override
4419 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4420 CharSequence message) {
4421 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4424 }
4425 final long callingId = Binder.clearCallingIdentity();
4426 try {
4427 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004428 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 }
4430 } finally {
4431 Binder.restoreCallingIdentity(callingId);
4432 }
4433 }
4434
4435 @Override
4436 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 "cancelTaskWindowTransition()");
4439 final long ident = Binder.clearCallingIdentity();
4440 try {
4441 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004442 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 MATCH_TASK_IN_STACKS_ONLY);
4444 if (task == null) {
4445 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4446 return;
4447 }
4448 task.cancelWindowTransition();
4449 }
4450 } finally {
4451 Binder.restoreCallingIdentity(ident);
4452 }
4453 }
4454
4455 @Override
4456 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 final long ident = Binder.clearCallingIdentity();
4459 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004460 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 } finally {
4462 Binder.restoreCallingIdentity(ident);
4463 }
4464 }
4465
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004466 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4467 boolean restoreFromDisk) {
4468 final TaskRecord task;
4469 synchronized (mGlobalLock) {
4470 task = mRootActivityContainer.anyTaskForId(taskId,
4471 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4472 if (task == null) {
4473 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4474 return null;
4475 }
4476 }
4477 // Don't call this while holding the lock as this operation might hit the disk.
4478 return task.getSnapshot(reducedResolution, restoreFromDisk);
4479 }
4480
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481 @Override
4482 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4483 synchronized (mGlobalLock) {
4484 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4485 if (r == null) {
4486 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4487 + token);
4488 return;
4489 }
4490 final long origId = Binder.clearCallingIdentity();
4491 try {
4492 r.setDisablePreviewScreenshots(disable);
4493 } finally {
4494 Binder.restoreCallingIdentity(origId);
4495 }
4496 }
4497 }
4498
4499 /** Return the user id of the last resumed activity. */
4500 @Override
4501 public @UserIdInt
4502 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4505 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004506 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004509 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 }
4511 }
4512
4513 @Override
4514 public void updateLockTaskFeatures(int userId, int flags) {
4515 final int callingUid = Binder.getCallingUid();
4516 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 "updateLockTaskFeatures()");
4519 }
4520 synchronized (mGlobalLock) {
4521 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4522 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004523 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004524 }
4525 }
4526
4527 @Override
4528 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4529 synchronized (mGlobalLock) {
4530 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4531 if (r == null) {
4532 return;
4533 }
4534 final long origId = Binder.clearCallingIdentity();
4535 try {
4536 r.setShowWhenLocked(showWhenLocked);
4537 } finally {
4538 Binder.restoreCallingIdentity(origId);
4539 }
4540 }
4541 }
4542
4543 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004544 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4545 synchronized (mGlobalLock) {
4546 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4547 if (r == null) {
4548 return;
4549 }
4550 final long origId = Binder.clearCallingIdentity();
4551 try {
4552 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4553 } finally {
4554 Binder.restoreCallingIdentity(origId);
4555 }
4556 }
4557 }
4558
4559 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004560 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4561 synchronized (mGlobalLock) {
4562 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4563 if (r == null) {
4564 return;
4565 }
4566 final long origId = Binder.clearCallingIdentity();
4567 try {
4568 r.setTurnScreenOn(turnScreenOn);
4569 } finally {
4570 Binder.restoreCallingIdentity(origId);
4571 }
4572 }
4573 }
4574
4575 @Override
4576 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004577 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004579 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 synchronized (mGlobalLock) {
4581 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4582 if (r == null) {
4583 return;
4584 }
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
4587 r.registerRemoteAnimations(definition);
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
4593
4594 @Override
4595 public void registerRemoteAnimationForNextActivityStart(String packageName,
4596 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004597 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004598 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004599 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 synchronized (mGlobalLock) {
4601 final long origId = Binder.clearCallingIdentity();
4602 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004603 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004604 packageName, adapter);
4605 } finally {
4606 Binder.restoreCallingIdentity(origId);
4607 }
4608 }
4609 }
4610
Evan Rosky966759f2019-01-15 10:33:58 -08004611 @Override
4612 public void registerRemoteAnimationsForDisplay(int displayId,
4613 RemoteAnimationDefinition definition) {
4614 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4615 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004616 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004617 synchronized (mGlobalLock) {
4618 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4619 if (display == null) {
4620 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4621 return;
4622 }
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
4625 display.mDisplayContent.registerRemoteAnimations(definition);
4626 } finally {
4627 Binder.restoreCallingIdentity(origId);
4628 }
4629 }
4630 }
4631
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4633 @Override
4634 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4635 synchronized (mGlobalLock) {
4636 final long origId = Binder.clearCallingIdentity();
4637 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004638 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 } finally {
4640 Binder.restoreCallingIdentity(origId);
4641 }
4642 }
4643 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004644
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 @Override
4646 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004647 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004648 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004649 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004650 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004651 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 }
4653 }
4654
4655 @Override
4656 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004657 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004658 != PERMISSION_GRANTED) {
4659 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4660 + Binder.getCallingPid()
4661 + ", uid=" + Binder.getCallingUid()
4662 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4663 Slog.w(TAG, msg);
4664 throw new SecurityException(msg);
4665 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004666 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004667 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004668 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004669 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004670 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 }
4672 }
4673
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004674 @Override
4675 public void stopAppSwitches() {
4676 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4677 synchronized (mGlobalLock) {
4678 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004679 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004680 mDidAppSwitch = false;
4681 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4682 }
4683 }
4684
4685 @Override
4686 public void resumeAppSwitches() {
4687 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4688 synchronized (mGlobalLock) {
4689 // Note that we don't execute any pending app switches... we will
4690 // let those wait until either the timeout, or the next start
4691 // activity request.
4692 mAppSwitchesAllowedTime = 0;
4693 }
4694 }
4695
Ricky Wai906af482019-06-03 17:25:28 +01004696 long getLastStopAppSwitchesTime() {
4697 return mLastStopAppSwitchesTime;
4698 }
4699
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004700 void onStartActivitySetDidAppSwitch() {
4701 if (mDidAppSwitch) {
4702 // This is the second allowed switch since we stopped switches, so now just generally
4703 // allow switches. Use case:
4704 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4705 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4706 // anyone to switch again).
4707 mAppSwitchesAllowedTime = 0;
4708 } else {
4709 mDidAppSwitch = true;
4710 }
4711 }
4712
4713 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 boolean shouldDisableNonVrUiLocked() {
4715 return mVrController.shouldDisableNonVrUiLocked();
4716 }
4717
Wale Ogunwale53783742018-09-16 10:21:51 -07004718 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 // 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 +00004720 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004722 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4723 + " to main display for VR");
4724 mRootActivityContainer.moveStackToDisplay(
4725 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 }
4727 mH.post(() -> {
4728 if (!mVrController.onVrModeChanged(r)) {
4729 return;
4730 }
4731 synchronized (mGlobalLock) {
4732 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4733 mWindowManager.disableNonVrUi(disableNonVrUi);
4734 if (disableNonVrUi) {
4735 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4736 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004737 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 }
4739 }
4740 });
4741 }
4742
Wale Ogunwale53783742018-09-16 10:21:51 -07004743 @Override
4744 public int getPackageScreenCompatMode(String packageName) {
4745 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4746 synchronized (mGlobalLock) {
4747 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4748 }
4749 }
4750
4751 @Override
4752 public void setPackageScreenCompatMode(String packageName, int mode) {
4753 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4754 "setPackageScreenCompatMode");
4755 synchronized (mGlobalLock) {
4756 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4757 }
4758 }
4759
4760 @Override
4761 public boolean getPackageAskScreenCompat(String packageName) {
4762 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4763 synchronized (mGlobalLock) {
4764 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4765 }
4766 }
4767
4768 @Override
4769 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4770 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4771 "setPackageAskScreenCompat");
4772 synchronized (mGlobalLock) {
4773 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4774 }
4775 }
4776
Wale Ogunwale64258362018-10-16 15:13:37 -07004777 public static String relaunchReasonToString(int relaunchReason) {
4778 switch (relaunchReason) {
4779 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4780 return "window_resize";
4781 case RELAUNCH_REASON_FREE_RESIZE:
4782 return "free_resize";
4783 default:
4784 return null;
4785 }
4786 }
4787
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004788 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004789 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004790 }
4791
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004792 /** Pokes the task persister. */
4793 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4794 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4795 }
4796
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 boolean isKeyguardLocked() {
4798 return mKeyguardController.isKeyguardLocked();
4799 }
4800
Garfield Tan01548632018-11-27 10:15:48 -08004801 /**
4802 * Clears launch params for the given package.
4803 * @param packageNames the names of the packages of which the launch params are to be cleared
4804 */
4805 @Override
4806 public void clearLaunchParamsForPackages(List<String> packageNames) {
4807 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4808 "clearLaunchParamsForPackages");
4809 synchronized (mGlobalLock) {
4810 for (int i = 0; i < packageNames.size(); ++i) {
4811 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4812 }
4813 }
4814 }
4815
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004816 /**
4817 * Makes the display with the given id a single task instance display. I.e the display can only
4818 * contain one task.
4819 */
4820 @Override
4821 public void setDisplayToSingleTaskInstance(int displayId) {
4822 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4823 "setDisplayToSingleTaskInstance");
4824 final long origId = Binder.clearCallingIdentity();
4825 try {
4826 final ActivityDisplay display =
4827 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4828 if (display != null) {
4829 display.setDisplayToSingleTaskInstance();
4830 }
4831 } finally {
4832 Binder.restoreCallingIdentity(origId);
4833 }
4834 }
4835
Wale Ogunwale31913b52018-10-13 08:29:31 -07004836 void dumpLastANRLocked(PrintWriter pw) {
4837 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4838 if (mLastANRState == null) {
4839 pw.println(" <no ANR has occurred since boot>");
4840 } else {
4841 pw.println(mLastANRState);
4842 }
4843 }
4844
4845 void dumpLastANRTracesLocked(PrintWriter pw) {
4846 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4847
4848 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4849 if (ArrayUtils.isEmpty(files)) {
4850 pw.println(" <no ANR has occurred since boot>");
4851 return;
4852 }
4853 // Find the latest file.
4854 File latest = null;
4855 for (File f : files) {
4856 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4857 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004858 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004859 }
4860 pw.print("File: ");
4861 pw.print(latest.getName());
4862 pw.println();
4863 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4864 String line;
4865 while ((line = in.readLine()) != null) {
4866 pw.println(line);
4867 }
4868 } catch (IOException e) {
4869 pw.print("Unable to read: ");
4870 pw.print(e);
4871 pw.println();
4872 }
4873 }
4874
4875 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4876 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4877 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4878 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4879 }
4880
4881 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4882 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4883 pw.println(header);
4884
Wale Ogunwaled32da472018-11-16 07:19:28 -08004885 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004886 dumpPackage);
4887 boolean needSep = printedAnything;
4888
4889 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004890 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004891 " ResumedActivity: ");
4892 if (printed) {
4893 printedAnything = true;
4894 needSep = false;
4895 }
4896
4897 if (dumpPackage == null) {
4898 if (needSep) {
4899 pw.println();
4900 }
4901 printedAnything = true;
4902 mStackSupervisor.dump(pw, " ");
4903 }
4904
4905 if (!printedAnything) {
4906 pw.println(" (nothing)");
4907 }
4908 }
4909
4910 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004911 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004912 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004913 pw.println(" ");
4914 }
4915
4916 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4917 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4918 getActivityStartController().dump(pw, "", dumpPackage);
4919 }
4920
4921 /**
4922 * There are three things that cmd can be:
4923 * - a flattened component name that matches an existing activity
4924 * - the cmd arg isn't the flattened component name of an existing activity:
4925 * dump all activity whose component contains the cmd as a substring
4926 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004927 * <p>
4928 * The caller should not hold lock when calling this method because it will wait for the
4929 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 *
4931 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4932 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4933 */
4934 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4935 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4936 ArrayList<ActivityRecord> activities;
4937
4938 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004939 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004940 dumpFocusedStackOnly);
4941 }
4942
4943 if (activities.size() <= 0) {
4944 return false;
4945 }
4946
4947 String[] newArgs = new String[args.length - opti];
4948 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4949
4950 TaskRecord lastTask = null;
4951 boolean needSep = false;
4952 for (int i = activities.size() - 1; i >= 0; i--) {
4953 ActivityRecord r = activities.get(i);
4954 if (needSep) {
4955 pw.println();
4956 }
4957 needSep = true;
4958 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004959 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004960 if (lastTask != task) {
4961 lastTask = task;
4962 pw.print("TASK "); pw.print(lastTask.affinity);
4963 pw.print(" id="); pw.print(lastTask.taskId);
4964 pw.print(" userId="); pw.println(lastTask.userId);
4965 if (dumpAll) {
4966 lastTask.dump(pw, " ");
4967 }
4968 }
4969 }
4970 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4971 }
4972 return true;
4973 }
4974
4975 /**
4976 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4977 * there is a thread associated with the activity.
4978 */
4979 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4980 final ActivityRecord r, String[] args, boolean dumpAll) {
4981 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004982 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004983 synchronized (mGlobalLock) {
4984 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4985 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4986 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004987 if (r.hasProcess()) {
4988 pw.println(r.app.getPid());
4989 appThread = r.app.getThread();
4990 } else {
4991 pw.println("(not running)");
4992 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004993 if (dumpAll) {
4994 r.dump(pw, innerPrefix);
4995 }
4996 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004997 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004998 // flush anything that is already in the PrintWriter since the thread is going
4999 // to write to the file descriptor directly
5000 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005001 try (TransferPipe tp = new TransferPipe()) {
5002 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5003 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 } catch (IOException e) {
5005 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5006 } catch (RemoteException e) {
5007 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5008 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005009 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005010 }
5011
sanryhuang498e77e2018-12-06 14:57:01 +08005012 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5013 boolean testPssMode) {
5014 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5016 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005017 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005018 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5019 st.toString());
5020 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005021 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5023 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005024 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5025 testPssMode);
5026 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005027 }
5028
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005029 int getCurrentUserId() {
5030 return mAmInternal.getCurrentUserId();
5031 }
5032
5033 private void enforceNotIsolatedCaller(String caller) {
5034 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5035 throw new SecurityException("Isolated process not allowed to call " + caller);
5036 }
5037 }
5038
Wale Ogunwalef6733932018-06-27 05:14:34 -07005039 public Configuration getConfiguration() {
5040 Configuration ci;
5041 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005042 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005043 ci.userSetLocale = false;
5044 }
5045 return ci;
5046 }
5047
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005048 /**
5049 * Current global configuration information. Contains general settings for the entire system,
5050 * also corresponds to the merged configuration of the default display.
5051 */
5052 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005053 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005054 }
5055
5056 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5057 boolean initLocale) {
5058 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5059 }
5060
5061 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5062 boolean initLocale, boolean deferResume) {
5063 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5064 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5065 UserHandle.USER_NULL, deferResume);
5066 }
5067
Wale Ogunwale59507092018-10-29 09:00:30 -07005068 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005069 final long origId = Binder.clearCallingIdentity();
5070 try {
5071 synchronized (mGlobalLock) {
5072 updateConfigurationLocked(values, null, false, true, userId,
5073 false /* deferResume */);
5074 }
5075 } finally {
5076 Binder.restoreCallingIdentity(origId);
5077 }
5078 }
5079
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005080 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5081 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5082 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5083 deferResume, null /* result */);
5084 }
5085
5086 /**
5087 * Do either or both things: (1) change the current configuration, and (2)
5088 * make sure the given activity is running with the (now) current
5089 * configuration. Returns true if the activity has been left running, or
5090 * false if <var>starting</var> is being destroyed to match the new
5091 * configuration.
5092 *
5093 * @param userId is only used when persistent parameter is set to true to persist configuration
5094 * for that particular user
5095 */
5096 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5097 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5098 ActivityTaskManagerService.UpdateConfigurationResult result) {
5099 int changes = 0;
5100 boolean kept = true;
5101
5102 if (mWindowManager != null) {
5103 mWindowManager.deferSurfaceLayout();
5104 }
5105 try {
5106 if (values != null) {
5107 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5108 deferResume);
5109 }
5110
5111 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5112 } finally {
5113 if (mWindowManager != null) {
5114 mWindowManager.continueSurfaceLayout();
5115 }
5116 }
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
Wale Ogunwalef6733932018-06-27 05:14:34 -07005243 private void updateEventDispatchingLocked(boolean booted) {
5244 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5245 }
5246
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5248 final ContentResolver resolver = mContext.getContentResolver();
5249 Settings.System.putConfigurationForUser(resolver, config, userId);
5250 }
5251
5252 private void sendLocaleToMountDaemonMsg(Locale l) {
5253 try {
5254 IBinder service = ServiceManager.getService("mount");
5255 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5256 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5257 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5258 } catch (RemoteException e) {
5259 Log.e(TAG, "Error storing locale for decryption UI", e);
5260 }
5261 }
5262
Alison Cichowlas3e340502018-08-07 17:15:01 -04005263 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5264 mStartActivitySources.remove(permissionToken);
5265 mExpiredStartAsCallerTokens.add(permissionToken);
5266 }
5267
5268 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5269 mExpiredStartAsCallerTokens.remove(permissionToken);
5270 }
5271
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005272 boolean isActivityStartsLoggingEnabled() {
5273 return mAmInternal.isActivityStartsLoggingEnabled();
5274 }
5275
Michal Karpinski8596ded2018-11-14 14:43:48 +00005276 boolean isBackgroundActivityStartsEnabled() {
5277 return mAmInternal.isBackgroundActivityStartsEnabled();
5278 }
5279
Wale Ogunwalef6733932018-06-27 05:14:34 -07005280 void enableScreenAfterBoot(boolean booted) {
5281 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5282 SystemClock.uptimeMillis());
5283 mWindowManager.enableScreenAfterBoot();
5284
5285 synchronized (mGlobalLock) {
5286 updateEventDispatchingLocked(booted);
5287 }
5288 }
5289
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005290 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5291 if (r == null || !r.hasProcess()) {
5292 return KEY_DISPATCHING_TIMEOUT_MS;
5293 }
5294 return getInputDispatchingTimeoutLocked(r.app);
5295 }
5296
5297 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005298 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005299 }
5300
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 /**
5302 * Decide based on the configuration whether we should show the ANR,
5303 * crash, etc dialogs. The idea is that if there is no affordance to
5304 * press the on-screen buttons, or the user experience would be more
5305 * greatly impacted than the crash itself, we shouldn't show the dialog.
5306 *
5307 * A thought: SystemUI might also want to get told about this, the Power
5308 * dialog / global actions also might want different behaviors.
5309 */
5310 private void updateShouldShowDialogsLocked(Configuration config) {
5311 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5312 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5313 && config.navigation == Configuration.NAVIGATION_NONAV);
5314 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5315 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5316 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5317 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5318 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5319 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5320 HIDE_ERROR_DIALOGS, 0) != 0;
5321 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5322 }
5323
5324 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5325 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5326 FONT_SCALE, 1.0f, userId);
5327
5328 synchronized (this) {
5329 if (getGlobalConfiguration().fontScale == scaleFactor) {
5330 return;
5331 }
5332
5333 final Configuration configuration
5334 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5335 configuration.fontScale = scaleFactor;
5336 updatePersistentConfiguration(configuration, userId);
5337 }
5338 }
5339
5340 // Actually is sleeping or shutting down or whatever else in the future
5341 // is an inactive state.
5342 boolean isSleepingOrShuttingDownLocked() {
5343 return isSleepingLocked() || mShuttingDown;
5344 }
5345
5346 boolean isSleepingLocked() {
5347 return mSleeping;
5348 }
5349
Riddle Hsu16567132018-08-16 21:37:47 +08005350 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005351 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005352 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 if (task.isActivityTypeStandard()) {
5354 if (mCurAppTimeTracker != r.appTimeTracker) {
5355 // We are switching app tracking. Complete the current one.
5356 if (mCurAppTimeTracker != null) {
5357 mCurAppTimeTracker.stop();
5358 mH.obtainMessage(
5359 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005360 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 mCurAppTimeTracker = null;
5362 }
5363 if (r.appTimeTracker != null) {
5364 mCurAppTimeTracker = r.appTimeTracker;
5365 startTimeTrackingFocusedActivityLocked();
5366 }
5367 } else {
5368 startTimeTrackingFocusedActivityLocked();
5369 }
5370 } else {
5371 r.appTimeTracker = null;
5372 }
5373 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5374 // TODO: Probably not, because we don't want to resume voice on switching
5375 // back to this activity
5376 if (task.voiceInteractor != null) {
5377 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5378 } else {
5379 finishRunningVoiceLocked();
5380
5381 if (mLastResumedActivity != null) {
5382 final IVoiceInteractionSession session;
5383
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005384 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005385 if (lastResumedActivityTask != null
5386 && lastResumedActivityTask.voiceSession != null) {
5387 session = lastResumedActivityTask.voiceSession;
5388 } else {
5389 session = mLastResumedActivity.voiceSession;
5390 }
5391
5392 if (session != null) {
5393 // We had been in a voice interaction session, but now focused has
5394 // move to something different. Just finish the session, we can't
5395 // return to it and retain the proper state and synchronization with
5396 // the voice interaction service.
5397 finishVoiceTask(session);
5398 }
5399 }
5400 }
5401
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005402 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5403 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005404 }
5405 updateResumedAppTrace(r);
5406 mLastResumedActivity = r;
5407
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005408 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005409
5410 applyUpdateLockStateLocked(r);
5411 applyUpdateVrModeLocked(r);
5412
5413 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005414 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 r == null ? "NULL" : r.shortComponentName,
5416 reason);
5417 }
5418
5419 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5420 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005421 final ActivityTaskManagerInternal.SleepToken token =
5422 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005423 updateSleepIfNeededLocked();
5424 return token;
5425 }
5426 }
5427
5428 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005429 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 final boolean wasSleeping = mSleeping;
5431 boolean updateOomAdj = false;
5432
5433 if (!shouldSleep) {
5434 // If wasSleeping is true, we need to wake up activity manager state from when
5435 // we started sleeping. In either case, we need to apply the sleep tokens, which
5436 // will wake up stacks or put them to sleep as appropriate.
5437 if (wasSleeping) {
5438 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005439 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5440 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005441 startTimeTrackingFocusedActivityLocked();
5442 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005443 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005444 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5445 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005446 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 if (wasSleeping) {
5448 updateOomAdj = true;
5449 }
5450 } else if (!mSleeping && shouldSleep) {
5451 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005452 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5453 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 if (mCurAppTimeTracker != null) {
5455 mCurAppTimeTracker.stop();
5456 }
5457 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005458 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 mStackSupervisor.goingToSleepLocked();
5460 updateResumedAppTrace(null /* resumed */);
5461 updateOomAdj = true;
5462 }
5463 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005464 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 }
5466 }
5467
5468 void updateOomAdj() {
5469 mH.post(mAmInternal::updateOomAdj);
5470 }
5471
Wale Ogunwale53783742018-09-16 10:21:51 -07005472 void updateCpuStats() {
5473 mH.post(mAmInternal::updateCpuStats);
5474 }
5475
Hui Yu03d12402018-12-06 18:00:37 -08005476 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5477 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005478 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5479 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005480 mH.sendMessage(m);
5481 }
5482
Hui Yu03d12402018-12-06 18:00:37 -08005483 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005484 ComponentName taskRoot = null;
5485 final TaskRecord task = activity.getTaskRecord();
5486 if (task != null) {
5487 final ActivityRecord rootActivity = task.getRootActivity();
5488 if (rootActivity != null) {
5489 taskRoot = rootActivity.mActivityComponent;
5490 }
5491 }
5492
Hui Yu03d12402018-12-06 18:00:37 -08005493 final Message m = PooledLambda.obtainMessage(
5494 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005495 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005496 mH.sendMessage(m);
5497 }
5498
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005499 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5500 String hostingType) {
5501 try {
5502 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5503 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5504 + activity.processName);
5505 }
5506 // Post message to start process to avoid possible deadlock of calling into AMS with the
5507 // ATMS lock held.
5508 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5509 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5510 isTop, hostingType, activity.intent.getComponent());
5511 mH.sendMessage(m);
5512 } finally {
5513 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5514 }
5515 }
5516
Wale Ogunwale53783742018-09-16 10:21:51 -07005517 void setBooting(boolean booting) {
5518 mAmInternal.setBooting(booting);
5519 }
5520
5521 boolean isBooting() {
5522 return mAmInternal.isBooting();
5523 }
5524
5525 void setBooted(boolean booted) {
5526 mAmInternal.setBooted(booted);
5527 }
5528
5529 boolean isBooted() {
5530 return mAmInternal.isBooted();
5531 }
5532
5533 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5534 mH.post(() -> {
5535 if (finishBooting) {
5536 mAmInternal.finishBooting();
5537 }
5538 if (enableScreen) {
5539 mInternal.enableScreenAfterBoot(isBooted());
5540 }
5541 });
5542 }
5543
5544 void setHeavyWeightProcess(ActivityRecord root) {
5545 mHeavyWeightProcess = root.app;
5546 final Message m = PooledLambda.obtainMessage(
5547 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005548 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005549 mH.sendMessage(m);
5550 }
5551
5552 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5553 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5554 return;
5555 }
5556
5557 mHeavyWeightProcess = null;
5558 final Message m = PooledLambda.obtainMessage(
5559 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5560 proc.mUserId);
5561 mH.sendMessage(m);
5562 }
5563
5564 private void cancelHeavyWeightProcessNotification(int userId) {
5565 final INotificationManager inm = NotificationManager.getService();
5566 if (inm == null) {
5567 return;
5568 }
5569 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005570 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005571 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5572 } catch (RuntimeException e) {
5573 Slog.w(TAG, "Error canceling notification for service", e);
5574 } catch (RemoteException e) {
5575 }
5576
5577 }
5578
5579 private void postHeavyWeightProcessNotification(
5580 WindowProcessController proc, Intent intent, int userId) {
5581 if (proc == null) {
5582 return;
5583 }
5584
5585 final INotificationManager inm = NotificationManager.getService();
5586 if (inm == null) {
5587 return;
5588 }
5589
5590 try {
5591 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5592 String text = mContext.getString(R.string.heavy_weight_notification,
5593 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5594 Notification notification =
5595 new Notification.Builder(context,
5596 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5597 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5598 .setWhen(0)
5599 .setOngoing(true)
5600 .setTicker(text)
5601 .setColor(mContext.getColor(
5602 com.android.internal.R.color.system_notification_accent_color))
5603 .setContentTitle(text)
5604 .setContentText(
5605 mContext.getText(R.string.heavy_weight_notification_detail))
5606 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5607 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5608 new UserHandle(userId)))
5609 .build();
5610 try {
5611 inm.enqueueNotificationWithTag("android", "android", null,
5612 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5613 } catch (RuntimeException e) {
5614 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5615 } catch (RemoteException e) {
5616 }
5617 } catch (PackageManager.NameNotFoundException e) {
5618 Slog.w(TAG, "Unable to create context for heavy notification", e);
5619 }
5620
5621 }
5622
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005623 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5624 IBinder token, String resultWho, int requestCode, Intent[] intents,
5625 String[] resolvedTypes, int flags, Bundle bOptions) {
5626
5627 ActivityRecord activity = null;
5628 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5629 activity = ActivityRecord.isInStackLocked(token);
5630 if (activity == null) {
5631 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5632 return null;
5633 }
5634 if (activity.finishing) {
5635 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5636 return null;
5637 }
5638 }
5639
5640 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5641 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5642 bOptions);
5643 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5644 if (noCreate) {
5645 return rec;
5646 }
5647 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5648 if (activity.pendingResults == null) {
5649 activity.pendingResults = new HashSet<>();
5650 }
5651 activity.pendingResults.add(rec.ref);
5652 }
5653 return rec;
5654 }
5655
Andrii Kulian52d255c2018-07-13 11:32:19 -07005656 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005657 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005658 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5660 mCurAppTimeTracker.start(resumedActivity.packageName);
5661 }
5662 }
5663
5664 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5665 if (mTracedResumedActivity != null) {
5666 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5667 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5668 }
5669 if (resumed != null) {
5670 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5671 constructResumedTraceName(resumed.packageName), 0);
5672 }
5673 mTracedResumedActivity = resumed;
5674 }
5675
5676 private String constructResumedTraceName(String packageName) {
5677 return "focused app: " + packageName;
5678 }
5679
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005680 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005681 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005682 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005683 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005684 // mainStack is null during startup.
5685 if (mainStack != null) {
5686 if (changes != 0 && starting == null) {
5687 // If the configuration changed, and the caller is not already
5688 // in the process of starting an activity, then find the top
5689 // activity to check if its configuration needs to change.
5690 starting = mainStack.topRunningActivityLocked();
5691 }
5692
5693 if (starting != null) {
5694 kept = starting.ensureActivityConfiguration(changes,
5695 false /* preserveWindow */);
5696 // And we need to make sure at this point that all other activities
5697 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005698 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005699 !PRESERVE_WINDOWS);
5700 }
5701 }
5702
5703 return kept;
5704 }
5705
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005706 void scheduleAppGcsLocked() {
5707 mH.post(() -> mAmInternal.scheduleAppGcs());
5708 }
5709
Wale Ogunwale53783742018-09-16 10:21:51 -07005710 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5711 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5712 }
5713
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005714 /**
5715 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5716 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5717 * on demand.
5718 */
5719 IPackageManager getPackageManager() {
5720 return AppGlobals.getPackageManager();
5721 }
5722
5723 PackageManagerInternal getPackageManagerInternalLocked() {
5724 if (mPmInternal == null) {
5725 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5726 }
5727 return mPmInternal;
5728 }
5729
Hai Zhangf4da9be2019-05-01 13:46:06 +08005730 PermissionPolicyInternal getPermissionPolicyInternal() {
5731 if (mPermissionPolicyInternal == null) {
5732 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5733 }
5734 return mPermissionPolicyInternal;
5735 }
5736
Wale Ogunwale008163e2018-07-23 23:11:08 -07005737 AppWarnings getAppWarningsLocked() {
5738 return mAppWarnings;
5739 }
5740
Wale Ogunwale214f3482018-10-04 11:00:47 -07005741 Intent getHomeIntent() {
5742 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5743 intent.setComponent(mTopComponent);
5744 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5745 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5746 intent.addCategory(Intent.CATEGORY_HOME);
5747 }
5748 return intent;
5749 }
5750
Chilun2ef71f72018-11-16 17:57:15 +08005751 /**
5752 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5753 * activities.
5754 *
5755 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5756 * component defined in config_secondaryHomeComponent.
5757 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5758 */
5759 Intent getSecondaryHomeIntent(String preferredPackage) {
5760 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005761 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5762 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5763 if (preferredPackage == null || useSystemProvidedLauncher) {
5764 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005765 final String secondaryHomeComponent = mContext.getResources().getString(
5766 com.android.internal.R.string.config_secondaryHomeComponent);
5767 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5768 } else {
5769 intent.setPackage(preferredPackage);
5770 }
5771 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5772 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5773 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5774 }
5775 return intent;
5776 }
5777
Wale Ogunwale214f3482018-10-04 11:00:47 -07005778 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5779 if (info == null) return null;
5780 ApplicationInfo newInfo = new ApplicationInfo(info);
5781 newInfo.initForUser(userId);
5782 return newInfo;
5783 }
5784
Wale Ogunwale9c103022018-10-18 07:44:54 -07005785 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005786 if (uid == SYSTEM_UID) {
5787 // The system gets to run in any process. If there are multiple processes with the same
5788 // uid, just pick the first (this should never happen).
5789 final SparseArray<WindowProcessController> procs =
5790 mProcessNames.getMap().get(processName);
5791 if (procs == null) return null;
5792 final int procCount = procs.size();
5793 for (int i = 0; i < procCount; i++) {
5794 final int procUid = procs.keyAt(i);
5795 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5796 // Don't use an app process or different user process for system component.
5797 continue;
5798 }
5799 return procs.valueAt(i);
5800 }
5801 }
5802
5803 return mProcessNames.get(processName, uid);
5804 }
5805
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005806 WindowProcessController getProcessController(IApplicationThread thread) {
5807 if (thread == null) {
5808 return null;
5809 }
5810
5811 final IBinder threadBinder = thread.asBinder();
5812 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5813 for (int i = pmap.size()-1; i >= 0; i--) {
5814 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5815 for (int j = procs.size() - 1; j >= 0; j--) {
5816 final WindowProcessController proc = procs.valueAt(j);
5817 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5818 return proc;
5819 }
5820 }
5821 }
5822
5823 return null;
5824 }
5825
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005826 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005827 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005828 if (proc == null) return null;
5829 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5830 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005831 }
5832 return null;
5833 }
5834
Riddle Hsua0536432019-02-16 00:38:59 +08005835 int getUidState(int uid) {
5836 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005837 }
5838
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005839 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005840 // A uid is considered to be foreground if it has a visible non-toast window.
5841 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005842 }
5843
Ricky Wai96f5c352019-04-10 18:40:17 +01005844 boolean isDeviceOwner(int uid) {
5845 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005846 }
5847
Ricky Wai96f5c352019-04-10 18:40:17 +01005848 void setDeviceOwnerUid(int uid) {
5849 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005850 }
5851
Wale Ogunwale9de19442018-10-18 19:05:03 -07005852 /**
5853 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5854 * the whitelist
5855 */
5856 String getPendingTempWhitelistTagForUidLocked(int uid) {
5857 return mPendingTempWhitelist.get(uid);
5858 }
5859
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005860 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5861 if (true || Build.IS_USER) {
5862 return;
5863 }
5864
5865 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5866 StrictMode.allowThreadDiskWrites();
5867 try {
5868 File tracesDir = new File("/data/anr");
5869 File tracesFile = null;
5870 try {
5871 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5872
5873 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005874 String timeString =
5875 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5876 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005877 sb.append(": ");
5878 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5879 sb.append(" since ");
5880 sb.append(msg);
5881 FileOutputStream fos = new FileOutputStream(tracesFile);
5882 fos.write(sb.toString().getBytes());
5883 if (app == null) {
5884 fos.write("\n*** No application process!".getBytes());
5885 }
5886 fos.close();
5887 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5888 } catch (IOException e) {
5889 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5890 return;
5891 }
5892
5893 if (app != null && app.getPid() > 0) {
5894 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5895 firstPids.add(app.getPid());
5896 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5897 }
5898
5899 File lastTracesFile = null;
5900 File curTracesFile = null;
5901 for (int i=9; i>=0; i--) {
5902 String name = String.format(Locale.US, "slow%02d.txt", i);
5903 curTracesFile = new File(tracesDir, name);
5904 if (curTracesFile.exists()) {
5905 if (lastTracesFile != null) {
5906 curTracesFile.renameTo(lastTracesFile);
5907 } else {
5908 curTracesFile.delete();
5909 }
5910 }
5911 lastTracesFile = curTracesFile;
5912 }
5913 tracesFile.renameTo(curTracesFile);
5914 } finally {
5915 StrictMode.setThreadPolicy(oldPolicy);
5916 }
5917 }
5918
Michal Karpinskida34cd42019-04-02 19:46:52 +01005919 boolean isAssociatedCompanionApp(int userId, int uid) {
5920 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5921 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005922 return false;
5923 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005924 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005925 }
5926
Issei Suzuki734bc942019-06-05 13:59:52 +02005927 void notifySingleTaskDisplayEmpty(int displayId) {
5928 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5929 }
5930
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005931 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005932 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005933
5934
Wale Ogunwale98875612018-10-12 07:53:02 -07005935 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5936 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005937
Riddle Hsud93a6c42018-11-29 21:50:06 +08005938 H(Looper looper) {
5939 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005940 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005941
5942 @Override
5943 public void handleMessage(Message msg) {
5944 switch (msg.what) {
5945 case REPORT_TIME_TRACKER_MSG: {
5946 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5947 tracker.deliverResult(mContext);
5948 } break;
5949 }
5950 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005951 }
5952
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005953 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005954 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005955
5956 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005957 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005958 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005959
5960 @Override
5961 public void handleMessage(Message msg) {
5962 switch (msg.what) {
5963 case DISMISS_DIALOG_UI_MSG: {
5964 final Dialog d = (Dialog) msg.obj;
5965 d.dismiss();
5966 break;
5967 }
5968 }
5969 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005970 }
5971
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005972 final class LocalService extends ActivityTaskManagerInternal {
5973 @Override
5974 public SleepToken acquireSleepToken(String tag, int displayId) {
5975 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005976 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005977 }
5978
5979 @Override
5980 public ComponentName getHomeActivityForUser(int userId) {
5981 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005982 final ActivityRecord homeActivity =
5983 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005984 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005985 }
5986 }
5987
5988 @Override
5989 public void onLocalVoiceInteractionStarted(IBinder activity,
5990 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5991 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005992 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005993 }
5994 }
5995
5996 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005997 public void notifyAppTransitionStarting(SparseIntArray reasons,
5998 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005999 synchronized (mGlobalLock) {
6000 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6001 reasons, timestamp);
6002 }
6003 }
6004
6005 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006006 public void notifySingleTaskDisplayDrawn(int displayId) {
6007 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6008 }
6009
6010 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006011 public void notifyAppTransitionFinished() {
6012 synchronized (mGlobalLock) {
6013 mStackSupervisor.notifyAppTransitionDone();
6014 }
6015 }
6016
6017 @Override
6018 public void notifyAppTransitionCancelled() {
6019 synchronized (mGlobalLock) {
6020 mStackSupervisor.notifyAppTransitionDone();
6021 }
6022 }
6023
6024 @Override
6025 public List<IBinder> getTopVisibleActivities() {
6026 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006027 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006028 }
6029 }
6030
6031 @Override
6032 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6033 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006034 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006035 }
6036 }
6037
6038 @Override
6039 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6040 Bundle bOptions) {
6041 Preconditions.checkNotNull(intents, "intents");
6042 final String[] resolvedTypes = new String[intents.length];
6043
6044 // UID of the package on user userId.
6045 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6046 // packageUid may not be initialized.
6047 int packageUid = 0;
6048 final long ident = Binder.clearCallingIdentity();
6049
6050 try {
6051 for (int i = 0; i < intents.length; i++) {
6052 resolvedTypes[i] =
6053 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6054 }
6055
6056 packageUid = AppGlobals.getPackageManager().getPackageUid(
6057 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6058 } catch (RemoteException e) {
6059 // Shouldn't happen.
6060 } finally {
6061 Binder.restoreCallingIdentity(ident);
6062 }
6063
Riddle Hsu591bf612019-02-14 17:55:31 +08006064 return getActivityStartController().startActivitiesInPackage(
6065 packageUid, packageName,
6066 intents, resolvedTypes, null /* resultTo */,
6067 SafeActivityOptions.fromBundle(bOptions), userId,
6068 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6069 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 }
6071
6072 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006073 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6074 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6075 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6076 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006077 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006078 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006079 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6080 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6081 userId, validateIncomingUser, originatingPendingIntent,
6082 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006083 }
6084 }
6085
6086 @Override
6087 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6088 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6089 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6090 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006091 PendingIntentRecord originatingPendingIntent,
6092 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006093 synchronized (mGlobalLock) {
6094 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6095 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6096 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006097 validateIncomingUser, originatingPendingIntent,
6098 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006099 }
6100 }
6101
6102 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6104 Intent intent, Bundle options, int userId) {
6105 return ActivityTaskManagerService.this.startActivityAsUser(
6106 caller, callerPacakge, intent,
6107 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6108 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6109 false /*validateIncomingUser*/);
6110 }
6111
6112 @Override
lumark588a3e82018-07-20 18:53:54 +08006113 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 synchronized (mGlobalLock) {
6115
6116 // We might change the visibilities here, so prepare an empty app transition which
6117 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006118 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006119 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006120 if (activityDisplay == null) {
6121 return;
6122 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006123 final DisplayContent dc = activityDisplay.mDisplayContent;
6124 final boolean wasTransitionSet =
6125 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006126 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006127 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006129 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130
6131 // If there was a transition set already we don't want to interfere with it as we
6132 // might be starting it too early.
6133 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006134 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137 if (callback != null) {
6138 callback.run();
6139 }
6140 }
6141
6142 @Override
6143 public void notifyKeyguardTrustedChanged() {
6144 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006145 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006146 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006147 }
6148 }
6149 }
6150
6151 /**
6152 * Called after virtual display Id is updated by
6153 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6154 * {@param vrVr2dDisplayId}.
6155 */
6156 @Override
6157 public void setVr2dDisplayId(int vr2dDisplayId) {
6158 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6159 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006160 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162 }
6163
6164 @Override
6165 public void setFocusedActivity(IBinder token) {
6166 synchronized (mGlobalLock) {
6167 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6168 if (r == null) {
6169 throw new IllegalArgumentException(
6170 "setFocusedActivity: No activity record matching token=" + token);
6171 }
Louis Chang19443452018-10-09 12:10:21 +08006172 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006173 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175 }
6176 }
6177
6178 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006180 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182
6183 @Override
6184 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006185 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187
6188 @Override
6189 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006190 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 }
6192
6193 @Override
6194 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6195 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6196 }
6197
6198 @Override
6199 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006200 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006202
6203 @Override
6204 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6205 synchronized (mGlobalLock) {
6206 mActiveVoiceInteractionServiceComponent = component;
6207 }
6208 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006209
6210 @Override
6211 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6212 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6213 return;
6214 }
6215 synchronized (mGlobalLock) {
6216 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6217 if (types == null) {
6218 if (uid < 0) {
6219 return;
6220 }
6221 types = new ArrayMap<>();
6222 mAllowAppSwitchUids.put(userId, types);
6223 }
6224 if (uid < 0) {
6225 types.remove(type);
6226 } else {
6227 types.put(type, uid);
6228 }
6229 }
6230 }
6231
6232 @Override
6233 public void onUserStopped(int userId) {
6234 synchronized (mGlobalLock) {
6235 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6236 mAllowAppSwitchUids.remove(userId);
6237 }
6238 }
6239
6240 @Override
6241 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6242 synchronized (mGlobalLock) {
6243 return ActivityTaskManagerService.this.isGetTasksAllowed(
6244 caller, callingPid, callingUid);
6245 }
6246 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006247
Riddle Hsua0536432019-02-16 00:38:59 +08006248 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006249 @Override
6250 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006251 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 mProcessNames.put(proc.mName, proc.mUid, proc);
6253 }
6254 }
6255
Riddle Hsua0536432019-02-16 00:38:59 +08006256 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006257 @Override
6258 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006259 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006260 mProcessNames.remove(name, uid);
6261 }
6262 }
6263
Riddle Hsua0536432019-02-16 00:38:59 +08006264 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006265 @Override
6266 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006267 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006268 if (proc == mHomeProcess) {
6269 mHomeProcess = null;
6270 }
6271 if (proc == mPreviousProcess) {
6272 mPreviousProcess = null;
6273 }
6274 }
6275 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006276
Riddle Hsua0536432019-02-16 00:38:59 +08006277 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006278 @Override
6279 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006280 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006281 return mTopProcessState;
6282 }
6283 }
6284
Riddle Hsua0536432019-02-16 00:38:59 +08006285 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006286 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006288 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006289 return proc == mHeavyWeightProcess;
6290 }
6291 }
6292
Riddle Hsua0536432019-02-16 00:38:59 +08006293 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006294 @Override
6295 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006296 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006297 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6298 }
6299 }
6300
6301 @Override
6302 public void finishHeavyWeightApp() {
6303 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006304 if (mHeavyWeightProcess != null) {
6305 mHeavyWeightProcess.finishActivities();
6306 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006307 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6308 mHeavyWeightProcess);
6309 }
6310 }
6311
Riddle Hsua0536432019-02-16 00:38:59 +08006312 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006313 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006314 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006315 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006316 return isSleepingLocked();
6317 }
6318 }
6319
6320 @Override
6321 public boolean isShuttingDown() {
6322 synchronized (mGlobalLock) {
6323 return mShuttingDown;
6324 }
6325 }
6326
6327 @Override
6328 public boolean shuttingDown(boolean booted, int timeout) {
6329 synchronized (mGlobalLock) {
6330 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006331 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006332 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006333 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006334 return mStackSupervisor.shutdownLocked(timeout);
6335 }
6336 }
6337
6338 @Override
6339 public void enableScreenAfterBoot(boolean booted) {
6340 synchronized (mGlobalLock) {
6341 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6342 SystemClock.uptimeMillis());
6343 mWindowManager.enableScreenAfterBoot();
6344 updateEventDispatchingLocked(booted);
6345 }
6346 }
6347
6348 @Override
6349 public boolean showStrictModeViolationDialog() {
6350 synchronized (mGlobalLock) {
6351 return mShowDialogs && !mSleeping && !mShuttingDown;
6352 }
6353 }
6354
6355 @Override
6356 public void showSystemReadyErrorDialogsIfNeeded() {
6357 synchronized (mGlobalLock) {
6358 try {
6359 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6360 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6361 + " data partition or your device will be unstable.");
6362 mUiHandler.post(() -> {
6363 if (mShowDialogs) {
6364 AlertDialog d = new BaseErrorDialog(mUiContext);
6365 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6366 d.setCancelable(false);
6367 d.setTitle(mUiContext.getText(R.string.android_system_label));
6368 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6369 d.setButton(DialogInterface.BUTTON_POSITIVE,
6370 mUiContext.getText(R.string.ok),
6371 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6372 d.show();
6373 }
6374 });
6375 }
6376 } catch (RemoteException e) {
6377 }
6378
6379 if (!Build.isBuildConsistent()) {
6380 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6381 mUiHandler.post(() -> {
6382 if (mShowDialogs) {
6383 AlertDialog d = new BaseErrorDialog(mUiContext);
6384 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6385 d.setCancelable(false);
6386 d.setTitle(mUiContext.getText(R.string.android_system_label));
6387 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6388 d.setButton(DialogInterface.BUTTON_POSITIVE,
6389 mUiContext.getText(R.string.ok),
6390 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6391 d.show();
6392 }
6393 });
6394 }
6395 }
6396 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006397
6398 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006399 public void onProcessMapped(int pid, WindowProcessController proc) {
6400 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006401 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006402 }
6403 }
6404
6405 @Override
6406 public void onProcessUnMapped(int pid) {
6407 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006408 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006409 }
6410 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006411
6412 @Override
6413 public void onPackageDataCleared(String name) {
6414 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006415 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006416 mAppWarnings.onPackageDataCleared(name);
6417 }
6418 }
6419
6420 @Override
6421 public void onPackageUninstalled(String name) {
6422 synchronized (mGlobalLock) {
6423 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006424 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006425 }
6426 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006427
6428 @Override
6429 public void onPackageAdded(String name, boolean replacing) {
6430 synchronized (mGlobalLock) {
6431 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6432 }
6433 }
6434
6435 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006436 public void onPackageReplaced(ApplicationInfo aInfo) {
6437 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006438 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006439 }
6440 }
6441
6442 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6444 synchronized (mGlobalLock) {
6445 return compatibilityInfoForPackageLocked(ai);
6446 }
6447 }
6448
Yunfan Chen75157d72018-07-27 14:47:21 +09006449 /**
6450 * Set the corresponding display information for the process global configuration. To be
6451 * called when we need to show IME on a different display.
6452 *
6453 * @param pid The process id associated with the IME window.
6454 * @param displayId The ID of the display showing the IME.
6455 */
6456 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006457 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006458 // Don't update process-level configuration for Multi-Client IME process since other
6459 // IMEs on other displays will also receive this configuration change due to IME
6460 // services use the same application config/context.
6461 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006462
Yunfan Chen75157d72018-07-27 14:47:21 +09006463 if (pid == MY_PID || pid < 0) {
6464 if (DEBUG_CONFIGURATION) {
6465 Slog.w(TAG,
6466 "Trying to update display configuration for system/invalid process.");
6467 }
6468 return;
6469 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006470 synchronized (mGlobalLock) {
6471 final ActivityDisplay activityDisplay =
6472 mRootActivityContainer.getActivityDisplay(displayId);
6473 if (activityDisplay == null) {
6474 // Call might come when display is not yet added or has been removed.
6475 if (DEBUG_CONFIGURATION) {
6476 Slog.w(TAG, "Trying to update display configuration for non-existing "
6477 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006478 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006479 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006480 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006481 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006482 if (process == null) {
6483 if (DEBUG_CONFIGURATION) {
6484 Slog.w(TAG, "Trying to update display configuration for invalid "
6485 + "process, pid=" + pid);
6486 }
6487 return;
6488 }
lumarkddc77fb2019-06-27 22:22:23 +08006489 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006490 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6491 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006492 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006493
6494 @Override
6495 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006496 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006497 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006498 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6499 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006500 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006501 }
6502 }
6503 }
6504
6505 @Override
6506 public void clearPendingResultForActivity(IBinder activityToken,
6507 WeakReference<PendingIntentRecord> pir) {
6508 synchronized (mGlobalLock) {
6509 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6510 if (r != null && r.pendingResults != null) {
6511 r.pendingResults.remove(pir);
6512 }
6513 }
6514 }
6515
6516 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006517 public ActivityTokens getTopActivityForTask(int taskId) {
6518 synchronized (mGlobalLock) {
6519 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6520 if (taskRecord == null) {
6521 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6522 + " Requested task not found");
6523 return null;
6524 }
6525 final ActivityRecord activity = taskRecord.getTopActivity();
6526 if (activity == null) {
6527 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6528 + " Requested activity not found");
6529 return null;
6530 }
6531 if (!activity.attachedToProcess()) {
6532 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6533 + activity);
6534 return null;
6535 }
6536 return new ActivityTokens(activity.appToken, activity.assistToken,
6537 activity.app.getThread());
6538 }
6539 }
6540
6541 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006542 public IIntentSender getIntentSender(int type, String packageName,
6543 int callingUid, int userId, IBinder token, String resultWho,
6544 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6545 Bundle bOptions) {
6546 synchronized (mGlobalLock) {
6547 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6548 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6549 }
6550 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006551
6552 @Override
6553 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6554 synchronized (mGlobalLock) {
6555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6556 if (r == null) {
6557 return null;
6558 }
6559 if (r.mServiceConnectionsHolder == null) {
6560 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6561 ActivityTaskManagerService.this, r);
6562 }
6563
6564 return r.mServiceConnectionsHolder;
6565 }
6566 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006567
6568 @Override
6569 public Intent getHomeIntent() {
6570 synchronized (mGlobalLock) {
6571 return ActivityTaskManagerService.this.getHomeIntent();
6572 }
6573 }
6574
6575 @Override
6576 public boolean startHomeActivity(int userId, String reason) {
6577 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006578 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006579 }
6580 }
6581
6582 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006583 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006584 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006585 synchronized (mGlobalLock) {
6586 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006587 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006588 }
Chilun8b1f1be2019-03-13 17:14:36 +08006589 }
6590
6591 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006592 public boolean startHomeOnAllDisplays(int userId, String reason) {
6593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006594 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006595 }
6596 }
6597
Riddle Hsua0536432019-02-16 00:38:59 +08006598 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006599 @Override
6600 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006601 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006602 if (mFactoryTest == FACTORY_TEST_OFF) {
6603 return false;
6604 }
6605 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6606 && wpc.mName.equals(mTopComponent.getPackageName())) {
6607 return true;
6608 }
6609 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6610 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6611 }
6612 }
6613
6614 @Override
6615 public void updateTopComponentForFactoryTest() {
6616 synchronized (mGlobalLock) {
6617 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6618 return;
6619 }
6620 final ResolveInfo ri = mContext.getPackageManager()
6621 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6622 final CharSequence errorMsg;
6623 if (ri != null) {
6624 final ActivityInfo ai = ri.activityInfo;
6625 final ApplicationInfo app = ai.applicationInfo;
6626 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6627 mTopAction = Intent.ACTION_FACTORY_TEST;
6628 mTopData = null;
6629 mTopComponent = new ComponentName(app.packageName, ai.name);
6630 errorMsg = null;
6631 } else {
6632 errorMsg = mContext.getResources().getText(
6633 com.android.internal.R.string.factorytest_not_system);
6634 }
6635 } else {
6636 errorMsg = mContext.getResources().getText(
6637 com.android.internal.R.string.factorytest_no_action);
6638 }
6639 if (errorMsg == null) {
6640 return;
6641 }
6642
6643 mTopAction = null;
6644 mTopData = null;
6645 mTopComponent = null;
6646 mUiHandler.post(() -> {
6647 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6648 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006649 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006650 });
6651 }
6652 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006653
Riddle Hsua0536432019-02-16 00:38:59 +08006654 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006655 @Override
6656 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6657 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006658 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006659 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006660 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006661
6662 wpc.clearRecentTasks();
6663 wpc.clearActivities();
6664
6665 if (wpc.isInstrumenting()) {
6666 finishInstrumentationCallback.run();
6667 }
6668
Jorim Jaggid0752812018-10-16 16:07:20 +02006669 if (!restarting && hasVisibleActivities) {
6670 mWindowManager.deferSurfaceLayout();
6671 try {
6672 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6673 // If there was nothing to resume, and we are not already restarting
6674 // this process, but there is a visible activity that is hosted by the
6675 // process...then make sure all visible activities are running, taking
6676 // care of restarting this process.
6677 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6678 !PRESERVE_WINDOWS);
6679 }
6680 } finally {
6681 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006682 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 }
6684 }
6685 }
6686
6687 @Override
6688 public void closeSystemDialogs(String reason) {
6689 enforceNotIsolatedCaller("closeSystemDialogs");
6690
6691 final int pid = Binder.getCallingPid();
6692 final int uid = Binder.getCallingUid();
6693 final long origId = Binder.clearCallingIdentity();
6694 try {
6695 synchronized (mGlobalLock) {
6696 // Only allow this from foreground processes, so that background
6697 // applications can't abuse it to prevent system UI from being shown.
6698 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006699 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006700 if (!proc.isPerceptible()) {
6701 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6702 + " from background process " + proc);
6703 return;
6704 }
6705 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 mWindowManager.closeSystemDialogs(reason);
6707
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006710 // Call into AM outside the synchronized block.
6711 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712 } finally {
6713 Binder.restoreCallingIdentity(origId);
6714 }
6715 }
6716
6717 @Override
6718 public void cleanupDisabledPackageComponents(
6719 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6720 synchronized (mGlobalLock) {
6721 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006722 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006724 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006725 mStackSupervisor.scheduleIdleLocked();
6726 }
6727
6728 // Clean-up disabled tasks
6729 getRecentTasks().cleanupDisabledPackageTasksLocked(
6730 packageName, disabledClasses, userId);
6731 }
6732 }
6733
6734 @Override
6735 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6736 int userId) {
6737 synchronized (mGlobalLock) {
6738
6739 boolean didSomething =
6740 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006741 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 null, doit, evenPersistent, userId);
6743 return didSomething;
6744 }
6745 }
6746
6747 @Override
6748 public void resumeTopActivities(boolean scheduleIdle) {
6749 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006750 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 if (scheduleIdle) {
6752 mStackSupervisor.scheduleIdleLocked();
6753 }
6754 }
6755 }
6756
Riddle Hsua0536432019-02-16 00:38:59 +08006757 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 @Override
6759 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006760 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6762 }
6763 }
6764
Riddle Hsua0536432019-02-16 00:38:59 +08006765 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766 @Override
6767 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006768 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006769 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 }
6771 }
6772
6773 @Override
6774 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6775 try {
6776 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6777 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6778 }
6779 } catch (RemoteException ex) {
6780 throw new SecurityException("Fail to check is caller a privileged app", ex);
6781 }
6782
6783 synchronized (mGlobalLock) {
6784 final long ident = Binder.clearCallingIdentity();
6785 try {
6786 if (mAmInternal.shouldConfirmCredentials(userId)) {
6787 if (mKeyguardController.isKeyguardLocked()) {
6788 // Showing launcher to avoid user entering credential twice.
6789 startHomeActivity(currentUserId, "notifyLockedProfile");
6790 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006791 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 }
6793 } finally {
6794 Binder.restoreCallingIdentity(ident);
6795 }
6796 }
6797 }
6798
6799 @Override
6800 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6801 mAmInternal.enforceCallingPermission(
6802 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6803
6804 synchronized (mGlobalLock) {
6805 final long ident = Binder.clearCallingIdentity();
6806 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006807 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6808 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6811 UserHandle.CURRENT);
6812 } finally {
6813 Binder.restoreCallingIdentity(ident);
6814 }
6815 }
6816 }
6817
6818 @Override
6819 public void writeActivitiesToProto(ProtoOutputStream proto) {
6820 synchronized (mGlobalLock) {
6821 // The output proto of "activity --proto activities"
6822 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006823 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006824 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6825 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 }
6827 }
6828
6829 @Override
6830 public void saveANRState(String reason) {
6831 synchronized (mGlobalLock) {
6832 final StringWriter sw = new StringWriter();
6833 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6834 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6835 if (reason != null) {
6836 pw.println(" Reason: " + reason);
6837 }
6838 pw.println();
6839 getActivityStartController().dump(pw, " ", null);
6840 pw.println();
6841 pw.println("-------------------------------------------------------------------------------");
6842 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6843 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6844 "" /* header */);
6845 pw.println();
6846 pw.close();
6847
6848 mLastANRState = sw.toString();
6849 }
6850 }
6851
6852 @Override
6853 public void clearSavedANRState() {
6854 synchronized (mGlobalLock) {
6855 mLastANRState = null;
6856 }
6857 }
6858
6859 @Override
6860 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6861 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6862 synchronized (mGlobalLock) {
6863 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6864 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6865 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6866 dumpLastANRLocked(pw);
6867 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6868 dumpLastANRTracesLocked(pw);
6869 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6870 dumpActivityStarterLocked(pw, dumpPackage);
6871 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6872 dumpActivityContainersLocked(pw);
6873 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6874 if (getRecentTasks() != null) {
6875 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6876 }
6877 }
6878 }
6879 }
6880
6881 @Override
6882 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6883 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6884 int wakefulness) {
6885 synchronized (mGlobalLock) {
6886 if (mHomeProcess != null && (dumpPackage == null
6887 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6888 if (needSep) {
6889 pw.println();
6890 needSep = false;
6891 }
6892 pw.println(" mHomeProcess: " + mHomeProcess);
6893 }
6894 if (mPreviousProcess != null && (dumpPackage == null
6895 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6896 if (needSep) {
6897 pw.println();
6898 needSep = false;
6899 }
6900 pw.println(" mPreviousProcess: " + mPreviousProcess);
6901 }
6902 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6903 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6904 StringBuilder sb = new StringBuilder(128);
6905 sb.append(" mPreviousProcessVisibleTime: ");
6906 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6907 pw.println(sb);
6908 }
6909 if (mHeavyWeightProcess != null && (dumpPackage == null
6910 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6911 if (needSep) {
6912 pw.println();
6913 needSep = false;
6914 }
6915 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6916 }
6917 if (dumpPackage == null) {
6918 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006919 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 if (dumpAll) {
6922 if (dumpPackage == null) {
6923 pw.println(" mConfigWillChange: "
6924 + getTopDisplayFocusedStack().mConfigWillChange);
6925 }
6926 if (mCompatModePackages.getPackages().size() > 0) {
6927 boolean printed = false;
6928 for (Map.Entry<String, Integer> entry
6929 : mCompatModePackages.getPackages().entrySet()) {
6930 String pkg = entry.getKey();
6931 int mode = entry.getValue();
6932 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6933 continue;
6934 }
6935 if (!printed) {
6936 pw.println(" mScreenCompatPackages:");
6937 printed = true;
6938 }
6939 pw.println(" " + pkg + ": " + mode);
6940 }
6941 }
6942 }
6943
6944 if (dumpPackage == null) {
6945 pw.println(" mWakefulness="
6946 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006947 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006948 if (mRunningVoice != null) {
6949 pw.println(" mRunningVoice=" + mRunningVoice);
6950 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6951 }
6952 pw.println(" mSleeping=" + mSleeping);
6953 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6954 pw.println(" mVrController=" + mVrController);
6955 }
6956 if (mCurAppTimeTracker != null) {
6957 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6958 }
6959 if (mAllowAppSwitchUids.size() > 0) {
6960 boolean printed = false;
6961 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6962 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6963 for (int j = 0; j < types.size(); j++) {
6964 if (dumpPackage == null ||
6965 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6966 if (needSep) {
6967 pw.println();
6968 needSep = false;
6969 }
6970 if (!printed) {
6971 pw.println(" mAllowAppSwitchUids:");
6972 printed = true;
6973 }
6974 pw.print(" User ");
6975 pw.print(mAllowAppSwitchUids.keyAt(i));
6976 pw.print(": Type ");
6977 pw.print(types.keyAt(j));
6978 pw.print(" = ");
6979 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6980 pw.println();
6981 }
6982 }
6983 }
6984 }
6985 if (dumpPackage == null) {
6986 if (mController != null) {
6987 pw.println(" mController=" + mController
6988 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6989 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006990 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6991 pw.println(" mLaunchingActivityWakeLock="
6992 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006993 }
6994
6995 return needSep;
6996 }
6997 }
6998
6999 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007000 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7001 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007002 synchronized (mGlobalLock) {
7003 if (dumpPackage == null) {
7004 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7005 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007006 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7007 if (mRunningVoice != null) {
7008 final long vrToken = proto.start(
7009 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7010 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7011 mRunningVoice.toString());
7012 mVoiceWakeLock.writeToProto(
7013 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7014 proto.end(vrToken);
7015 }
7016 mVrController.writeToProto(proto,
7017 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007018 if (mController != null) {
7019 final long token = proto.start(CONTROLLER);
7020 proto.write(CONTROLLER, mController.toString());
7021 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7022 proto.end(token);
7023 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007024 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7025 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7026 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 }
7028
7029 if (mHomeProcess != null && (dumpPackage == null
7030 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007031 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007032 }
7033
7034 if (mPreviousProcess != null && (dumpPackage == null
7035 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007036 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007037 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7038 }
7039
7040 if (mHeavyWeightProcess != null && (dumpPackage == null
7041 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007042 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 }
7044
7045 for (Map.Entry<String, Integer> entry
7046 : mCompatModePackages.getPackages().entrySet()) {
7047 String pkg = entry.getKey();
7048 int mode = entry.getValue();
7049 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7050 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7051 proto.write(PACKAGE, pkg);
7052 proto.write(MODE, mode);
7053 proto.end(compatToken);
7054 }
7055 }
7056
7057 if (mCurAppTimeTracker != null) {
7058 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7059 }
7060
7061 }
7062 }
7063
7064 @Override
7065 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7066 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7067 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007068 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7069 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007070 }
7071
7072 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007073 public void dumpForOom(PrintWriter pw) {
7074 synchronized (mGlobalLock) {
7075 pw.println(" mHomeProcess: " + mHomeProcess);
7076 pw.println(" mPreviousProcess: " + mPreviousProcess);
7077 if (mHeavyWeightProcess != null) {
7078 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7079 }
7080 }
7081 }
7082
7083 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 public boolean canGcNow() {
7085 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007086 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 }
7088 }
7089
Riddle Hsua0536432019-02-16 00:38:59 +08007090 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007091 @Override
7092 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007093 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007094 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007095 return top != null ? top.app : null;
7096 }
7097 }
7098
Riddle Hsua0536432019-02-16 00:38:59 +08007099 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 @Override
7101 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007102 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007103 if (mRootActivityContainer != null) {
7104 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 }
7106 }
7107 }
7108
7109 @Override
7110 public void scheduleDestroyAllActivities(String reason) {
7111 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007112 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114 }
7115
7116 @Override
7117 public void removeUser(int userId) {
7118 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007119 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 }
7121 }
7122
7123 @Override
7124 public boolean switchUser(int userId, UserState userState) {
7125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128 }
7129
7130 @Override
7131 public void onHandleAppCrash(WindowProcessController wpc) {
7132 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007133 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 }
7135 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007136
7137 @Override
7138 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007140 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007141 }
7142 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007143
Riddle Hsua0536432019-02-16 00:38:59 +08007144 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007145 @Override
7146 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007147 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007148 }
7149
Riddle Hsua0536432019-02-16 00:38:59 +08007150 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007151 @Override
7152 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007153 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007154 }
7155
Riddle Hsua0536432019-02-16 00:38:59 +08007156 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007157 @Override
7158 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007159 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007160 }
7161
Riddle Hsua0536432019-02-16 00:38:59 +08007162 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007163 @Override
7164 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007165 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007166 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007167
7168 @Override
7169 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007170 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007171 mPendingTempWhitelist.put(uid, tag);
7172 }
7173 }
7174
7175 @Override
7176 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007177 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007178 mPendingTempWhitelist.remove(uid);
7179 }
7180 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007181
7182 @Override
7183 public boolean handleAppCrashInActivityController(String processName, int pid,
7184 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7185 Runnable killCrashingAppCallback) {
7186 synchronized (mGlobalLock) {
7187 if (mController == null) {
7188 return false;
7189 }
7190
7191 try {
7192 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7193 stackTrace)) {
7194 killCrashingAppCallback.run();
7195 return true;
7196 }
7197 } catch (RemoteException e) {
7198 mController = null;
7199 Watchdog.getInstance().setActivityController(null);
7200 }
7201 return false;
7202 }
7203 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007204
7205 @Override
7206 public void removeRecentTasksByPackageName(String packageName, int userId) {
7207 synchronized (mGlobalLock) {
7208 mRecentTasks.removeTasksByPackageName(packageName, userId);
7209 }
7210 }
7211
7212 @Override
7213 public void cleanupRecentTasksForUser(int userId) {
7214 synchronized (mGlobalLock) {
7215 mRecentTasks.cleanupLocked(userId);
7216 }
7217 }
7218
7219 @Override
7220 public void loadRecentTasksForUser(int userId) {
7221 synchronized (mGlobalLock) {
7222 mRecentTasks.loadUserRecentsLocked(userId);
7223 }
7224 }
7225
7226 @Override
7227 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7228 synchronized (mGlobalLock) {
7229 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7230 }
7231 }
7232
7233 @Override
7234 public void flushRecentTasks() {
7235 mRecentTasks.flush();
7236 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007237
7238 @Override
7239 public WindowProcessController getHomeProcess() {
7240 synchronized (mGlobalLock) {
7241 return mHomeProcess;
7242 }
7243 }
7244
7245 @Override
7246 public WindowProcessController getPreviousProcess() {
7247 synchronized (mGlobalLock) {
7248 return mPreviousProcess;
7249 }
7250 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007251
7252 @Override
7253 public void clearLockedTasks(String reason) {
7254 synchronized (mGlobalLock) {
7255 getLockTaskController().clearLockedTasks(reason);
7256 }
7257 }
7258
7259 @Override
7260 public void updateUserConfiguration() {
7261 synchronized (mGlobalLock) {
7262 final Configuration configuration = new Configuration(getGlobalConfiguration());
7263 final int currentUserId = mAmInternal.getCurrentUserId();
7264 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7265 configuration, currentUserId, Settings.System.canWrite(mContext));
7266 updateConfigurationLocked(configuration, null /* starting */,
7267 false /* initLocale */, false /* persistent */, currentUserId,
7268 false /* deferResume */);
7269 }
7270 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007271
7272 @Override
7273 public boolean canShowErrorDialogs() {
7274 synchronized (mGlobalLock) {
7275 return mShowDialogs && !mSleeping && !mShuttingDown
7276 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7277 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7278 mAmInternal.getCurrentUserId())
7279 && !(UserManager.isDeviceInDemoMode(mContext)
7280 && mAmInternal.getCurrentUser().isDemo());
7281 }
7282 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007283
7284 @Override
7285 public void setProfileApp(String profileApp) {
7286 synchronized (mGlobalLock) {
7287 mProfileApp = profileApp;
7288 }
7289 }
7290
7291 @Override
7292 public void setProfileProc(WindowProcessController wpc) {
7293 synchronized (mGlobalLock) {
7294 mProfileProc = wpc;
7295 }
7296 }
7297
7298 @Override
7299 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7300 synchronized (mGlobalLock) {
7301 mProfilerInfo = profilerInfo;
7302 }
7303 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007304
7305 @Override
7306 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7307 synchronized (mGlobalLock) {
7308 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7309 }
7310 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007311
7312 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007313 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7314 boolean reducedResolution) {
7315 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7316 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007317 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007318
7319 @Override
7320 public boolean isUidForeground(int uid) {
7321 synchronized (mGlobalLock) {
7322 return ActivityTaskManagerService.this.isUidForeground(uid);
7323 }
7324 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007325
7326 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007327 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007328 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007329 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007330 }
7331 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007332
7333 @Override
7334 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007335 // Translate package names into UIDs
7336 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007337 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007338 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7339 if (uid >= 0) {
7340 result.add(uid);
7341 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007342 }
7343 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007344 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007345 }
7346 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007347 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007348}