blob: 3c5dd6c1fcc36831a14c63343647a71d6e46e353 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import 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;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900216import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.telecom.TelecomManager;
218import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100219import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700221import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700223import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700250import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
261import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900268import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700295import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
299import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
301/**
302 * System service for managing activities and their containers (task, stacks, displays,... ).
303 *
304 * {@hide}
305 */
306public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800379 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700380 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700381 private UserManagerService mUserManager;
382 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700383 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800384 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700385 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** All processes currently running that might have a window organized by name. */
387 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100388 /** All processes we currently have running mapped by pid and uid */
389 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** This is the process holding what we currently consider to be the "home" activity. */
391 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700392 /** The currently running heavy-weight process, if any. */
393 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700394 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /**
396 * This is the process holding the activity the user last visited that is in a different process
397 * from the one they are currently in.
398 */
399 WindowProcessController mPreviousProcess;
400 /** The time at which the previous process was last visible. */
401 long mPreviousProcessVisibleTime;
402
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700403 /** List of intents that were used to start the most recent tasks. */
404 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700405 /** State of external calls telling us if the device is awake or asleep. */
406 private boolean mKeyguardShown = false;
407
408 // Wrapper around VoiceInteractionServiceManager
409 private AssistUtils mAssistUtils;
410
411 // VoiceInteraction session ID that changes for each new request except when
412 // being called for multi-window assist in a single session.
413 private int mViSessionId = 1000;
414
415 // How long to wait in getAssistContextExtras for the activity and foreground services
416 // to respond with the result.
417 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
418
419 // How long top wait when going through the modern assist (which doesn't need to block
420 // on getting this result before starting to launch its UI).
421 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
422
423 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
424 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
425
Alison Cichowlas3e340502018-08-07 17:15:01 -0400426 // Permission tokens are used to temporarily granted a trusted app the ability to call
427 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
428 // showing any appropriate error messages to the user.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
430 10 * MINUTE_IN_MILLIS;
431
432 // How long before the service actually expires a token. This is slightly longer than
433 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
434 // expiration exception.
435 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
436 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
437
438 // How long the service will remember expired tokens, for the purpose of providing error
439 // messaging when a client uses an expired token.
440 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
441 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
442
443 // Activity tokens of system activities that are delegating their call to
444 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
445 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
446
447 // Permission tokens that have expired, but we remember for error reporting.
448 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700450 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
451
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 // Keeps track of the active voice interaction service component, notified from
453 // VoiceInteractionManagerService
454 ComponentName mActiveVoiceInteractionServiceComponent;
455
Michal Karpinskida34cd42019-04-02 19:46:52 +0100456 // A map userId and all its companion app uids
457 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000458
Wale Ogunwalee2172292018-10-25 10:11:10 -0700459 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460 KeyguardController mKeyguardController;
461 private final ClientLifecycleManager mLifecycleManager;
462 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700463 /** The controller for all operations related to locktask. */
464 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700465 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 boolean mSuppressResizeConfigChanges;
468
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700469 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 new UpdateConfigurationResult();
471
472 static final class UpdateConfigurationResult {
473 // Configuration changes that were updated.
474 int changes;
475 // If the activity was relaunched to match the new configuration.
476 boolean activityRelaunched;
477
478 void reset() {
479 changes = 0;
480 activityRelaunched = false;
481 }
482 }
483
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private int mConfigurationSeq;
486 // To cache the list of supported system locales
487 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700488
489 /**
490 * Temp object used when global and/or display override configuration is updated. It is also
491 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
492 * anyone...
493 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 private Configuration mTempConfig = new Configuration();
495
Wale Ogunwalef6733932018-06-27 05:14:34 -0700496 /** Temporary to avoid allocations. */
497 final StringBuilder mStringBuilder = new StringBuilder(256);
498
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 // Amount of time after a call to stopAppSwitches() during which we will
500 // prevent further untrusted switches from happening.
501 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
502
503 /**
504 * The time at which we will allow normal application switches again,
505 * after a call to {@link #stopAppSwitches()}.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
509 * This is set to true after the first switch after mAppSwitchesAllowedTime
510 * is set; any switches after that will clear the time.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
Ricky Wai906af482019-06-03 17:25:28 +0100514 /**
515 * Last stop app switches time, apps finished before this time cannot start background activity
516 * even if they are in grace period.
517 */
518 private long mLastStopAppSwitchesTime;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 IActivityController mController = null;
521 boolean mControllerIsAMonkey = false;
522
Wale Ogunwale214f3482018-10-04 11:00:47 -0700523 final int mFactoryTest;
524
525 /** Used to control how we initialize the service. */
526 ComponentName mTopComponent;
527 String mTopAction = Intent.ACTION_MAIN;
528 String mTopData;
529
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800530 /** Profiling app information. */
531 String mProfileApp = null;
532 WindowProcessController mProfileProc = null;
533 ProfilerInfo mProfilerInfo = null;
534
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700536 * Dump of the activity state at the time of the last ANR. Cleared after
537 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
538 */
539 String mLastANRState;
540
541 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542 * Used to retain an update lock when the foreground activity is in
543 * immersive mode.
544 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700545 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546
547 /**
548 * Packages that are being allowed to perform unrestricted app switches. Mapping is
549 * User -> Type -> uid.
550 */
551 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
552
553 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700554 private int mThumbnailWidth;
555 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700556
557 /**
558 * Flag that indicates if multi-window is enabled.
559 *
560 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
561 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
562 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
563 * At least one of the forms of multi-window must be enabled in order for this flag to be
564 * initialized to 'true'.
565 *
566 * @see #mSupportsSplitScreenMultiWindow
567 * @see #mSupportsFreeformWindowManagement
568 * @see #mSupportsPictureInPicture
569 * @see #mSupportsMultiDisplay
570 */
571 boolean mSupportsMultiWindow;
572 boolean mSupportsSplitScreenMultiWindow;
573 boolean mSupportsFreeformWindowManagement;
574 boolean mSupportsPictureInPicture;
575 boolean mSupportsMultiDisplay;
576 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700577 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700578
579 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
580
581 // VR Vr2d Display Id.
582 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700583
Wale Ogunwalef6733932018-06-27 05:14:34 -0700584 /**
585 * Set while we are wanting to sleep, to prevent any
586 * activities from being started/resumed.
587 *
588 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
589 *
590 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
591 * while in the sleep state until there is a pending transition out of sleep, in which case
592 * mSleeping is set to false, and remains false while awake.
593 *
594 * Whether mSleeping can quickly toggled between true/false without the device actually
595 * display changing states is undefined.
596 */
597 private boolean mSleeping = false;
598
599 /**
600 * The process state used for processes that are running the top activities.
601 * This changes between TOP and TOP_SLEEPING to following mSleeping.
602 */
603 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
604
Riddle Hsua0022cd2019-09-09 21:12:41 +0800605 @Retention(RetentionPolicy.SOURCE)
606 @IntDef({
607 LAYOUT_REASON_CONFIG_CHANGED,
608 LAYOUT_REASON_VISIBILITY_CHANGED,
609 })
610 @interface LayoutReason {}
611 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
612 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
613
614 /** The reasons to perform surface placement. */
615 @LayoutReason
616 private int mLayoutReasons;
617
Wale Ogunwalef6733932018-06-27 05:14:34 -0700618 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
619 // automatically. Important for devices without direct input devices.
620 private boolean mShowDialogs = true;
621
622 /** Set if we are shutting down the system, similar to sleeping. */
623 boolean mShuttingDown = false;
624
625 /**
626 * We want to hold a wake lock while running a voice interaction session, since
627 * this may happen with the screen off and we need to keep the CPU running to
628 * be able to continue to interact with the user.
629 */
630 PowerManager.WakeLock mVoiceWakeLock;
631
632 /**
633 * Set while we are running a voice interaction. This overrides sleeping while it is active.
634 */
635 IVoiceInteractionSession mRunningVoice;
636
637 /**
638 * The last resumed activity. This is identical to the current resumed activity most
639 * of the time but could be different when we're pausing one activity before we resume
640 * another activity.
641 */
642 ActivityRecord mLastResumedActivity;
643
644 /**
645 * The activity that is currently being traced as the active resumed activity.
646 *
647 * @see #updateResumedAppTrace
648 */
649 private @Nullable ActivityRecord mTracedResumedActivity;
650
651 /** If non-null, we are tracking the time the user spends in the currently focused app. */
652 AppTimeTracker mCurAppTimeTracker;
653
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700654 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700655
Wale Ogunwale53783742018-09-16 10:21:51 -0700656 /**
657 * Packages that the user has asked to have run in screen size
658 * compatibility mode instead of filling the screen.
659 */
660 CompatModePackages mCompatModePackages;
661
Wale Ogunwalef6733932018-06-27 05:14:34 -0700662 private FontScaleSettingObserver mFontScaleSettingObserver;
663
Ricky Wai96f5c352019-04-10 18:40:17 +0100664 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000665
Wale Ogunwalef6733932018-06-27 05:14:34 -0700666 private final class FontScaleSettingObserver extends ContentObserver {
667 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
668 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
669
670 public FontScaleSettingObserver() {
671 super(mH);
672 final ContentResolver resolver = mContext.getContentResolver();
673 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
674 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
675 UserHandle.USER_ALL);
676 }
677
678 @Override
679 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
680 if (mFontScaleUri.equals(uri)) {
681 updateFontScaleIfNeeded(userId);
682 } else if (mHideErrorDialogsUri.equals(uri)) {
683 synchronized (mGlobalLock) {
684 updateShouldShowDialogsLocked(getGlobalConfiguration());
685 }
686 }
687 }
688 }
689
Riddle Hsua0536432019-02-16 00:38:59 +0800690 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
691 @Target(ElementType.METHOD)
692 @Retention(RetentionPolicy.SOURCE)
693 @interface HotPath {
694 int NONE = 0;
695 int OOM_ADJUSTMENT = 1;
696 int LRU_UPDATE = 2;
697 int PROCESS_CHANGE = 3;
698 int caller() default NONE;
699 }
700
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800701 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
702 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900703 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800704 mAmInternal.updateOomAdj();
705 }
706 };
707
Charles Chen8d98dd22018-12-26 17:36:54 +0800708 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
709 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700710 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700711 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700712 mSystemThread = ActivityThread.currentActivityThread();
713 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700714 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800715 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700717 }
718
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700719 public void onSystemReady() {
720 synchronized (mGlobalLock) {
721 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
722 PackageManager.FEATURE_CANT_SAVE_STATE);
723 mAssistUtils = new AssistUtils(mContext);
724 mVrController.onSystemReady();
725 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700726 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onInitPowerManagement() {
731 synchronized (mGlobalLock) {
732 mStackSupervisor.initPowerManagement();
733 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
734 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
735 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
736 mVoiceWakeLock.setReferenceCounted(false);
737 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700738 }
739
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700740 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700741 mFontScaleSettingObserver = new FontScaleSettingObserver();
742 }
743
Wale Ogunwale59507092018-10-29 09:00:30 -0700744 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700745 final boolean freeformWindowManagement =
746 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
747 || Settings.Global.getInt(
748 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
749
750 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
751 final boolean supportsPictureInPicture = supportsMultiWindow &&
752 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
753 final boolean supportsSplitScreenMultiWindow =
754 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
755 final boolean supportsMultiDisplay = mContext.getPackageManager()
756 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700757 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
758 final boolean forceResizable = Settings.Global.getInt(
759 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700760 final boolean sizeCompatFreeform = Settings.Global.getInt(
761 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700762
763 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900764 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765
766 final Configuration configuration = new Configuration();
767 Settings.System.getConfiguration(resolver, configuration);
768 if (forceRtl) {
769 // This will take care of setting the correct layout direction flags
770 configuration.setLayoutDirection(configuration.locale);
771 }
772
773 synchronized (mGlobalLock) {
774 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700775 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776 final boolean multiWindowFormEnabled = freeformWindowManagement
777 || supportsSplitScreenMultiWindow
778 || supportsPictureInPicture
779 || supportsMultiDisplay;
780 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
781 mSupportsMultiWindow = true;
782 mSupportsFreeformWindowManagement = freeformWindowManagement;
783 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
784 mSupportsPictureInPicture = supportsPictureInPicture;
785 mSupportsMultiDisplay = supportsMultiDisplay;
786 } else {
787 mSupportsMultiWindow = false;
788 mSupportsFreeformWindowManagement = false;
789 mSupportsSplitScreenMultiWindow = false;
790 mSupportsPictureInPicture = false;
791 mSupportsMultiDisplay = false;
792 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700793 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700794 // This happens before any activities are started, so we can change global configuration
795 // in-place.
796 updateConfigurationLocked(configuration, null, true);
797 final Configuration globalConfig = getGlobalConfiguration();
798 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
799
800 // Load resources only after the current configuration has been set.
801 final Resources res = mContext.getResources();
802 mThumbnailWidth = res.getDimensionPixelSize(
803 com.android.internal.R.dimen.thumbnail_width);
804 mThumbnailHeight = res.getDimensionPixelSize(
805 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 }
807 }
808
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800809 public WindowManagerGlobalLock getGlobalLock() {
810 return mGlobalLock;
811 }
812
Yunfan Chen585f2932019-01-29 16:04:45 +0900813 /** For test purpose only. */
814 @VisibleForTesting
815 public ActivityTaskManagerInternal getAtmInternal() {
816 return mInternal;
817 }
818
Riddle Hsud93a6c42018-11-29 21:50:06 +0800819 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
820 Looper looper) {
821 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700824 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800825 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700826 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828
829 mTempConfig.setToDefaults();
830 mTempConfig.setLocales(LocaleList.getDefault());
831 mConfigurationSeq = mTempConfig.seq = 1;
832 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800833 mRootActivityContainer = new RootActivityContainer(this);
834 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700836 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700837 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700838 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700840 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700841 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700842 mKeyguardController = mStackSupervisor.getKeyguardController();
843 }
844
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700845 public void onActivityManagerInternalAdded() {
846 synchronized (mGlobalLock) {
847 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
848 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
849 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700850 }
851
Yunfan Chen75157d72018-07-27 14:47:21 +0900852 int increaseConfigurationSeqLocked() {
853 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
854 return mConfigurationSeq;
855 }
856
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700857 protected ActivityStackSupervisor createStackSupervisor() {
858 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
859 supervisor.initialize();
860 return supervisor;
861 }
862
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800863 protected AppWarnings createAppWarnings(
864 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
865 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
866 }
867
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700868 public void setWindowManager(WindowManagerService wm) {
869 synchronized (mGlobalLock) {
870 mWindowManager = wm;
871 mLockTaskController.setWindowManager(wm);
872 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800873 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700875 }
876
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
878 synchronized (mGlobalLock) {
879 mUsageStatsInternal = usageStatsManager;
880 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700881 }
882
Wale Ogunwalef6733932018-06-27 05:14:34 -0700883 UserManagerService getUserManager() {
884 if (mUserManager == null) {
885 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
886 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
887 }
888 return mUserManager;
889 }
890
891 AppOpsService getAppOpsService() {
892 if (mAppOpsService == null) {
893 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
894 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
895 }
896 return mAppOpsService;
897 }
898
899 boolean hasUserRestriction(String restriction, int userId) {
900 return getUserManager().hasUserRestriction(restriction, userId);
901 }
902
Michal Karpinski15486842019-04-25 17:33:42 +0100903 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
904 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700905 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100906 if (mode == AppOpsManager.MODE_DEFAULT) {
907 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
908 == PERMISSION_GRANTED;
909 }
910 return mode == AppOpsManager.MODE_ALLOWED;
911 }
912
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700913 @VisibleForTesting
914 protected void setRecentTasks(RecentTasks recentTasks) {
915 mRecentTasks = recentTasks;
916 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700917 }
918
919 RecentTasks getRecentTasks() {
920 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700923 ClientLifecycleManager getLifecycleManager() {
924 return mLifecycleManager;
925 }
926
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 ActivityStartController getActivityStartController() {
928 return mActivityStartController;
929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 TaskChangeNotificationController getTaskChangeNotificationController() {
932 return mTaskChangeNotificationController;
933 }
934
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700935 LockTaskController getLockTaskController() {
936 return mLockTaskController;
937 }
938
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 /**
940 * Return the global configuration used by the process corresponding to the input pid. This is
941 * usually the global configuration with some overrides specific to that process.
942 */
943 Configuration getGlobalConfigurationForCallingPid() {
944 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800945 return getGlobalConfigurationForPid(pid);
946 }
947
948 /**
949 * Return the global configuration used by the process corresponding to the given pid.
950 */
951 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900952 if (pid == MY_PID || pid < 0) {
953 return getGlobalConfiguration();
954 }
955 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100956 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 return app != null ? app.getConfiguration() : getGlobalConfiguration();
958 }
959 }
960
961 /**
962 * Return the device configuration info used by the process corresponding to the input pid.
963 * The value is consistent with the global configuration for the process.
964 */
965 @Override
966 public ConfigurationInfo getDeviceConfigurationInfo() {
967 ConfigurationInfo config = new ConfigurationInfo();
968 synchronized (mGlobalLock) {
969 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
970 config.reqTouchScreen = globalConfig.touchscreen;
971 config.reqKeyboardType = globalConfig.keyboard;
972 config.reqNavigation = globalConfig.navigation;
973 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
974 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
975 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
976 }
977 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
978 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
979 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
980 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700981 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900982 }
983 return config;
984 }
985
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700987 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public static final class Lifecycle extends SystemService {
991 private final ActivityTaskManagerService mService;
992
993 public Lifecycle(Context context) {
994 super(context);
995 mService = new ActivityTaskManagerService(context);
996 }
997
998 @Override
999 public void onStart() {
1000 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 }
1003
Garfield Tan891146c2018-10-09 12:14:00 -07001004 @Override
1005 public void onUnlockUser(int userId) {
1006 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001007 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001008 }
1009 }
1010
1011 @Override
1012 public void onCleanupUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
1014 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1015 }
1016 }
1017
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001018 public ActivityTaskManagerService getService() {
1019 return mService;
1020 }
1021 }
1022
1023 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 public final int startActivity(IApplicationThread caller, String callingPackage,
1025 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1026 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1027 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1028 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1029 UserHandle.getCallingUserId());
1030 }
1031
1032 @Override
1033 public final int startActivities(IApplicationThread caller, String callingPackage,
1034 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1035 int userId) {
1036 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller(reason);
1038 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001040 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1041 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1042 reason, null /* originatingPendingIntent */,
1043 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 }
1045
1046 @Override
1047 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1048 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1049 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1050 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1051 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1052 true /*validateIncomingUser*/);
1053 }
1054
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001055 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1057 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1058 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001061 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1063
1064 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .setCaller(caller)
1067 .setCallingPackage(callingPackage)
1068 .setResolvedType(resolvedType)
1069 .setResultTo(resultTo)
1070 .setResultWho(resultWho)
1071 .setRequestCode(requestCode)
1072 .setStartFlags(startFlags)
1073 .setProfilerInfo(profilerInfo)
1074 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001075 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 .execute();
1077
1078 }
1079
1080 @Override
1081 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1082 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1084 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 // Refuse possible leaked file descriptors
1086 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089
1090 if (!(target instanceof PendingIntentRecord)) {
1091 throw new IllegalArgumentException("Bad PendingIntent object");
1092 }
1093
1094 PendingIntentRecord pir = (PendingIntentRecord)target;
1095
1096 synchronized (mGlobalLock) {
1097 // If this is coming from the currently resumed activity, it is
1098 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001099 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 if (stack.mResumedActivity != null &&
1101 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001102 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 }
1104 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001105 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 }
1108
1109 @Override
1110 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1111 Bundle bOptions) {
1112 // Refuse possible leaked file descriptors
1113 if (intent != null && intent.hasFileDescriptors()) {
1114 throw new IllegalArgumentException("File descriptors passed in Intent");
1115 }
1116 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1117
1118 synchronized (mGlobalLock) {
1119 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1120 if (r == null) {
1121 SafeActivityOptions.abort(options);
1122 return false;
1123 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 // The caller is not running... d'oh!
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
1129 intent = new Intent(intent);
1130 // The caller is not allowed to change the data.
1131 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1132 // And we are resetting to find the next component...
1133 intent.setComponent(null);
1134
1135 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1136
1137 ActivityInfo aInfo = null;
1138 try {
1139 List<ResolveInfo> resolves =
1140 AppGlobals.getPackageManager().queryIntentActivities(
1141 intent, r.resolvedType,
1142 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1143 UserHandle.getCallingUserId()).getList();
1144
1145 // Look for the original activity in the list...
1146 final int N = resolves != null ? resolves.size() : 0;
1147 for (int i=0; i<N; i++) {
1148 ResolveInfo rInfo = resolves.get(i);
1149 if (rInfo.activityInfo.packageName.equals(r.packageName)
1150 && rInfo.activityInfo.name.equals(r.info.name)) {
1151 // We found the current one... the next matching is
1152 // after it.
1153 i++;
1154 if (i<N) {
1155 aInfo = resolves.get(i).activityInfo;
1156 }
1157 if (debug) {
1158 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1159 + "/" + r.info.name);
1160 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1161 ? "null" : aInfo.packageName + "/" + aInfo.name));
1162 }
1163 break;
1164 }
1165 }
1166 } catch (RemoteException e) {
1167 }
1168
1169 if (aInfo == null) {
1170 // Nobody who is next!
1171 SafeActivityOptions.abort(options);
1172 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1173 return false;
1174 }
1175
1176 intent.setComponent(new ComponentName(
1177 aInfo.applicationInfo.packageName, aInfo.name));
1178 intent.setFlags(intent.getFlags()&~(
1179 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1180 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1181 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1182 FLAG_ACTIVITY_NEW_TASK));
1183
1184 // Okay now we need to start the new activity, replacing the currently running activity.
1185 // This is a little tricky because we want to start the new one as if the current one is
1186 // finished, but not finish the current one first so that there is no flicker.
1187 // And thus...
1188 final boolean wasFinishing = r.finishing;
1189 r.finishing = true;
1190
1191 // Propagate reply information over to the new activity.
1192 final ActivityRecord resultTo = r.resultTo;
1193 final String resultWho = r.resultWho;
1194 final int requestCode = r.requestCode;
1195 r.resultTo = null;
1196 if (resultTo != null) {
1197 resultTo.removeResultsLocked(r, resultWho, requestCode);
1198 }
1199
1200 final long origId = Binder.clearCallingIdentity();
1201 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001202 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001203 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001204 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001205 .setResolvedType(r.resolvedType)
1206 .setActivityInfo(aInfo)
1207 .setResultTo(resultTo != null ? resultTo.appToken : null)
1208 .setResultWho(resultWho)
1209 .setRequestCode(requestCode)
1210 .setCallingPid(-1)
1211 .setCallingUid(r.launchedFromUid)
1212 .setCallingPackage(r.launchedFromPackage)
1213 .setRealCallingPid(-1)
1214 .setRealCallingUid(r.launchedFromUid)
1215 .setActivityOptions(options)
1216 .execute();
1217 Binder.restoreCallingIdentity(origId);
1218
1219 r.finishing = wasFinishing;
1220 if (res != ActivityManager.START_SUCCESS) {
1221 return false;
1222 }
1223 return true;
1224 }
1225 }
1226
1227 @Override
1228 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1231 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001232 enforceNotIsolatedCaller("startActivityAndWait");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1234 userId, "startActivityAndWait");
1235 // TODO: Switch to user app stacks here.
1236 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setActivityOptions(bOptions)
1245 .setUserId(userId)
1246 .setProfilerInfo(profilerInfo)
1247 .setWaitResult(res)
1248 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001249 return res;
1250 }
1251
1252 @Override
1253 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1254 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1255 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001256 enforceNotIsolatedCaller("startActivityWithConfig");
1257 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1258 "startActivityWithConfig");
1259 // TODO: Switch to user app stacks here.
1260 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1261 .setCaller(caller)
1262 .setCallingPackage(callingPackage)
1263 .setResolvedType(resolvedType)
1264 .setResultTo(resultTo)
1265 .setResultWho(resultWho)
1266 .setRequestCode(requestCode)
1267 .setStartFlags(startFlags)
1268 .setGlobalConfiguration(config)
1269 .setActivityOptions(bOptions)
1270 .setUserId(userId)
1271 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001272 }
1273
Alison Cichowlas3e340502018-08-07 17:15:01 -04001274
1275 @Override
1276 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1277 int callingUid = Binder.getCallingUid();
1278 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1279 throw new SecurityException("Only the system process can request a permission token, "
1280 + "received request from uid: " + callingUid);
1281 }
1282 IBinder permissionToken = new Binder();
1283 synchronized (mGlobalLock) {
1284 mStartActivitySources.put(permissionToken, delegatorToken);
1285 }
1286
1287 Message expireMsg = PooledLambda.obtainMessage(
1288 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1289 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1290
1291 Message forgetMsg = PooledLambda.obtainMessage(
1292 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1293 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1294
1295 return permissionToken;
1296 }
1297
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 @Override
1299 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1300 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1302 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001304 // permission grants) as any app that may launch one of your own activities. So we only
1305 // allow this in two cases:
1306 // 1) The caller is an activity that is part of the core framework, and then only when it
1307 // is running as the system.
1308 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1309 // can only be requested by a system activity, which may then delegate this call to
1310 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 final ActivityRecord sourceRecord;
1312 final int targetUid;
1313 final String targetPackage;
1314 final boolean isResolver;
1315 synchronized (mGlobalLock) {
1316 if (resultTo == null) {
1317 throw new SecurityException("Must be called from an activity");
1318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319 final IBinder sourceToken;
1320 if (permissionToken != null) {
1321 // To even attempt to use a permissionToken, an app must also have this signature
1322 // permission.
1323 mAmInternal.enforceCallingPermission(
1324 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1325 "startActivityAsCaller");
1326 // If called with a permissionToken, we want the sourceRecord from the delegator
1327 // activity that requested this token.
1328 sourceToken = mStartActivitySources.remove(permissionToken);
1329 if (sourceToken == null) {
1330 // Invalid permissionToken, check if it recently expired.
1331 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1332 throw new SecurityException("Called with expired permission token: "
1333 + permissionToken);
1334 } else {
1335 throw new SecurityException("Called with invalid permission token: "
1336 + permissionToken);
1337 }
1338 }
1339 } else {
1340 // This method was called directly by the source.
1341 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001343
Wale Ogunwaled32da472018-11-16 07:19:28 -08001344 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345 if (sourceRecord == null) {
1346 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 }
1348 if (sourceRecord.app == null) {
1349 throw new SecurityException("Called without a process attached to activity");
1350 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351
1352 // Whether called directly or from a delegate, the source activity must be from the
1353 // android package.
1354 if (!sourceRecord.info.packageName.equals("android")) {
1355 throw new SecurityException("Must be called from an activity that is "
1356 + "declared in the android package");
1357 }
1358
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001359 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 // This is still okay, as long as this activity is running under the
1361 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001364 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 + " must be system uid or original calling uid "
1366 + sourceRecord.launchedFromUid);
1367 }
1368 }
1369 if (ignoreTargetSecurity) {
1370 if (intent.getComponent() == null) {
1371 throw new SecurityException(
1372 "Component must be specified with ignoreTargetSecurity");
1373 }
1374 if (intent.getSelector() != null) {
1375 throw new SecurityException(
1376 "Selector not allowed with ignoreTargetSecurity");
1377 }
1378 }
1379 targetUid = sourceRecord.launchedFromUid;
1380 targetPackage = sourceRecord.launchedFromPackage;
1381 isResolver = sourceRecord.isResolverOrChildActivity();
1382 }
1383
1384 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001385 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 }
1387
1388 // TODO: Switch to user app stacks here.
1389 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001390 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 .setCallingUid(targetUid)
1392 .setCallingPackage(targetPackage)
1393 .setResolvedType(resolvedType)
1394 .setResultTo(resultTo)
1395 .setResultWho(resultWho)
1396 .setRequestCode(requestCode)
1397 .setStartFlags(startFlags)
1398 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001399 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1401 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001402 // The target may well be in the background, which would normally prevent it
1403 // from starting an activity. Here we definitely want the start to succeed.
1404 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 .execute();
1406 } catch (SecurityException e) {
1407 // XXX need to figure out how to propagate to original app.
1408 // A SecurityException here is generally actually a fault of the original
1409 // calling activity (such as a fairly granting permissions), so propagate it
1410 // back to them.
1411 /*
1412 StringBuilder msg = new StringBuilder();
1413 msg.append("While launching");
1414 msg.append(intent.toString());
1415 msg.append(": ");
1416 msg.append(e.getMessage());
1417 */
1418 throw e;
1419 }
1420 }
1421
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001422 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1423 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1424 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1425 }
1426
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 @Override
1428 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1429 Intent intent, String resolvedType, IVoiceInteractionSession session,
1430 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1431 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 if (session == null || interactor == null) {
1434 throw new NullPointerException("null session or interactor");
1435 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(callingUid)
1440 .setCallingPackage(callingPackage)
1441 .setResolvedType(resolvedType)
1442 .setVoiceSession(session)
1443 .setVoiceInteractor(interactor)
1444 .setStartFlags(startFlags)
1445 .setProfilerInfo(profilerInfo)
1446 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001447 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001448 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .execute();
1450 }
1451
1452 @Override
1453 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1454 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1456 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001458 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .setCallingUid(callingUid)
1460 .setCallingPackage(callingPackage)
1461 .setResolvedType(resolvedType)
1462 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001463 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001464 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .execute();
1466 }
1467
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 /**
1469 * Start the recents activity to perform the recents animation.
1470 *
1471 * @param intent The intent to start the recents activity.
1472 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1473 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001475 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1476 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001477 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 final long origId = Binder.clearCallingIdentity();
1481 try {
1482 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001483 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1484 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001485 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486
1487 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001488 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001490 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001491 if (recentsAnimationRunner == null) {
1492 anim.preloadRecentsActivity();
1493 } else {
1494 anim.startRecentsActivity(recentsAnimationRunner);
1495 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 }
1497 } finally {
1498 Binder.restoreCallingIdentity(origId);
1499 }
1500 }
1501
1502 @Override
1503 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001504 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 "startActivityFromRecents()");
1506
1507 final int callingPid = Binder.getCallingPid();
1508 final int callingUid = Binder.getCallingUid();
1509 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1510 final long origId = Binder.clearCallingIdentity();
1511 try {
1512 synchronized (mGlobalLock) {
1513 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1514 safeOptions);
1515 }
1516 } finally {
1517 Binder.restoreCallingIdentity(origId);
1518 }
1519 }
1520
1521 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001522 * Public API to check if the client is allowed to start an activity on specified display.
1523 *
1524 * If the target display is private or virtual, some restrictions will apply.
1525 *
1526 * @param displayId Target display id.
1527 * @param intent Intent used to launch the activity.
1528 * @param resolvedType The MIME type of the intent.
1529 * @param userId The id of the user for whom the call is made.
1530 * @return {@code true} if a call to start an activity on the target display should succeed and
1531 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1532 */
1533 @Override
1534 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1535 String resolvedType, int userId) {
1536 final int callingUid = Binder.getCallingUid();
1537 final int callingPid = Binder.getCallingPid();
1538 final long origId = Binder.clearCallingIdentity();
1539
1540 try {
1541 // Collect information about the target of the Intent.
1542 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1543 0 /* startFlags */, null /* profilerInfo */, userId,
1544 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1545 UserHandle.USER_NULL));
1546 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1547
1548 synchronized (mGlobalLock) {
1549 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1550 aInfo);
1551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(origId);
1554 }
1555 }
1556
1557 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 * This is the internal entry point for handling Activity.finish().
1559 *
1560 * @param token The Binder token referencing the Activity we want to finish.
1561 * @param resultCode Result code, if any, from this Activity.
1562 * @param resultData Result data (Intent), if any, from this Activity.
1563 * @param finishTask Whether to finish the task associated with this Activity.
1564 *
1565 * @return Returns true if the activity successfully finished, or false if it is still running.
1566 */
1567 @Override
1568 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1569 int finishTask) {
1570 // Refuse possible leaked file descriptors
1571 if (resultData != null && resultData.hasFileDescriptors()) {
1572 throw new IllegalArgumentException("File descriptors passed in Intent");
1573 }
1574
1575 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (r == null) {
1578 return true;
1579 }
1580 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001581 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001582 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 if (rootR == null) {
1584 Slog.w(TAG, "Finishing task with all activities already finished");
1585 }
1586 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1587 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001588 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 return false;
1590 }
1591
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1593 // We should consolidate.
1594 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001596 final ActivityRecord next =
1597 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 if (next != null) {
1599 // ask watcher if this is allowed
1600 boolean resumeOK = true;
1601 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001602 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 Watchdog.getInstance().setActivityController(null);
1606 }
1607
1608 if (!resumeOK) {
1609 Slog.i(TAG, "Not finishing activity because controller resumed");
1610 return false;
1611 }
1612 }
1613 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001614
1615 // note down that the process has finished an activity and is in background activity
1616 // starts grace period
1617 if (r.app != null) {
1618 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1619 }
1620
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001622 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 try {
1624 boolean res;
1625 final boolean finishWithRootActivity =
1626 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1627 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1628 || (finishWithRootActivity && r == rootR)) {
1629 // If requested, remove the task that is associated to this activity only if it
1630 // was the root activity in the task. The result code and data is ignored
1631 // because we don't support returning them across task boundaries. Also, to
1632 // keep backwards compatibility we remove the task from recents when finishing
1633 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001634 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001636 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001637 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001638 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001640 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001641 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 if (!res) {
1643 Slog.i(TAG, "Failed to finish by app-request");
1644 }
1645 }
1646 return res;
1647 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001648 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public boolean finishActivityAffinity(IBinder token) {
1656 synchronized (mGlobalLock) {
1657 final long origId = Binder.clearCallingIdentity();
1658 try {
1659 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1660 if (r == null) {
1661 return false;
1662 }
1663
1664 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1665 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001666 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 return false;
1668 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001669
1670 final PooledFunction p = PooledLambda.obtainFunction(
1671 ActivityRecord::finishIfSameAffinity, r,
1672 PooledLambda.__(ActivityRecord.class));
1673 r.getTask().forAllActivities(
1674 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1675 p.recycle();
1676
Andrii Kuliande93eff2019-07-12 12:21:27 -07001677 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
1680 }
1681 }
1682 }
1683
1684 @Override
1685 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1686 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001687 try {
1688 WindowProcessController proc = null;
1689 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001690 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001691 ActivityStack stack = ActivityRecord.getStackLocked(token);
1692 if (stack == null) {
1693 return;
1694 }
1695 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1696 false /* fromTimeout */, false /* processPausingActivities */, config);
1697 if (r != null) {
1698 proc = r.app;
1699 }
1700 if (stopProfiling && proc != null) {
1701 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 }
1703 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001704 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001705 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001706 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 }
1709
1710 @Override
1711 public final void activityResumed(IBinder token) {
1712 final long origId = Binder.clearCallingIdentity();
1713 synchronized (mGlobalLock) {
1714 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 }
1716 Binder.restoreCallingIdentity(origId);
1717 }
1718
1719 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001720 public final void activityTopResumedStateLost() {
1721 final long origId = Binder.clearCallingIdentity();
1722 synchronized (mGlobalLock) {
1723 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1724 }
1725 Binder.restoreCallingIdentity(origId);
1726 }
1727
1728 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 public final void activityPaused(IBinder token) {
1730 final long origId = Binder.clearCallingIdentity();
1731 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001732 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 ActivityStack stack = ActivityRecord.getStackLocked(token);
1734 if (stack != null) {
1735 stack.activityPausedLocked(token, false);
1736 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001737 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 }
1739 Binder.restoreCallingIdentity(origId);
1740 }
1741
1742 @Override
1743 public final void activityStopped(IBinder token, Bundle icicle,
1744 PersistableBundle persistentState, CharSequence description) {
1745 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1746
1747 // Refuse possible leaked file descriptors
1748 if (icicle != null && icicle.hasFileDescriptors()) {
1749 throw new IllegalArgumentException("File descriptors passed in Bundle");
1750 }
1751
1752 final long origId = Binder.clearCallingIdentity();
1753
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001754 String restartingName = null;
1755 int restartingUid = 0;
1756 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001759 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001761 if (r.attachedToProcess()
1762 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1763 // The activity was requested to restart from
1764 // {@link #restartActivityProcessIfVisible}.
1765 restartingName = r.app.mName;
1766 restartingUid = r.app.mUid;
1767 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001768 r.activityStoppedLocked(icicle, persistentState, description);
1769 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001770 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 }
1772
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001773 if (restartingName != null) {
1774 // In order to let the foreground activity can be restarted with its saved state from
1775 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1776 // until the activity reports stopped with the state. And the activity record will be
1777 // kept because the record state is restarting, then the activity will be restarted
1778 // immediately if it is still the top one.
1779 mStackSupervisor.removeRestartTimeouts(r);
1780 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1781 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001782 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783
1784 Binder.restoreCallingIdentity(origId);
1785 }
1786
1787 @Override
1788 public final void activityDestroyed(IBinder token) {
1789 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1790 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001791 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001792 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001793 try {
1794 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1795 if (activity != null) {
1796 activity.destroyed("activityDestroyed");
1797 }
1798 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001799 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001800 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 }
1802 }
1803 }
1804
1805 @Override
1806 public final void activityRelaunched(IBinder token) {
1807 final long origId = Binder.clearCallingIdentity();
1808 synchronized (mGlobalLock) {
1809 mStackSupervisor.activityRelaunchedLocked(token);
1810 }
1811 Binder.restoreCallingIdentity(origId);
1812 }
1813
1814 public final void activitySlept(IBinder token) {
1815 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1816
1817 final long origId = Binder.clearCallingIdentity();
1818
1819 synchronized (mGlobalLock) {
1820 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r != null) {
1822 mStackSupervisor.activitySleptLocked(r);
1823 }
1824 }
1825
1826 Binder.restoreCallingIdentity(origId);
1827 }
1828
1829 @Override
1830 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1831 synchronized (mGlobalLock) {
1832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1833 if (r == null) {
1834 return;
1835 }
1836 final long origId = Binder.clearCallingIdentity();
1837 try {
1838 r.setRequestedOrientation(requestedOrientation);
1839 } finally {
1840 Binder.restoreCallingIdentity(origId);
1841 }
1842 }
1843 }
1844
1845 @Override
1846 public int getRequestedOrientation(IBinder token) {
1847 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001848 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1849 return (r != null)
1850 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 }
1852 }
1853
1854 @Override
1855 public void setImmersive(IBinder token, boolean immersive) {
1856 synchronized (mGlobalLock) {
1857 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1858 if (r == null) {
1859 throw new IllegalArgumentException();
1860 }
1861 r.immersive = immersive;
1862
1863 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001864 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001866 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 }
1868 }
1869 }
1870
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 void applyUpdateLockStateLocked(ActivityRecord r) {
1872 // Modifications to the UpdateLock state are done on our handler, outside
1873 // the activity manager's locks. The new state is determined based on the
1874 // state *now* of the relevant activity record. The object is passed to
1875 // the handler solely for logging detail, not to be consulted/modified.
1876 final boolean nextState = r != null && r.immersive;
1877 mH.post(() -> {
1878 if (mUpdateLock.isHeld() != nextState) {
1879 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1880 "Applying new update lock state '" + nextState + "' for " + r);
1881 if (nextState) {
1882 mUpdateLock.acquire();
1883 } else {
1884 mUpdateLock.release();
1885 }
1886 }
1887 });
1888 }
1889
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 @Override
1891 public boolean isImmersive(IBinder token) {
1892 synchronized (mGlobalLock) {
1893 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1894 if (r == null) {
1895 throw new IllegalArgumentException();
1896 }
1897 return r.immersive;
1898 }
1899 }
1900
1901 @Override
1902 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 return (r != null) ? r.immersive : false;
1907 }
1908 }
1909
1910 @Override
1911 public void overridePendingTransition(IBinder token, String packageName,
1912 int enterAnim, int exitAnim) {
1913 synchronized (mGlobalLock) {
1914 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1915 if (self == null) {
1916 return;
1917 }
1918
1919 final long origId = Binder.clearCallingIdentity();
1920
1921 if (self.isState(
1922 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001923 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001924 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 }
1926
1927 Binder.restoreCallingIdentity(origId);
1928 }
1929 }
1930
1931 @Override
1932 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001935 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 if (r == null) {
1937 return ActivityManager.COMPAT_MODE_UNKNOWN;
1938 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001939 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 }
1941 }
1942
1943 @Override
1944 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001949 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001950 if (r == null) {
1951 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1952 return;
1953 }
1954 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001955 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 }
1957 }
1958
1959 @Override
1960 public int getLaunchedFromUid(IBinder activityToken) {
1961 ActivityRecord srec;
1962 synchronized (mGlobalLock) {
1963 srec = ActivityRecord.forTokenLocked(activityToken);
1964 }
1965 if (srec == null) {
1966 return -1;
1967 }
1968 return srec.launchedFromUid;
1969 }
1970
1971 @Override
1972 public String getLaunchedFromPackage(IBinder activityToken) {
1973 ActivityRecord srec;
1974 synchronized (mGlobalLock) {
1975 srec = ActivityRecord.forTokenLocked(activityToken);
1976 }
1977 if (srec == null) {
1978 return null;
1979 }
1980 return srec.launchedFromPackage;
1981 }
1982
1983 @Override
1984 public boolean convertFromTranslucent(IBinder token) {
1985 final long origId = Binder.clearCallingIdentity();
1986 try {
1987 synchronized (mGlobalLock) {
1988 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1989 if (r == null) {
1990 return false;
1991 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001992 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
1994 } finally {
1995 Binder.restoreCallingIdentity(origId);
1996 }
1997 }
1998
1999 @Override
2000 public boolean convertToTranslucent(IBinder token, Bundle options) {
2001 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2002 final long origId = Binder.clearCallingIdentity();
2003 try {
2004 synchronized (mGlobalLock) {
2005 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2006 if (r == null) {
2007 return false;
2008 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002009 final ActivityRecord under = r.getTask().getActivityBelow(r);
2010 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2012 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002013 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 } finally {
2016 Binder.restoreCallingIdentity(origId);
2017 }
2018 }
2019
2020 @Override
2021 public void notifyActivityDrawn(IBinder token) {
2022 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2023 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002024 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002026 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 }
2028 }
2029 }
2030
2031 @Override
2032 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2033 synchronized (mGlobalLock) {
2034 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2035 if (r == null) {
2036 return;
2037 }
2038 r.reportFullyDrawnLocked(restoredFromBundle);
2039 }
2040 }
2041
2042 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002043 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 synchronized (mGlobalLock) {
2045 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2046 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2047 return stack.mDisplayId;
2048 }
2049 return DEFAULT_DISPLAY;
2050 }
2051 }
2052
2053 @Override
2054 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002055 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 long ident = Binder.clearCallingIdentity();
2057 try {
2058 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002059 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 }
2063 return null;
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(ident);
2067 }
2068 }
2069
2070 @Override
2071 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2074 final long callingId = Binder.clearCallingIdentity();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 if (stack == null) {
2079 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2080 return;
2081 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002082 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002083 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 } finally {
2088 Binder.restoreCallingIdentity(callingId);
2089 }
2090 }
2091
2092 @Override
2093 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002094 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2096 final long callingId = Binder.clearCallingIdentity();
2097 try {
2098 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002099 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002100 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 if (task == null) {
2102 return;
2103 }
2104 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002105 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002106 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(callingId);
2111 }
2112 }
2113
2114 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002115 public void restartActivityProcessIfVisible(IBinder activityToken) {
2116 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2117 final long callingId = Binder.clearCallingIdentity();
2118 try {
2119 synchronized (mGlobalLock) {
2120 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2121 if (r == null) {
2122 return;
2123 }
2124 r.restartProcessIfVisible();
2125 }
2126 } finally {
2127 Binder.restoreCallingIdentity(callingId);
2128 }
2129 }
2130
2131 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002133 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 synchronized (mGlobalLock) {
2135 final long ident = Binder.clearCallingIdentity();
2136 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002137 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 "remove-task");
2139 } finally {
2140 Binder.restoreCallingIdentity(ident);
2141 }
2142 }
2143 }
2144
2145 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002146 public void removeAllVisibleRecentTasks() {
2147 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2148 synchronized (mGlobalLock) {
2149 final long ident = Binder.clearCallingIdentity();
2150 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002151 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002152 } finally {
2153 Binder.restoreCallingIdentity(ident);
2154 }
2155 }
2156 }
2157
2158 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2160 synchronized (mGlobalLock) {
2161 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2162 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002163 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 }
2165 }
2166 return false;
2167 }
2168
2169 @Override
2170 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2171 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002172
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002173 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002174 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2175 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002176 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002177 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002178 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002179 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 }
2181 }
2182
2183 /**
2184 * Attempts to move a task backwards in z-order (the order of activities within the task is
2185 * unchanged).
2186 *
2187 * There are several possible results of this call:
2188 * - if the task is locked, then we will show the lock toast
2189 * - if there is a task behind the provided task, then that task is made visible and resumed as
2190 * this task is moved to the back
2191 * - otherwise, if there are no other tasks in the stack:
2192 * - if this task is in the pinned stack, then we remove the stack completely, which will
2193 * have the effect of moving the task to the top or bottom of the fullscreen stack
2194 * (depending on whether it is visible)
2195 * - otherwise, we simply return home and hide this task
2196 *
2197 * @param token A reference to the activity we wish to move
2198 * @param nonRoot If false then this only works if the activity is the root
2199 * of a task; if true it will work for any activity in a task.
2200 * @return Returns true if the move completed, false if not.
2201 */
2202 @Override
2203 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002204 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 synchronized (mGlobalLock) {
2206 final long origId = Binder.clearCallingIdentity();
2207 try {
2208 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002209 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002211 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 }
2213 } finally {
2214 Binder.restoreCallingIdentity(origId);
2215 }
2216 }
2217 return false;
2218 }
2219
2220 @Override
2221 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 long ident = Binder.clearCallingIdentity();
2224 Rect rect = new Rect();
2225 try {
2226 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002227 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (task == null) {
2230 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2231 return rect;
2232 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002233 if (task.getParent() != null) {
2234 rect.set(task.getBounds());
2235 } else if (task.mLastNonFullscreenBounds != null) {
2236 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 }
2238 }
2239 } finally {
2240 Binder.restoreCallingIdentity(ident);
2241 }
2242 return rect;
2243 }
2244
2245 @Override
2246 public ActivityManager.TaskDescription getTaskDescription(int id) {
2247 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002248 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002250 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2252 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002253 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002254 }
2255 }
2256 return null;
2257 }
2258
2259 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002260 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2261 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2262 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2263 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2264 return;
2265 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002266 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 synchronized (mGlobalLock) {
2268 final long ident = Binder.clearCallingIdentity();
2269 try {
Louis Changcdec0802019-11-11 11:45:07 +08002270 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002271 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002272 if (task == null) {
2273 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2274 return;
2275 }
2276
2277 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2278 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2279
2280 if (!task.isActivityTypeStandardOrUndefined()) {
2281 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2282 + " non-standard task " + taskId + " to windowing mode="
2283 + windowingMode);
2284 }
2285
2286 final ActivityStack stack = task.getStack();
2287 if (toTop) {
2288 stack.moveToFront("setTaskWindowingMode", task);
2289 }
2290 stack.setWindowingMode(windowingMode);
2291 } finally {
2292 Binder.restoreCallingIdentity(ident);
2293 }
2294 }
2295 }
2296
2297 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002299 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 ActivityRecord r = getCallingRecordLocked(token);
2301 return r != null ? r.info.packageName : null;
2302 }
2303 }
2304
2305 @Override
2306 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 ActivityRecord r = getCallingRecordLocked(token);
2309 return r != null ? r.intent.getComponent() : null;
2310 }
2311 }
2312
2313 private ActivityRecord getCallingRecordLocked(IBinder token) {
2314 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2315 if (r == null) {
2316 return null;
2317 }
2318 return r.resultTo;
2319 }
2320
2321 @Override
2322 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002323 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002324
2325 synchronized (mGlobalLock) {
2326 final long origId = Binder.clearCallingIdentity();
2327 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002328 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 } finally {
2330 Binder.restoreCallingIdentity(origId);
2331 }
2332 }
2333 }
2334
Mark Renouf446251d2019-04-26 10:22:41 -04002335 @Override
2336 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2337 synchronized (mGlobalLock) {
2338 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2339 if (r == null) {
2340 return;
2341 }
2342 ActivityStack stack = r.getActivityStack();
2343 if (stack != null && stack.isSingleTaskInstance()) {
2344 // Single-task stacks are used for activities which are presented in floating
2345 // windows above full screen activities. Instead of directly finishing the
2346 // task, a task change listener is used to notify SystemUI so the action can be
2347 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002348 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002349 mTaskChangeNotificationController
2350 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2351 } else {
2352 try {
2353 callback.requestFinish();
2354 } catch (RemoteException e) {
2355 Slog.e(TAG, "Failed to invoke request finish callback", e);
2356 }
2357 }
2358 }
2359 }
2360
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 /**
2362 * TODO: Add mController hook
2363 */
2364 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2366 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368
2369 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2370 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2372 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 }
2374 }
2375
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2377 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002379
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 final int callingPid = Binder.getCallingPid();
2381 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002382 if (!isSameApp(callingUid, callingPackage)) {
2383 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2384 + Binder.getCallingPid() + " as package " + callingPackage;
2385 Slog.w(TAG, msg);
2386 throw new SecurityException(msg);
2387 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 SafeActivityOptions.abort(options);
2390 return;
2391 }
2392 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002393 WindowProcessController callerApp = null;
2394 if (appThread != null) {
2395 callerApp = getProcessController(appThread);
2396 }
2397 final ActivityStarter starter = getActivityStartController().obtainStarter(
2398 null /* intent */, "moveTaskToFront");
2399 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2400 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002401 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002402 return;
2403 }
2404 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 try {
Louis Changcdec0802019-11-11 11:45:07 +08002406 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 if (task == null) {
2408 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002409 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 return;
2411 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002412 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002414 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415 return;
2416 }
2417 ActivityOptions realOptions = options != null
2418 ? options.getOptions(mStackSupervisor)
2419 : null;
2420 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2421 false /* forceNonResizable */);
2422
Wale Ogunwale21e06482019-11-18 05:14:15 -08002423 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 if (topActivity != null) {
2425
2426 // We are reshowing a task, use a starting window to hide the initial draw delay
2427 // so the transition can start earlier.
2428 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2429 true /* taskSwitch */, fromRecents);
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(origId);
2433 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 }
2435
Ricky Waiaca8a772019-04-04 16:01:06 +01002436 /**
2437 * Return true if callingUid is system, or packageName belongs to that callingUid.
2438 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002439 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 try {
2441 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2442 if (packageName == null) {
2443 return false;
2444 }
2445 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2446 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2447 UserHandle.getUserId(callingUid));
2448 return UserHandle.isSameApp(callingUid, uid);
2449 }
2450 } catch (RemoteException e) {
2451 // Should not happen
2452 }
2453 return true;
2454 }
2455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2457 int callingPid, int callingUid, String name) {
2458 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2459 return true;
2460 }
2461
2462 if (getRecentTasks().isCallerRecents(sourceUid)) {
2463 return true;
2464 }
2465
2466 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(sourceUid)) {
2471 return true;
2472 }
2473
2474 // If the actual IPC caller is different from the logical source, then
2475 // also see if they are allowed to control app switches.
2476 if (callingUid != -1 && callingUid != sourceUid) {
2477 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(callingUid)) {
2482 return true;
2483 }
2484 }
2485
2486 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2487 return false;
2488 }
2489
2490 private boolean checkAllowAppSwitchUid(int uid) {
2491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2492 if (types != null) {
2493 for (int i = types.size() - 1; i >= 0; i--) {
2494 if (types.valueAt(i).intValue() == uid) {
2495 return true;
2496 }
2497 }
2498 }
2499 return false;
2500 }
2501
2502 @Override
2503 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2504 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2505 "setActivityController()");
2506 synchronized (mGlobalLock) {
2507 mController = controller;
2508 mControllerIsAMonkey = imAMonkey;
2509 Watchdog.getInstance().setActivityController(controller);
2510 }
2511 }
2512
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002513 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 synchronized (mGlobalLock) {
2515 return mController != null && mControllerIsAMonkey;
2516 }
2517 }
2518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 @Override
2520 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2521 synchronized (mGlobalLock) {
2522 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2523 }
2524 }
2525
2526 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2528 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2529 }
2530
2531 @Override
2532 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2533 @WindowConfiguration.ActivityType int ignoreActivityType,
2534 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2535 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002536 final int callingPid = Binder.getCallingPid();
2537 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002538 final int[] profileIds = getUserManager().getProfileIds(
2539 UserHandle.getUserId(callingUid), true);
2540 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2541 for (int i = 0; i < profileIds.length; i++) {
2542 callingProfileIds.add(profileIds[i]);
2543 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2545
2546 synchronized (mGlobalLock) {
2547 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2548
Nicholas Sauer0259e532019-08-30 08:24:55 -07002549 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002551 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 }
2553
2554 return list;
2555 }
2556
2557 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2559 synchronized (mGlobalLock) {
2560 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002561 try {
2562 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2563 if (r == null) return;
2564
2565 final PooledConsumer c = PooledLambda.obtainConsumer(
2566 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2567 r, resultWho, requestCode);
2568 // TODO: This should probably only loop over the task since you need to be in the
2569 // same task to return results.
2570 r.getActivityStack().forAllActivities(c);
2571 c.recycle();
2572
2573 updateOomAdj();
2574 } finally {
2575 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 }
2578 }
2579
2580 @Override
2581 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 ActivityStack stack = ActivityRecord.getStackLocked(token);
2584 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002585 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 }
2587 return false;
2588 }
2589 }
2590
2591 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 synchronized (mGlobalLock) {
2595 final long ident = Binder.clearCallingIdentity();
2596 try {
Louis Changcdec0802019-11-11 11:45:07 +08002597 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 if (task == null) {
2599 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2600 return;
2601 }
2602
2603 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2604 + " to stackId=" + stackId + " toTop=" + toTop);
2605
Wale Ogunwaled32da472018-11-16 07:19:28 -08002606 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 if (stack == null) {
2608 throw new IllegalStateException(
2609 "moveTaskToStack: No stack for stackId=" + stackId);
2610 }
2611 if (!stack.isActivityTypeStandardOrUndefined()) {
2612 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2613 + taskId + " to stack " + stackId);
2614 }
2615 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002616 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2618 }
2619 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2620 "moveTaskToStack");
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625 }
2626
2627 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002628 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002630
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
2633 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002634 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2635 if (stack == null) {
2636 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2637 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2640 throw new IllegalArgumentException("Stack: " + stackId
2641 + " doesn't support animated resize.");
2642 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002643 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002644 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 }
2646 } finally {
2647 Binder.restoreCallingIdentity(ident);
2648 }
2649 }
2650
wilsonshih5c4cf522019-01-25 09:03:47 +08002651 @Override
2652 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2653 int animationDuration) {
2654 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2655
2656 final long ident = Binder.clearCallingIdentity();
2657 try {
2658 synchronized (mGlobalLock) {
2659 if (xOffset == 0 && yOffset == 0) {
2660 return;
2661 }
2662 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2663 if (stack == null) {
2664 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2665 return;
2666 }
2667 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2668 throw new IllegalArgumentException("Stack: " + stackId
2669 + " doesn't support animated resize.");
2670 }
2671 final Rect destBounds = new Rect();
2672 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002673 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2675 return;
2676 }
2677 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002678 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002679 animationDuration, false /* fromFullscreen */);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 /**
2686 * Moves the specified task to the primary-split-screen stack.
2687 *
2688 * @param taskId Id of task to move.
2689 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2690 * exist already. See
2691 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2692 * and
2693 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2694 * @param toTop If the task and stack should be moved to the top.
2695 * @param animate Whether we should play an animation for the moving the task.
2696 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2697 * stack. Pass {@code null} to use default bounds.
2698 * @param showRecents If the recents activity should be shown on the other side of the task
2699 * going into split-screen mode.
2700 */
2701 @Override
2702 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2703 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002704 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 "setTaskWindowingModeSplitScreenPrimary()");
2706 synchronized (mGlobalLock) {
2707 final long ident = Binder.clearCallingIdentity();
2708 try {
Louis Changcdec0802019-11-11 11:45:07 +08002709 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002710 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 if (task == null) {
2712 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2713 return false;
2714 }
2715 if (DEBUG_STACK) Slog.d(TAG_STACK,
2716 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2717 + " to createMode=" + createMode + " toTop=" + toTop);
2718 if (!task.isActivityTypeStandardOrUndefined()) {
2719 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2720 + " non-standard task " + taskId + " to split-screen windowing mode");
2721 }
2722
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002723 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 final int windowingMode = task.getWindowingMode();
2725 final ActivityStack stack = task.getStack();
2726 if (toTop) {
2727 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2728 }
2729 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002730 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2731 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 return windowingMode != task.getWindowingMode();
2733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737 }
2738
2739 /**
2740 * Removes stacks in the input windowing modes from the system if they are of activity type
2741 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2742 */
2743 @Override
2744 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 "removeStacksInWindowingModes()");
2747
2748 synchronized (mGlobalLock) {
2749 final long ident = Binder.clearCallingIdentity();
2750 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002751 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756 }
2757
2758 @Override
2759 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002761 "removeStacksWithActivityTypes()");
2762
2763 synchronized (mGlobalLock) {
2764 final long ident = Binder.clearCallingIdentity();
2765 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
2770 }
2771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772
2773 @Override
2774 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2775 int userId) {
2776 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2778 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002780 final boolean detailed = checkGetTasksPermission(
2781 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2782 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 == PackageManager.PERMISSION_GRANTED;
2784
2785 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002786 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 callingUid);
2788 }
2789 }
2790
2791 @Override
2792 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002793 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 long ident = Binder.clearCallingIdentity();
2795 try {
2796 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002797 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 }
2799 } finally {
2800 Binder.restoreCallingIdentity(ident);
2801 }
2802 }
2803
2804 @Override
2805 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002806 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 long ident = Binder.clearCallingIdentity();
2808 try {
2809 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002810 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 }
2812 } finally {
2813 Binder.restoreCallingIdentity(ident);
2814 }
2815 }
2816
2817 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002818 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2819 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2820 long ident = Binder.clearCallingIdentity();
2821 try {
2822 synchronized (mGlobalLock) {
2823 return mRootActivityContainer.getAllStackInfos(displayId);
2824 }
2825 } finally {
2826 Binder.restoreCallingIdentity(ident);
2827 }
2828 }
2829
2830 @Override
2831 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2832 int displayId) {
2833 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2834 long ident = Binder.clearCallingIdentity();
2835 try {
2836 synchronized (mGlobalLock) {
2837 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2838 }
2839 } finally {
2840 Binder.restoreCallingIdentity(ident);
2841 }
2842 }
2843
2844 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002846 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002847 final long callingUid = Binder.getCallingUid();
2848 final long origId = Binder.clearCallingIdentity();
2849 try {
2850 synchronized (mGlobalLock) {
2851 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002852 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2854 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2855 }
2856 } finally {
2857 Binder.restoreCallingIdentity(origId);
2858 }
2859 }
2860
2861 @Override
2862 public void startLockTaskModeByToken(IBinder token) {
2863 synchronized (mGlobalLock) {
2864 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2865 if (r == null) {
2866 return;
2867 }
Louis Changcdec0802019-11-11 11:45:07 +08002868 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 }
2870 }
2871
2872 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002873 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002874 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 // This makes inner call to look as if it was initiated by system.
2876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002879 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002880 MATCH_TASK_IN_STACKS_ONLY);
2881 if (task == null) {
2882 return;
2883 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884
2885 // When starting lock task mode the stack must be in front and focused
2886 task.getStack().moveToFront("startSystemLockTaskMode");
2887 startLockTaskModeLocked(task, true /* isSystemCaller */);
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(ident);
2891 }
2892 }
2893
2894 @Override
2895 public void stopLockTaskModeByToken(IBinder token) {
2896 synchronized (mGlobalLock) {
2897 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2898 if (r == null) {
2899 return;
2900 }
Louis Changcdec0802019-11-11 11:45:07 +08002901 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 }
2904
2905 /**
2906 * This API should be called by SystemUI only when user perform certain action to dismiss
2907 * lock task mode. We should only dismiss pinned lock task mode in this case.
2908 */
2909 @Override
2910 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002911 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2913 }
2914
Louis Changcdec0802019-11-11 11:45:07 +08002915 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2917 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2918 return;
2919 }
2920
Wale Ogunwaled32da472018-11-16 07:19:28 -08002921 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002922 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 throw new IllegalArgumentException("Invalid task, not in foreground");
2924 }
2925
2926 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2927 // system or a specific app.
2928 // * System-initiated requests will only start the pinned mode (screen pinning)
2929 // * App-initiated requests
2930 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2931 // - will start the pinned mode, otherwise
2932 final int callingUid = Binder.getCallingUid();
2933 long ident = Binder.clearCallingIdentity();
2934 try {
2935 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002936 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002938 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 } finally {
2940 Binder.restoreCallingIdentity(ident);
2941 }
2942 }
2943
Louis Changcdec0802019-11-11 11:45:07 +08002944 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 final int callingUid = Binder.getCallingUid();
2946 long ident = Binder.clearCallingIdentity();
2947 try {
2948 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002949 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 }
2951 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2952 // task and jumping straight into a call in the case of emergency call back.
2953 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2954 if (tm != null) {
2955 tm.showInCallScreen(false);
2956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002963 public void updateLockTaskPackages(int userId, String[] packages) {
2964 final int callingUid = Binder.getCallingUid();
2965 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2966 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2967 "updateLockTaskPackages()");
2968 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002969 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002970 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2971 + Arrays.toString(packages));
2972 getLockTaskController().updateLockTaskPackages(userId, packages);
2973 }
2974 }
2975
2976 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 public boolean isInLockTaskMode() {
2978 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2979 }
2980
2981 @Override
2982 public int getLockTaskModeState() {
2983 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002984 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 }
2986 }
2987
2988 @Override
2989 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2990 synchronized (mGlobalLock) {
2991 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2992 if (r != null) {
2993 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002994 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 }
2997 }
2998 }
2999
3000 @Override
3001 public Bundle getActivityOptions(IBinder token) {
3002 final long origId = Binder.clearCallingIdentity();
3003 try {
3004 synchronized (mGlobalLock) {
3005 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3006 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003007 final ActivityOptions activityOptions = r.takeOptionsLocked(
3008 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 return activityOptions == null ? null : activityOptions.toBundle();
3010 }
3011 return null;
3012 }
3013 } finally {
3014 Binder.restoreCallingIdentity(origId);
3015 }
3016 }
3017
3018 @Override
3019 public List<IBinder> getAppTasks(String callingPackage) {
3020 int callingUid = Binder.getCallingUid();
3021 long ident = Binder.clearCallingIdentity();
3022 try {
3023 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003024 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 } finally {
3027 Binder.restoreCallingIdentity(ident);
3028 }
3029 }
3030
3031 @Override
3032 public void finishVoiceTask(IVoiceInteractionSession session) {
3033 synchronized (mGlobalLock) {
3034 final long origId = Binder.clearCallingIdentity();
3035 try {
3036 // TODO: VI Consider treating local voice interactions and voice tasks
3037 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003038 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 } finally {
3040 Binder.restoreCallingIdentity(origId);
3041 }
3042 }
3043
3044 }
3045
3046 @Override
3047 public boolean isTopOfTask(IBinder token) {
3048 synchronized (mGlobalLock) {
3049 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003050 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 }
3052 }
3053
3054 @Override
3055 public void notifyLaunchTaskBehindComplete(IBinder token) {
3056 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3057 }
3058
3059 @Override
3060 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003061 mH.post(() -> {
3062 synchronized (mGlobalLock) {
3063 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003064 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003066 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003067 } catch (RemoteException e) {
3068 }
3069 }
3070 }
3071
3072 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 }
3074
3075 /** Called from an app when assist data is ready. */
3076 @Override
3077 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3078 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003079 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 synchronized (pae) {
3081 pae.result = extras;
3082 pae.structure = structure;
3083 pae.content = content;
3084 if (referrer != null) {
3085 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3086 }
3087 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003088 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003089 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003090 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 structure.setHomeActivity(pae.isHome);
3092 }
3093 pae.haveResult = true;
3094 pae.notifyAll();
3095 if (pae.intent == null && pae.receiver == null) {
3096 // Caller is just waiting for the result.
3097 return;
3098 }
3099 }
3100 // We are now ready to launch the assist activity.
3101 IAssistDataReceiver sendReceiver = null;
3102 Bundle sendBundle = null;
3103 synchronized (mGlobalLock) {
3104 buildAssistBundleLocked(pae, extras);
3105 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003106 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 if (!exists) {
3108 // Timed out.
3109 return;
3110 }
3111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 // Caller wants result sent back to them.
3114 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003115 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003116 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003117 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3118 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3120 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3121 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3122 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3123 }
3124 }
3125 if (sendReceiver != null) {
3126 try {
3127 sendReceiver.onHandleAssistData(sendBundle);
3128 } catch (RemoteException e) {
3129 }
3130 return;
3131 }
3132
3133 final long ident = Binder.clearCallingIdentity();
3134 try {
3135 if (TextUtils.equals(pae.intent.getAction(),
3136 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003137 // Start voice interaction through VoiceInteractionManagerService.
3138 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3139 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 } else {
3141 pae.intent.replaceExtras(pae.extras);
3142 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3143 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3144 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003145 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146
3147 try {
3148 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3149 } catch (ActivityNotFoundException e) {
3150 Slog.w(TAG, "No activity to handle assist action.", e);
3151 }
3152 }
3153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157
3158 @Override
3159 public int addAppTask(IBinder activityToken, Intent intent,
3160 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3161 final int callingUid = Binder.getCallingUid();
3162 final long callingIdent = Binder.clearCallingIdentity();
3163
3164 try {
3165 synchronized (mGlobalLock) {
3166 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3167 if (r == null) {
3168 throw new IllegalArgumentException("Activity does not exist; token="
3169 + activityToken);
3170 }
3171 ComponentName comp = intent.getComponent();
3172 if (comp == null) {
3173 throw new IllegalArgumentException("Intent " + intent
3174 + " must specify explicit component");
3175 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 if (thumbnail.getWidth() != mThumbnailWidth
3177 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 throw new IllegalArgumentException("Bad thumbnail size: got "
3179 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 if (intent.getSelector() != null) {
3183 intent.setSelector(null);
3184 }
3185 if (intent.getSourceBounds() != null) {
3186 intent.setSourceBounds(null);
3187 }
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3189 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3190 // The caller has added this as an auto-remove task... that makes no
3191 // sense, so turn off auto-remove.
3192 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3193 }
3194 }
3195 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3196 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3197 if (ainfo.applicationInfo.uid != callingUid) {
3198 throw new SecurityException(
3199 "Can't add task for another application: target uid="
3200 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3201 }
3202
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003203 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003204 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003205 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003207 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003209 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 return INVALID_TASK_ID;
3211 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003212 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213
3214 // TODO: Send the thumbnail to WM to store it.
3215
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003216 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 }
3218 } finally {
3219 Binder.restoreCallingIdentity(callingIdent);
3220 }
3221 }
3222
3223 @Override
3224 public Point getAppTaskThumbnailSize() {
3225 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003226 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 }
3229
3230 @Override
3231 public void setTaskResizeable(int taskId, int resizeableMode) {
3232 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003233 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3235 if (task == null) {
3236 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3237 return;
3238 }
3239 task.setResizeMode(resizeableMode);
3240 }
3241 }
3242
3243 @Override
3244 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 long ident = Binder.clearCallingIdentity();
3247 try {
3248 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003249 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003250 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 if (task == null) {
3252 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3253 return;
3254 }
3255 // Place the task in the right stack if it isn't there already based on
3256 // the requested bounds.
3257 // The stack transition logic is:
3258 // - a null bounds on a freeform task moves that task to fullscreen
3259 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3260 // that task to freeform
3261 // - otherwise the task is not moved
3262 ActivityStack stack = task.getStack();
3263 if (!task.getWindowConfiguration().canResizeTask()) {
3264 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3265 }
3266 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3267 stack = stack.getDisplay().getOrCreateStack(
3268 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3269 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3270 stack = stack.getDisplay().getOrCreateStack(
3271 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3272 }
3273
3274 // Reparent the task to the right stack if necessary
3275 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3276 if (stack != task.getStack()) {
3277 // Defer resume until the task is resized below
3278 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3279 DEFER_RESUME, "resizeTask");
3280 preserveWindow = false;
3281 }
3282
3283 // After reparenting (which only resizes the task to the stack bounds), resize the
3284 // task to the actual bounds provided
3285 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3286 }
3287 } finally {
3288 Binder.restoreCallingIdentity(ident);
3289 }
3290 }
3291
Evan Roskyddedfd42019-10-04 13:38:38 -07003292 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3293 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003294 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003295 throw new RuntimeException("Invalid token in task transaction");
3296 }
3297 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3298 // masks here.
3299 int configMask = change.getConfigSetMask();
3300 int windowMask = change.getWindowSetMask();
3301 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3302 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3303 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3304 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3305 c.setTo(change.getConfiguration(), configMask, windowMask);
3306 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003307 // TODO(b/145675353): remove the following once we could apply new bounds to the
3308 // pinned stack together with its children.
3309 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3310 }
3311
3312 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3313 int windowMask, Configuration config) {
3314 if ((container instanceof ActivityStack)
3315 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3316 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3317 final ActivityStack stack = (ActivityStack) container;
3318 if (stack.inPinnedWindowingMode()) {
3319 stack.resize(config.windowConfiguration.getBounds(),
3320 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3321 PRESERVE_WINDOWS, true /* deferResume */);
3322 }
3323 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003324 }
3325
3326 @Override
3327 public void applyContainerTransaction(WindowContainerTransaction t) {
3328 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3329 long ident = Binder.clearCallingIdentity();
3330 try {
3331 if (t == null) {
3332 return;
3333 }
3334 synchronized (mGlobalLock) {
3335 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3336 t.getChanges().entrySet().iterator();
3337 while (entries.hasNext()) {
3338 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3339 entries.next();
3340 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3341 entry.getKey()).getContainer();
3342 sanitizeAndApplyConfigChange(cc, entry.getValue());
3343 }
3344 }
3345 } finally {
3346 Binder.restoreCallingIdentity(ident);
3347 }
3348 }
3349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 @Override
3351 public boolean releaseActivityInstance(IBinder token) {
3352 synchronized (mGlobalLock) {
3353 final long origId = Binder.clearCallingIdentity();
3354 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003355 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3356 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 return false;
3358 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003359 r.destroyImmediately(true /* removeFromApp */, "app-req");
3360 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(origId);
3363 }
3364 }
3365 }
3366
3367 @Override
3368 public void releaseSomeActivities(IApplicationThread appInt) {
3369 synchronized (mGlobalLock) {
3370 final long origId = Binder.clearCallingIdentity();
3371 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003372 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003373 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 } finally {
3375 Binder.restoreCallingIdentity(origId);
3376 }
3377 }
3378 }
3379
3380 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003381 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 != PackageManager.PERMISSION_GRANTED) {
3384 throw new SecurityException("Requires permission "
3385 + android.Manifest.permission.DEVICE_POWER);
3386 }
3387
3388 synchronized (mGlobalLock) {
3389 long ident = Binder.clearCallingIdentity();
3390 if (mKeyguardShown != keyguardShowing) {
3391 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003392 final Message msg = PooledLambda.obtainMessage(
3393 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3394 keyguardShowing);
3395 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397 try {
wilsonshih177261f2019-02-22 12:02:18 +08003398 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 } finally {
3400 Binder.restoreCallingIdentity(ident);
3401 }
3402 }
3403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 mH.post(() -> {
3405 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3406 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3407 }
3408 });
3409 }
3410
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003411 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 mH.post(() -> {
3413 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3414 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3415 }
3416 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 }
3418
3419 @Override
3420 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3422 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423
3424 final File passedIconFile = new File(filePath);
3425 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3426 passedIconFile.getName());
3427 if (!legitIconFile.getPath().equals(filePath)
3428 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3429 throw new IllegalArgumentException("Bad file path: " + filePath
3430 + " passed for userId " + userId);
3431 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003432 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 }
3434
3435 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 synchronized (mGlobalLock) {
3439 final long ident = Binder.clearCallingIdentity();
3440 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003441 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 if (stack == null) {
3443 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3444 return;
3445 }
3446 if (!stack.isActivityTypeStandardOrUndefined()) {
3447 throw new IllegalArgumentException(
3448 "Removing non-standard stack is not allowed.");
3449 }
3450 mStackSupervisor.removeStack(stack);
3451 } finally {
3452 Binder.restoreCallingIdentity(ident);
3453 }
3454 }
3455 }
3456
3457 @Override
3458 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460
3461 synchronized (mGlobalLock) {
3462 final long ident = Binder.clearCallingIdentity();
3463 try {
3464 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3465 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003466 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 } finally {
3468 Binder.restoreCallingIdentity(ident);
3469 }
3470 }
3471 }
3472
3473 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003474 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 synchronized (mGlobalLock) {
3476 long ident = Binder.clearCallingIdentity();
3477 try {
3478 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3479 if (r == null) {
3480 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003481 "toggleFreeformWindowingMode: No activity record matching token="
3482 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 }
3484
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003485 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003486 if (stack == null) {
3487 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3488 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 }
3490
Yunfan Chend967af82019-01-17 18:30:18 +09003491 if (!stack.inFreeformWindowingMode()
3492 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3493 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3494 + "toggle between fullscreen and freeform.");
3495 }
3496
3497 if (stack.inFreeformWindowingMode()) {
3498 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003499 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003500 throw new IllegalStateException("Size-compat windows are currently not"
3501 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003502 } else if (stack.getParent().inFreeformWindowingMode()) {
3503 // If the window is on a freeform display, set it to undefined. It will be
3504 // resolved to freeform and it can adjust windowing mode when the display mode
3505 // changes in runtime.
3506 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003507 } else {
3508 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3509 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003510 } finally {
3511 Binder.restoreCallingIdentity(ident);
3512 }
3513 }
3514 }
3515
3516 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3517 @Override
3518 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003519 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003520 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003521 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 }
3523
3524 /** Unregister a task stack listener so that it stops receiving callbacks. */
3525 @Override
3526 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003529 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003530 }
3531
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 @Override
3533 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3534 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3535 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3536 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3537 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3538 }
3539
3540 @Override
3541 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3542 IBinder activityToken, int flags) {
3543 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3544 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3545 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3546 }
3547
3548 @Override
3549 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3550 Bundle args) {
3551 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3552 true /* focused */, true /* newSessionId */, userHandle, args,
3553 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3554 }
3555
3556 @Override
3557 public Bundle getAssistContextExtras(int requestType) {
3558 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3559 null, null, true /* focused */, true /* newSessionId */,
3560 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3561 if (pae == null) {
3562 return null;
3563 }
3564 synchronized (pae) {
3565 while (!pae.haveResult) {
3566 try {
3567 pae.wait();
3568 } catch (InterruptedException e) {
3569 }
3570 }
3571 }
3572 synchronized (mGlobalLock) {
3573 buildAssistBundleLocked(pae, pae.result);
3574 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003576 }
3577 return pae.extras;
3578 }
3579
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003580 /**
3581 * Binder IPC calls go through the public entry point.
3582 * This can be called with or without the global lock held.
3583 */
3584 private static int checkCallingPermission(String permission) {
3585 return checkPermission(
3586 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3587 }
3588
3589 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003590 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003591 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3592 mAmInternal.enforceCallingPermission(permission, func);
3593 }
3594 }
3595
3596 @VisibleForTesting
3597 int checkGetTasksPermission(String permission, int pid, int uid) {
3598 return checkPermission(permission, pid, uid);
3599 }
3600
3601 static int checkPermission(String permission, int pid, int uid) {
3602 if (permission == null) {
3603 return PackageManager.PERMISSION_DENIED;
3604 }
3605 return checkComponentPermission(permission, pid, uid, -1, true);
3606 }
3607
Wale Ogunwale214f3482018-10-04 11:00:47 -07003608 public static int checkComponentPermission(String permission, int pid, int uid,
3609 int owningUid, boolean exported) {
3610 return ActivityManagerService.checkComponentPermission(
3611 permission, pid, uid, owningUid, exported);
3612 }
3613
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003614 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3615 if (getRecentTasks().isCallerRecents(callingUid)) {
3616 // Always allow the recents component to get tasks
3617 return true;
3618 }
3619
3620 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3621 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3622 if (!allowed) {
3623 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3624 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3625 // Temporary compatibility: some existing apps on the system image may
3626 // still be requesting the old permission and not switched to the new
3627 // one; if so, we'll still allow them full access. This means we need
3628 // to see if they are holding the old permission and are a system app.
3629 try {
3630 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3631 allowed = true;
3632 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3633 + " is using old GET_TASKS but privileged; allowing");
3634 }
3635 } catch (RemoteException e) {
3636 }
3637 }
3638 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3639 + " does not hold REAL_GET_TASKS; limiting output");
3640 }
3641 return allowed;
3642 }
3643
Nicholas Sauer0259e532019-08-30 08:24:55 -07003644 boolean isCrossUserAllowed(int pid, int uid) {
3645 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3646 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3647 }
3648
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3650 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3651 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3652 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 "enqueueAssistContext()");
3655
3656 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003657 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 if (activity == null) {
3659 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3660 return null;
3661 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003662 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3664 return null;
3665 }
3666 if (focused) {
3667 if (activityToken != null) {
3668 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3669 if (activity != caller) {
3670 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3671 + " is not current top " + activity);
3672 return null;
3673 }
3674 }
3675 } else {
3676 activity = ActivityRecord.forTokenLocked(activityToken);
3677 if (activity == null) {
3678 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3679 + " couldn't be found");
3680 return null;
3681 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003682 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3684 return null;
3685 }
3686 }
3687
3688 PendingAssistExtras pae;
3689 Bundle extras = new Bundle();
3690 if (args != null) {
3691 extras.putAll(args);
3692 }
3693 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003694 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003695
3696 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3697 userHandle);
3698 pae.isHome = activity.isActivityTypeHome();
3699
3700 // Increment the sessionId if necessary
3701 if (newSessionId) {
3702 mViSessionId++;
3703 }
3704 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003705 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3706 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003707 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003708 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 } catch (RemoteException e) {
3710 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3711 return null;
3712 }
3713 return pae;
3714 }
3715 }
3716
3717 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3718 if (result != null) {
3719 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3720 }
3721 if (pae.hint != null) {
3722 pae.extras.putBoolean(pae.hint, true);
3723 }
3724 }
3725
3726 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3727 IAssistDataReceiver receiver;
3728 synchronized (mGlobalLock) {
3729 mPendingAssistExtras.remove(pae);
3730 receiver = pae.receiver;
3731 }
3732 if (receiver != null) {
3733 // Caller wants result sent back to them.
3734 Bundle sendBundle = new Bundle();
3735 // At least return the receiver extras
3736 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3737 try {
3738 pae.receiver.onHandleAssistData(sendBundle);
3739 } catch (RemoteException e) {
3740 }
3741 }
3742 }
3743
3744 public class PendingAssistExtras extends Binder implements Runnable {
3745 public final ActivityRecord activity;
3746 public boolean isHome;
3747 public final Bundle extras;
3748 public final Intent intent;
3749 public final String hint;
3750 public final IAssistDataReceiver receiver;
3751 public final int userHandle;
3752 public boolean haveResult = false;
3753 public Bundle result = null;
3754 public AssistStructure structure = null;
3755 public AssistContent content = null;
3756 public Bundle receiverExtras;
3757
3758 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3759 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3760 int _userHandle) {
3761 activity = _activity;
3762 extras = _extras;
3763 intent = _intent;
3764 hint = _hint;
3765 receiver = _receiver;
3766 receiverExtras = _receiverExtras;
3767 userHandle = _userHandle;
3768 }
3769
3770 @Override
3771 public void run() {
3772 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3773 synchronized (this) {
3774 haveResult = true;
3775 notifyAll();
3776 }
3777 pendingAssistExtrasTimedOut(this);
3778 }
3779 }
3780
3781 @Override
3782 public boolean isAssistDataAllowedOnCurrentActivity() {
3783 int userId;
3784 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003785 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3787 return false;
3788 }
3789
Wale Ogunwale21e06482019-11-18 05:14:15 -08003790 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 if (activity == null) {
3792 return false;
3793 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003794 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 }
3796 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3797 }
3798
3799 @Override
3800 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3801 long ident = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003805 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 if (top != caller) {
3807 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3808 + " is not current top " + top);
3809 return false;
3810 }
3811 if (!top.nowVisible) {
3812 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3813 + " is not visible");
3814 return false;
3815 }
3816 }
3817 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3818 token);
3819 } finally {
3820 Binder.restoreCallingIdentity(ident);
3821 }
3822 }
3823
3824 @Override
3825 public boolean isRootVoiceInteraction(IBinder token) {
3826 synchronized (mGlobalLock) {
3827 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3828 if (r == null) {
3829 return false;
3830 }
3831 return r.rootVoiceInteraction;
3832 }
3833 }
3834
Wale Ogunwalef6733932018-06-27 05:14:34 -07003835 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3836 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3837 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3838 if (activityToCallback == null) return;
3839 activityToCallback.setVoiceSessionLocked(voiceSession);
3840
3841 // Inform the activity
3842 try {
3843 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3844 voiceInteractor);
3845 long token = Binder.clearCallingIdentity();
3846 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003847 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003848 } finally {
3849 Binder.restoreCallingIdentity(token);
3850 }
3851 // TODO: VI Should we cache the activity so that it's easier to find later
3852 // rather than scan through all the stacks and activities?
3853 } catch (RemoteException re) {
3854 activityToCallback.clearVoiceSessionLocked();
3855 // TODO: VI Should this terminate the voice session?
3856 }
3857 }
3858
3859 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3860 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3861 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3862 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3863 boolean wasRunningVoice = mRunningVoice != null;
3864 mRunningVoice = session;
3865 if (!wasRunningVoice) {
3866 mVoiceWakeLock.acquire();
3867 updateSleepIfNeededLocked();
3868 }
3869 }
3870 }
3871
3872 void finishRunningVoiceLocked() {
3873 if (mRunningVoice != null) {
3874 mRunningVoice = null;
3875 mVoiceWakeLock.release();
3876 updateSleepIfNeededLocked();
3877 }
3878 }
3879
3880 @Override
3881 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3882 synchronized (mGlobalLock) {
3883 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3884 if (keepAwake) {
3885 mVoiceWakeLock.acquire();
3886 } else {
3887 mVoiceWakeLock.release();
3888 }
3889 }
3890 }
3891 }
3892
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 @Override
3894 public ComponentName getActivityClassForToken(IBinder token) {
3895 synchronized (mGlobalLock) {
3896 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3897 if (r == null) {
3898 return null;
3899 }
3900 return r.intent.getComponent();
3901 }
3902 }
3903
3904 @Override
3905 public String getPackageForToken(IBinder token) {
3906 synchronized (mGlobalLock) {
3907 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3908 if (r == null) {
3909 return null;
3910 }
3911 return r.packageName;
3912 }
3913 }
3914
3915 @Override
3916 public void showLockTaskEscapeMessage(IBinder token) {
3917 synchronized (mGlobalLock) {
3918 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3919 if (r == null) {
3920 return;
3921 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003922 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 }
3924 }
3925
3926 @Override
3927 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003928 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 final long token = Binder.clearCallingIdentity();
3930 try {
3931 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003932 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 }
3934 } finally {
3935 Binder.restoreCallingIdentity(token);
3936 }
3937 }
3938
3939 /**
3940 * Try to place task to provided position. The final position might be different depending on
3941 * current user and stacks state. The task will be moved to target stack if it's currently in
3942 * different stack.
3943 */
3944 @Override
3945 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003946 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 synchronized (mGlobalLock) {
3948 long ident = Binder.clearCallingIdentity();
3949 try {
3950 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3951 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003952 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 if (task == null) {
3954 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3955 + taskId);
3956 }
3957
Wale Ogunwaled32da472018-11-16 07:19:28 -08003958 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959
3960 if (stack == null) {
3961 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3962 + stackId);
3963 }
3964 if (!stack.isActivityTypeStandardOrUndefined()) {
3965 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3966 + " the position of task " + taskId + " in/to non-standard stack");
3967 }
3968
3969 // TODO: Have the callers of this API call a separate reparent method if that is
3970 // what they intended to do vs. having this method also do reparenting.
3971 if (task.getStack() == stack) {
3972 // Change position in current stack.
3973 stack.positionChildAt(task, position);
3974 } else {
3975 // Reparent to new stack.
3976 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3977 !DEFER_RESUME, "positionTaskInStack");
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983 }
3984
3985 @Override
3986 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3987 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3988 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003989 + Arrays.toString(horizontalSizeConfiguration) + " "
3990 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 synchronized (mGlobalLock) {
3992 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3993 if (record == null) {
3994 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3995 + "found for: " + token);
3996 }
3997 record.setSizeConfigurations(horizontalSizeConfiguration,
3998 verticalSizeConfigurations, smallestSizeConfigurations);
3999 }
4000 }
4001
4002 /**
4003 * Dismisses split-screen multi-window mode.
4004 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4005 */
4006 @Override
4007 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004008 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4010 final long ident = Binder.clearCallingIdentity();
4011 try {
4012 synchronized (mGlobalLock) {
4013 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004014 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 if (stack == null) {
4016 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4017 return;
4018 }
4019
4020 if (toTop) {
4021 // Caller wants the current split-screen primary stack to be the top stack after
4022 // it goes fullscreen, so move it to the front.
4023 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004024 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004026 // stack after it goes fullscreen, so we move the focus to the top-most
4027 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4029 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4030 if (otherStack != null) {
4031 otherStack.moveToFront("dismissSplitScreenMode_other");
4032 }
4033 }
4034
Evan Rosky10475742018-09-05 19:02:48 -07004035 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 }
4037 } finally {
4038 Binder.restoreCallingIdentity(ident);
4039 }
4040 }
4041
4042 /**
4043 * Dismisses Pip
4044 * @param animate True if the dismissal should be animated.
4045 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4046 * default animation duration should be used.
4047 */
4048 @Override
4049 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 final long ident = Binder.clearCallingIdentity();
4052 try {
4053 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004054 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004055 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 if (stack == null) {
4057 Slog.w(TAG, "dismissPip: pinned stack not found.");
4058 return;
4059 }
4060 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4061 throw new IllegalArgumentException("Stack: " + stack
4062 + " doesn't support animated resize.");
4063 }
4064 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004065 stack.animateResizePinnedStack(null /* destBounds */,
4066 null /* sourceHintBounds */, animationDuration,
4067 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004069 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 }
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(ident);
4074 }
4075 }
4076
4077 @Override
4078 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004079 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 synchronized (mGlobalLock) {
4081 mSuppressResizeConfigChanges = suppress;
4082 }
4083 }
4084
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 @Override
4086 // TODO: API should just be about changing windowing modes...
4087 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004088 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 "moveTasksToFullscreenStack()");
4090 synchronized (mGlobalLock) {
4091 final long origId = Binder.clearCallingIdentity();
4092 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004093 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 if (stack != null){
4095 if (!stack.isActivityTypeStandardOrUndefined()) {
4096 throw new IllegalArgumentException(
4097 "You can't move tasks from non-standard stacks.");
4098 }
4099 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4100 }
4101 } finally {
4102 Binder.restoreCallingIdentity(origId);
4103 }
4104 }
4105 }
4106
4107 /**
4108 * Moves the top activity in the input stackId to the pinned stack.
4109 *
4110 * @param stackId Id of stack to move the top activity to pinned stack.
4111 * @param bounds Bounds to use for pinned stack.
4112 *
4113 * @return True if the top activity of the input stack was successfully moved to the pinned
4114 * stack.
4115 */
4116 @Override
4117 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004118 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 "moveTopActivityToPinnedStack()");
4120 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4123 + "Device doesn't support picture-in-picture mode");
4124 }
4125
4126 long ident = Binder.clearCallingIdentity();
4127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004128 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 } finally {
4130 Binder.restoreCallingIdentity(ident);
4131 }
4132 }
4133 }
4134
4135 @Override
4136 public boolean isInMultiWindowMode(IBinder token) {
4137 final long origId = Binder.clearCallingIdentity();
4138 try {
4139 synchronized (mGlobalLock) {
4140 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4141 if (r == null) {
4142 return false;
4143 }
4144 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4145 return r.inMultiWindowMode();
4146 }
4147 } finally {
4148 Binder.restoreCallingIdentity(origId);
4149 }
4150 }
4151
4152 @Override
4153 public boolean isInPictureInPictureMode(IBinder token) {
4154 final long origId = Binder.clearCallingIdentity();
4155 try {
4156 synchronized (mGlobalLock) {
4157 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4158 }
4159 } finally {
4160 Binder.restoreCallingIdentity(origId);
4161 }
4162 }
4163
4164 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004165 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4166 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 return false;
4168 }
4169
4170 // If we are animating to fullscreen then we have already dispatched the PIP mode
4171 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004172 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004173 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175
4176 @Override
4177 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4178 final long origId = Binder.clearCallingIdentity();
4179 try {
4180 synchronized (mGlobalLock) {
4181 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4182 "enterPictureInPictureMode", token, params);
4183
4184 // If the activity is already in picture in picture mode, then just return early
4185 if (isInPictureInPictureMode(r)) {
4186 return true;
4187 }
4188
4189 // Activity supports picture-in-picture, now check that we can enter PiP at this
4190 // point, if it is
4191 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4192 false /* beforeStopping */)) {
4193 return false;
4194 }
4195
4196 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004197 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004198 if (r.getParent() == null) {
4199 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4200 return;
4201 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004202 // Only update the saved args from the args that are set
4203 r.pictureInPictureArgs.copyOnlySet(params);
4204 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4205 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4206 // Adjust the source bounds by the insets for the transition down
4207 final Rect sourceBounds = new Rect(
4208 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004209 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004210 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004211 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004212 stack.setPictureInPictureAspectRatio(aspectRatio);
4213 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004214 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4215 r.info.applicationInfo.uid, r.shortComponentName,
4216 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004217 logPictureInPictureArgs(params);
4218 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 };
4220
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004221 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 // If the keyguard is showing or occluded, then try and dismiss it before
4223 // entering picture-in-picture (this will prompt the user to authenticate if the
4224 // device is currently locked).
4225 dismissKeyguard(token, new KeyguardDismissCallback() {
4226 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004227 public void onDismissSucceeded() {
4228 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 }
4230 }, null /* message */);
4231 } else {
4232 // Enter picture in picture immediately otherwise
4233 enterPipRunnable.run();
4234 }
4235 return true;
4236 }
4237 } finally {
4238 Binder.restoreCallingIdentity(origId);
4239 }
4240 }
4241
4242 @Override
4243 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4244 final long origId = Binder.clearCallingIdentity();
4245 try {
4246 synchronized (mGlobalLock) {
4247 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4248 "setPictureInPictureParams", token, params);
4249
4250 // Only update the saved args from the args that are set
4251 r.pictureInPictureArgs.copyOnlySet(params);
4252 if (r.inPinnedWindowingMode()) {
4253 // If the activity is already in picture-in-picture, update the pinned stack now
4254 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4255 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004256 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 if (!stack.isAnimatingBoundsToFullscreen()) {
4258 stack.setPictureInPictureAspectRatio(
4259 r.pictureInPictureArgs.getAspectRatio());
4260 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4261 }
4262 }
4263 logPictureInPictureArgs(params);
4264 }
4265 } finally {
4266 Binder.restoreCallingIdentity(origId);
4267 }
4268 }
4269
4270 @Override
4271 public int getMaxNumPictureInPictureActions(IBinder token) {
4272 // Currently, this is a static constant, but later, we may change this to be dependent on
4273 // the context of the activity
4274 return 3;
4275 }
4276
4277 private void logPictureInPictureArgs(PictureInPictureParams params) {
4278 if (params.hasSetActions()) {
4279 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4280 params.getActions().size());
4281 }
4282 if (params.hasSetAspectRatio()) {
4283 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4284 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4285 MetricsLogger.action(lm);
4286 }
4287 }
4288
4289 /**
4290 * Checks the state of the system and the activity associated with the given {@param token} to
4291 * verify that picture-in-picture is supported for that activity.
4292 *
4293 * @return the activity record for the given {@param token} if all the checks pass.
4294 */
4295 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4296 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 throw new IllegalStateException(caller
4299 + ": Device doesn't support picture-in-picture mode.");
4300 }
4301
4302 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4303 if (r == null) {
4304 throw new IllegalStateException(caller
4305 + ": Can't find activity for token=" + token);
4306 }
4307
4308 if (!r.supportsPictureInPicture()) {
4309 throw new IllegalStateException(caller
4310 + ": Current activity does not support picture-in-picture.");
4311 }
4312
4313 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004314 && !mWindowManager.isValidPictureInPictureAspectRatio(
4315 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 final float minAspectRatio = mContext.getResources().getFloat(
4317 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4318 final float maxAspectRatio = mContext.getResources().getFloat(
4319 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4320 throw new IllegalArgumentException(String.format(caller
4321 + ": Aspect ratio is too extreme (must be between %f and %f).",
4322 minAspectRatio, maxAspectRatio));
4323 }
4324
4325 // Truncate the number of actions if necessary
4326 params.truncateActions(getMaxNumPictureInPictureActions(token));
4327
4328 return r;
4329 }
4330
4331 @Override
4332 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004333 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 synchronized (mGlobalLock) {
4335 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4336 if (r == null) {
4337 throw new IllegalArgumentException("Activity does not exist; token="
4338 + activityToken);
4339 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004340 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 }
4342 }
4343
4344 @Override
4345 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4346 Rect tempDockedTaskInsetBounds,
4347 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004348 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 long ident = Binder.clearCallingIdentity();
4350 try {
4351 synchronized (mGlobalLock) {
4352 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4353 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4354 PRESERVE_WINDOWS);
4355 }
4356 } finally {
4357 Binder.restoreCallingIdentity(ident);
4358 }
4359 }
4360
4361 @Override
4362 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 final long ident = Binder.clearCallingIdentity();
4365 try {
4366 synchronized (mGlobalLock) {
4367 mStackSupervisor.setSplitScreenResizing(resizing);
4368 }
4369 } finally {
4370 Binder.restoreCallingIdentity(ident);
4371 }
4372 }
4373
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 /**
4375 * Check that we have the features required for VR-related API calls, and throw an exception if
4376 * not.
4377 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004378 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 if (!mContext.getPackageManager().hasSystemFeature(
4380 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4381 throw new UnsupportedOperationException("VR mode not supported on this device!");
4382 }
4383 }
4384
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 @Override
4386 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388
4389 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4390
4391 ActivityRecord r;
4392 synchronized (mGlobalLock) {
4393 r = ActivityRecord.isInStackLocked(token);
4394 }
4395
4396 if (r == null) {
4397 throw new IllegalArgumentException();
4398 }
4399
4400 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004401 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 VrManagerInternal.NO_ERROR) {
4403 return err;
4404 }
4405
4406 // Clear the binder calling uid since this path may call moveToTask().
4407 final long callingId = Binder.clearCallingIdentity();
4408 try {
4409 synchronized (mGlobalLock) {
4410 r.requestedVrComponent = (enabled) ? packageName : null;
4411
4412 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004413 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004414 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416 return 0;
4417 }
4418 } finally {
4419 Binder.restoreCallingIdentity(callingId);
4420 }
4421 }
4422
4423 @Override
4424 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4425 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4426 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004427 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4429 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4430 }
Louis Changcdec0802019-11-11 11:45:07 +08004431 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 || activity.voiceSession != null) {
4433 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4434 return;
4435 }
4436 if (activity.pendingVoiceInteractionStart) {
4437 Slog.w(TAG, "Pending start of voice interaction already.");
4438 return;
4439 }
4440 activity.pendingVoiceInteractionStart = true;
4441 }
4442 LocalServices.getService(VoiceInteractionManagerInternal.class)
4443 .startLocalVoiceInteraction(callingActivity, options);
4444 }
4445
4446 @Override
4447 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4448 LocalServices.getService(VoiceInteractionManagerInternal.class)
4449 .stopLocalVoiceInteraction(callingActivity);
4450 }
4451
4452 @Override
4453 public boolean supportsLocalVoiceInteraction() {
4454 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4455 .supportsLocalVoiceInteraction();
4456 }
4457
4458 /** Notifies all listeners when the pinned stack animation starts. */
4459 @Override
4460 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004461 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 }
4463
4464 /** Notifies all listeners when the pinned stack animation ends. */
4465 @Override
4466 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004467 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 }
4469
4470 @Override
4471 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 final long ident = Binder.clearCallingIdentity();
4474 try {
4475 synchronized (mGlobalLock) {
4476 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4477 }
4478 } finally {
4479 Binder.restoreCallingIdentity(ident);
4480 }
4481 }
4482
4483 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004485 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486
4487 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004488 if (mWindowManager == null) {
4489 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4490 return false;
4491 }
4492
4493 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 }
4497
Riddle Hsua0022cd2019-09-09 21:12:41 +08004498 mH.sendMessage(PooledLambda.obtainMessage(
4499 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4500 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501
4502 final long origId = Binder.clearCallingIdentity();
4503 try {
4504 if (values != null) {
4505 Settings.System.clearConfiguration(values);
4506 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 UserHandle.USER_NULL, false /* deferResume */,
4509 mTmpUpdateConfigurationResult);
4510 return mTmpUpdateConfigurationResult.changes != 0;
4511 } finally {
4512 Binder.restoreCallingIdentity(origId);
4513 }
4514 }
4515 }
4516
4517 @Override
4518 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4519 CharSequence message) {
4520 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4523 }
4524 final long callingId = Binder.clearCallingIdentity();
4525 try {
4526 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004527 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528 }
4529 } finally {
4530 Binder.restoreCallingIdentity(callingId);
4531 }
4532 }
4533
4534 @Override
4535 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004536 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 "cancelTaskWindowTransition()");
4538 final long ident = Binder.clearCallingIdentity();
4539 try {
4540 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004541 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 MATCH_TASK_IN_STACKS_ONLY);
4543 if (task == null) {
4544 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4545 return;
4546 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004547 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 }
4549 } finally {
4550 Binder.restoreCallingIdentity(ident);
4551 }
4552 }
4553
4554 @Override
4555 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 final long ident = Binder.clearCallingIdentity();
4558 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004559 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004560 } finally {
4561 Binder.restoreCallingIdentity(ident);
4562 }
4563 }
4564
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004565 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4566 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004567 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004568 synchronized (mGlobalLock) {
4569 task = mRootActivityContainer.anyTaskForId(taskId,
4570 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4571 if (task == null) {
4572 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4573 return null;
4574 }
4575 }
4576 // Don't call this while holding the lock as this operation might hit the disk.
4577 return task.getSnapshot(reducedResolution, restoreFromDisk);
4578 }
4579
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 @Override
4581 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4582 synchronized (mGlobalLock) {
4583 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4584 if (r == null) {
4585 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4586 + token);
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.setDisablePreviewScreenshots(disable);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
Riddle Hsu440f88b2019-11-06 22:17:35 +08004598 @Override
4599 public void invalidateHomeTaskSnapshot(IBinder token) {
4600 synchronized (mGlobalLock) {
4601 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4602 if (r == null || !r.isActivityTypeHome()) {
4603 return;
4604 }
4605 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4606 }
4607 }
4608
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 /** Return the user id of the last resumed activity. */
4610 @Override
4611 public @UserIdInt
4612 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004613 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004614 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4615 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004616 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004617 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004619 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004620 }
4621 }
4622
4623 @Override
4624 public void updateLockTaskFeatures(int userId, int flags) {
4625 final int callingUid = Binder.getCallingUid();
4626 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "updateLockTaskFeatures()");
4629 }
4630 synchronized (mGlobalLock) {
4631 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4632 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004633 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004634 }
4635 }
4636
4637 @Override
4638 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4639 synchronized (mGlobalLock) {
4640 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4641 if (r == null) {
4642 return;
4643 }
4644 final long origId = Binder.clearCallingIdentity();
4645 try {
4646 r.setShowWhenLocked(showWhenLocked);
4647 } finally {
4648 Binder.restoreCallingIdentity(origId);
4649 }
4650 }
4651 }
4652
4653 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004654 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4655 synchronized (mGlobalLock) {
4656 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4657 if (r == null) {
4658 return;
4659 }
4660 final long origId = Binder.clearCallingIdentity();
4661 try {
4662 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4663 } finally {
4664 Binder.restoreCallingIdentity(origId);
4665 }
4666 }
4667 }
4668
4669 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004670 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4671 synchronized (mGlobalLock) {
4672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4673 if (r == null) {
4674 return;
4675 }
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
4678 r.setTurnScreenOn(turnScreenOn);
4679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
4684
4685 @Override
4686 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004689 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004690 synchronized (mGlobalLock) {
4691 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4692 if (r == null) {
4693 return;
4694 }
4695 final long origId = Binder.clearCallingIdentity();
4696 try {
4697 r.registerRemoteAnimations(definition);
4698 } finally {
4699 Binder.restoreCallingIdentity(origId);
4700 }
4701 }
4702 }
4703
4704 @Override
4705 public void registerRemoteAnimationForNextActivityStart(String packageName,
4706 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004708 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004709 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004710 synchronized (mGlobalLock) {
4711 final long origId = Binder.clearCallingIdentity();
4712 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004713 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004714 packageName, adapter);
4715 } finally {
4716 Binder.restoreCallingIdentity(origId);
4717 }
4718 }
4719 }
4720
Evan Rosky966759f2019-01-15 10:33:58 -08004721 @Override
4722 public void registerRemoteAnimationsForDisplay(int displayId,
4723 RemoteAnimationDefinition definition) {
4724 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4725 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004726 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004727 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08004728 final DisplayContent display = mRootActivityContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004729 if (display == null) {
4730 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4731 return;
4732 }
4733 final long origId = Binder.clearCallingIdentity();
4734 try {
4735 display.mDisplayContent.registerRemoteAnimations(definition);
4736 } finally {
4737 Binder.restoreCallingIdentity(origId);
4738 }
4739 }
4740 }
4741
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004742 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4743 @Override
4744 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4745 synchronized (mGlobalLock) {
4746 final long origId = Binder.clearCallingIdentity();
4747 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004748 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004749 } finally {
4750 Binder.restoreCallingIdentity(origId);
4751 }
4752 }
4753 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004754
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004755 @Override
4756 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004758 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004759 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004760 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004761 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004762 }
4763 }
4764
4765 @Override
4766 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004767 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 != PERMISSION_GRANTED) {
4769 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4770 + Binder.getCallingPid()
4771 + ", uid=" + Binder.getCallingUid()
4772 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4773 Slog.w(TAG, msg);
4774 throw new SecurityException(msg);
4775 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004776 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004777 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004778 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004779 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004780 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 }
4782 }
4783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 @Override
4785 public void stopAppSwitches() {
4786 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4787 synchronized (mGlobalLock) {
4788 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004789 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004790 mDidAppSwitch = false;
4791 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4792 }
4793 }
4794
4795 @Override
4796 public void resumeAppSwitches() {
4797 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4798 synchronized (mGlobalLock) {
4799 // Note that we don't execute any pending app switches... we will
4800 // let those wait until either the timeout, or the next start
4801 // activity request.
4802 mAppSwitchesAllowedTime = 0;
4803 }
4804 }
4805
Ricky Wai906af482019-06-03 17:25:28 +01004806 long getLastStopAppSwitchesTime() {
4807 return mLastStopAppSwitchesTime;
4808 }
4809
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004810 void onStartActivitySetDidAppSwitch() {
4811 if (mDidAppSwitch) {
4812 // This is the second allowed switch since we stopped switches, so now just generally
4813 // allow switches. Use case:
4814 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4815 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4816 // anyone to switch again).
4817 mAppSwitchesAllowedTime = 0;
4818 } else {
4819 mDidAppSwitch = true;
4820 }
4821 }
4822
4823 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004824 boolean shouldDisableNonVrUiLocked() {
4825 return mVrController.shouldDisableNonVrUiLocked();
4826 }
4827
Wale Ogunwale53783742018-09-16 10:21:51 -07004828 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004829 // 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 +00004830 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004831 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004832 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4833 + " to main display for VR");
4834 mRootActivityContainer.moveStackToDisplay(
4835 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004836 }
4837 mH.post(() -> {
4838 if (!mVrController.onVrModeChanged(r)) {
4839 return;
4840 }
4841 synchronized (mGlobalLock) {
4842 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4843 mWindowManager.disableNonVrUi(disableNonVrUi);
4844 if (disableNonVrUi) {
4845 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4846 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004847 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004848 }
4849 }
4850 });
4851 }
4852
Wale Ogunwale53783742018-09-16 10:21:51 -07004853 @Override
4854 public int getPackageScreenCompatMode(String packageName) {
4855 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4856 synchronized (mGlobalLock) {
4857 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4858 }
4859 }
4860
4861 @Override
4862 public void setPackageScreenCompatMode(String packageName, int mode) {
4863 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4864 "setPackageScreenCompatMode");
4865 synchronized (mGlobalLock) {
4866 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4867 }
4868 }
4869
4870 @Override
4871 public boolean getPackageAskScreenCompat(String packageName) {
4872 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4873 synchronized (mGlobalLock) {
4874 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4875 }
4876 }
4877
4878 @Override
4879 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4880 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4881 "setPackageAskScreenCompat");
4882 synchronized (mGlobalLock) {
4883 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4884 }
4885 }
4886
Wale Ogunwale64258362018-10-16 15:13:37 -07004887 public static String relaunchReasonToString(int relaunchReason) {
4888 switch (relaunchReason) {
4889 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4890 return "window_resize";
4891 case RELAUNCH_REASON_FREE_RESIZE:
4892 return "free_resize";
4893 default:
4894 return null;
4895 }
4896 }
4897
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004898 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004899 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004900 }
4901
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004902 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004903 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004904 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4905 }
4906
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004907 boolean isKeyguardLocked() {
4908 return mKeyguardController.isKeyguardLocked();
4909 }
4910
Garfield Tan01548632018-11-27 10:15:48 -08004911 /**
4912 * Clears launch params for the given package.
4913 * @param packageNames the names of the packages of which the launch params are to be cleared
4914 */
4915 @Override
4916 public void clearLaunchParamsForPackages(List<String> packageNames) {
4917 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4918 "clearLaunchParamsForPackages");
4919 synchronized (mGlobalLock) {
4920 for (int i = 0; i < packageNames.size(); ++i) {
4921 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4922 }
4923 }
4924 }
4925
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004926 /**
4927 * Makes the display with the given id a single task instance display. I.e the display can only
4928 * contain one task.
4929 */
4930 @Override
4931 public void setDisplayToSingleTaskInstance(int displayId) {
4932 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4933 "setDisplayToSingleTaskInstance");
4934 final long origId = Binder.clearCallingIdentity();
4935 try {
Louis Chang677921f2019-12-06 16:44:24 +08004936 final DisplayContent display =
4937 mRootActivityContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004938 if (display != null) {
4939 display.setDisplayToSingleTaskInstance();
4940 }
4941 } finally {
4942 Binder.restoreCallingIdentity(origId);
4943 }
4944 }
4945
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004946 /**
4947 * Requests that an activity should enter picture-in-picture mode if possible.
4948 */
4949 @Override
4950 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4951 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4952 "requestPictureInPictureMode");
4953 final long origId = Binder.clearCallingIdentity();
4954 try {
4955 synchronized (mGlobalLock) {
4956 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4957 if (activity == null) {
4958 return;
4959 }
4960
4961 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4962 "requestPictureInPictureMode", /* beforeStopping */ false);
4963 if (!canEnterPictureInPicture) {
4964 throw new IllegalStateException(
4965 "Requested PIP on an activity that doesn't support it");
4966 }
4967
4968 try {
4969 final ClientTransaction transaction = ClientTransaction.obtain(
4970 activity.app.getThread(),
4971 activity.token);
4972 transaction.addCallback(EnterPipRequestedItem.obtain());
4973 getLifecycleManager().scheduleTransaction(transaction);
4974 } catch (Exception e) {
4975 Slog.w(TAG, "Failed to send enter pip requested item: "
4976 + activity.intent.getComponent(), e);
4977 }
4978 }
4979 } finally {
4980 Binder.restoreCallingIdentity(origId);
4981 }
4982 }
4983
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 void dumpLastANRLocked(PrintWriter pw) {
4985 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4986 if (mLastANRState == null) {
4987 pw.println(" <no ANR has occurred since boot>");
4988 } else {
4989 pw.println(mLastANRState);
4990 }
4991 }
4992
4993 void dumpLastANRTracesLocked(PrintWriter pw) {
4994 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4995
4996 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4997 if (ArrayUtils.isEmpty(files)) {
4998 pw.println(" <no ANR has occurred since boot>");
4999 return;
5000 }
5001 // Find the latest file.
5002 File latest = null;
5003 for (File f : files) {
5004 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5005 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005006 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005007 }
5008 pw.print("File: ");
5009 pw.print(latest.getName());
5010 pw.println();
5011 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5012 String line;
5013 while ((line = in.readLine()) != null) {
5014 pw.println(line);
5015 }
5016 } catch (IOException e) {
5017 pw.print("Unable to read: ");
5018 pw.print(e);
5019 pw.println();
5020 }
5021 }
5022
5023 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5024 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5025 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5026 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5027 }
5028
5029 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5030 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5031 pw.println(header);
5032
Wale Ogunwaled32da472018-11-16 07:19:28 -08005033 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005034 dumpPackage);
5035 boolean needSep = printedAnything;
5036
5037 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08005038 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 " ResumedActivity: ");
5040 if (printed) {
5041 printedAnything = true;
5042 needSep = false;
5043 }
5044
5045 if (dumpPackage == null) {
5046 if (needSep) {
5047 pw.println();
5048 }
5049 printedAnything = true;
5050 mStackSupervisor.dump(pw, " ");
5051 }
5052
5053 if (!printedAnything) {
5054 pw.println(" (nothing)");
5055 }
5056 }
5057
5058 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005059 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08005060 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005061 pw.println(" ");
5062 }
5063
5064 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5065 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5066 getActivityStartController().dump(pw, "", dumpPackage);
5067 }
5068
5069 /**
5070 * There are three things that cmd can be:
5071 * - a flattened component name that matches an existing activity
5072 * - the cmd arg isn't the flattened component name of an existing activity:
5073 * dump all activity whose component contains the cmd as a substring
5074 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005075 * <p>
5076 * The caller should not hold lock when calling this method because it will wait for the
5077 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005078 *
5079 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5080 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5081 */
5082 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5083 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5084 ArrayList<ActivityRecord> activities;
5085
5086 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005087 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005088 dumpFocusedStackOnly);
5089 }
5090
5091 if (activities.size() <= 0) {
5092 return false;
5093 }
5094
5095 String[] newArgs = new String[args.length - opti];
5096 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5097
Louis Changcdec0802019-11-11 11:45:07 +08005098 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005099 boolean needSep = false;
5100 for (int i = activities.size() - 1; i >= 0; i--) {
5101 ActivityRecord r = activities.get(i);
5102 if (needSep) {
5103 pw.println();
5104 }
5105 needSep = true;
5106 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005107 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005108 if (lastTask != task) {
5109 lastTask = task;
5110 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005111 pw.print(" id="); pw.print(lastTask.mTaskId);
5112 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005113 if (dumpAll) {
5114 lastTask.dump(pw, " ");
5115 }
5116 }
5117 }
5118 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5119 }
5120 return true;
5121 }
5122
5123 /**
5124 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5125 * there is a thread associated with the activity.
5126 */
5127 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5128 final ActivityRecord r, String[] args, boolean dumpAll) {
5129 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005130 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005131 synchronized (mGlobalLock) {
5132 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5133 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5134 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005135 if (r.hasProcess()) {
5136 pw.println(r.app.getPid());
5137 appThread = r.app.getThread();
5138 } else {
5139 pw.println("(not running)");
5140 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005141 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005142 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005143 }
5144 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005145 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005146 // flush anything that is already in the PrintWriter since the thread is going
5147 // to write to the file descriptor directly
5148 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005149 try (TransferPipe tp = new TransferPipe()) {
5150 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5151 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005152 } catch (IOException e) {
5153 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5154 } catch (RemoteException e) {
5155 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5156 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005157 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005158 }
5159
sanryhuang498e77e2018-12-06 14:57:01 +08005160 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5161 boolean testPssMode) {
5162 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5163 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5164 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005165 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005166 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5167 st.toString());
5168 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005169 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5170 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5171 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005172 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5173 testPssMode);
5174 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005175 }
5176
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 int getCurrentUserId() {
5178 return mAmInternal.getCurrentUserId();
5179 }
5180
5181 private void enforceNotIsolatedCaller(String caller) {
5182 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5183 throw new SecurityException("Isolated process not allowed to call " + caller);
5184 }
5185 }
5186
Wale Ogunwalef6733932018-06-27 05:14:34 -07005187 public Configuration getConfiguration() {
5188 Configuration ci;
5189 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005190 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005191 ci.userSetLocale = false;
5192 }
5193 return ci;
5194 }
5195
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196 /**
5197 * Current global configuration information. Contains general settings for the entire system,
5198 * also corresponds to the merged configuration of the default display.
5199 */
5200 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005201 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202 }
5203
5204 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5205 boolean initLocale) {
5206 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5207 }
5208
5209 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5210 boolean initLocale, boolean deferResume) {
5211 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5212 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5213 UserHandle.USER_NULL, deferResume);
5214 }
5215
Wale Ogunwale59507092018-10-29 09:00:30 -07005216 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005217 final long origId = Binder.clearCallingIdentity();
5218 try {
5219 synchronized (mGlobalLock) {
5220 updateConfigurationLocked(values, null, false, true, userId,
5221 false /* deferResume */);
5222 }
5223 } finally {
5224 Binder.restoreCallingIdentity(origId);
5225 }
5226 }
5227
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5229 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5230 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5231 deferResume, null /* result */);
5232 }
5233
5234 /**
5235 * Do either or both things: (1) change the current configuration, and (2)
5236 * make sure the given activity is running with the (now) current
5237 * configuration. Returns true if the activity has been left running, or
5238 * false if <var>starting</var> is being destroyed to match the new
5239 * configuration.
5240 *
5241 * @param userId is only used when persistent parameter is set to true to persist configuration
5242 * for that particular user
5243 */
5244 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5245 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5246 ActivityTaskManagerService.UpdateConfigurationResult result) {
5247 int changes = 0;
5248 boolean kept = true;
5249
Riddle Hsua0022cd2019-09-09 21:12:41 +08005250 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 try {
5252 if (values != null) {
5253 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5254 deferResume);
5255 }
5256
5257 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5258 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005259 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260 }
5261
5262 if (result != null) {
5263 result.changes = changes;
5264 result.activityRelaunched = !kept;
5265 }
5266 return kept;
5267 }
5268
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005270 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005272
Louis Chang677921f2019-12-06 16:44:24 +08005273 final DisplayContent defaultDisplay =
5274 mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276 mTempConfig.setTo(getGlobalConfiguration());
5277 final int changes = mTempConfig.updateFrom(values);
5278 if (changes == 0) {
5279 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5280 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5281 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5282 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005283 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284 return 0;
5285 }
5286
5287 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5288 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005289 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5291 values.colorMode,
5292 values.densityDpi,
5293 values.fontScale,
5294 values.hardKeyboardHidden,
5295 values.keyboard,
5296 values.keyboardHidden,
5297 values.mcc,
5298 values.mnc,
5299 values.navigation,
5300 values.navigationHidden,
5301 values.orientation,
5302 values.screenHeightDp,
5303 values.screenLayout,
5304 values.screenWidthDp,
5305 values.smallestScreenWidthDp,
5306 values.touchscreen,
5307 values.uiMode);
5308
5309
5310 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5311 final LocaleList locales = values.getLocales();
5312 int bestLocaleIndex = 0;
5313 if (locales.size() > 1) {
5314 if (mSupportedSystemLocales == null) {
5315 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5316 }
5317 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5318 }
5319 SystemProperties.set("persist.sys.locale",
5320 locales.get(bestLocaleIndex).toLanguageTag());
5321 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005322
5323 final Message m = PooledLambda.obtainMessage(
5324 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5325 locales.get(bestLocaleIndex));
5326 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005327 }
5328
Yunfan Chen75157d72018-07-27 14:47:21 +09005329 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005330
5331 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005332 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333
5334 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5335 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005336 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
5338 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005339 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005340
5341 AttributeCache ac = AttributeCache.instance();
5342 if (ac != null) {
5343 ac.updateConfiguration(mTempConfig);
5344 }
5345
5346 // Make sure all resources in our process are updated right now, so that anyone who is going
5347 // to retrieve resource values after we return will be sure to get the new ones. This is
5348 // especially important during boot, where the first config change needs to guarantee all
5349 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005350 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 // We need another copy of global config because we're scheduling some calls instead of
5353 // running them in place. We need to be sure that object we send will be handled unchanged.
5354 final Configuration configCopy = new Configuration(mTempConfig);
5355 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005356 final Message msg = PooledLambda.obtainMessage(
5357 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5358 this, userId, configCopy);
5359 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005360 }
5361
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005362 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5363 for (int i = pidMap.size() - 1; i >= 0; i--) {
5364 final int pid = pidMap.keyAt(i);
5365 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005366 if (DEBUG_CONFIGURATION) {
5367 Slog.v(TAG_CONFIGURATION, "Update process config of "
5368 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005370 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005371 }
5372
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005373 final Message msg = PooledLambda.obtainMessage(
5374 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5375 mAmInternal, changes, initLocale);
5376 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005377
5378 // Override configuration of the default display duplicates global config, so we need to
5379 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005380 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5381 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382
5383 return changes;
5384 }
5385
Riddle Hsua0022cd2019-09-09 21:12:41 +08005386 /** @see WindowSurfacePlacer#deferLayout */
5387 void deferWindowLayout() {
5388 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5389 // Reset the reasons at the first entrance because we only care about the changes in the
5390 // deferred scope.
5391 mLayoutReasons = 0;
5392 }
5393
5394 mWindowManager.mWindowPlacerLocked.deferLayout();
5395 }
5396
5397 /** @see WindowSurfacePlacer#continueLayout */
5398 void continueWindowLayout() {
5399 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5400 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5401 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5402 }
5403 }
5404
5405 /**
5406 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5407 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5408 * defer count is gone.
5409 */
5410 void addWindowLayoutReasons(@LayoutReason int reasons) {
5411 mLayoutReasons |= reasons;
5412 }
5413
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 private void updateEventDispatchingLocked(boolean booted) {
5415 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5416 }
5417
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005418 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5419 final ContentResolver resolver = mContext.getContentResolver();
5420 Settings.System.putConfigurationForUser(resolver, config, userId);
5421 }
5422
5423 private void sendLocaleToMountDaemonMsg(Locale l) {
5424 try {
5425 IBinder service = ServiceManager.getService("mount");
5426 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5427 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5428 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5429 } catch (RemoteException e) {
5430 Log.e(TAG, "Error storing locale for decryption UI", e);
5431 }
5432 }
5433
Alison Cichowlas3e340502018-08-07 17:15:01 -04005434 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5435 mStartActivitySources.remove(permissionToken);
5436 mExpiredStartAsCallerTokens.add(permissionToken);
5437 }
5438
5439 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5440 mExpiredStartAsCallerTokens.remove(permissionToken);
5441 }
5442
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005443 boolean isActivityStartsLoggingEnabled() {
5444 return mAmInternal.isActivityStartsLoggingEnabled();
5445 }
5446
Michal Karpinski8596ded2018-11-14 14:43:48 +00005447 boolean isBackgroundActivityStartsEnabled() {
5448 return mAmInternal.isBackgroundActivityStartsEnabled();
5449 }
5450
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005452 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005453 mWindowManager.enableScreenAfterBoot();
5454
5455 synchronized (mGlobalLock) {
5456 updateEventDispatchingLocked(booted);
5457 }
5458 }
5459
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005460 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5461 if (r == null || !r.hasProcess()) {
5462 return KEY_DISPATCHING_TIMEOUT_MS;
5463 }
5464 return getInputDispatchingTimeoutLocked(r.app);
5465 }
5466
5467 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005468 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005469 }
5470
Wale Ogunwalef6733932018-06-27 05:14:34 -07005471 /**
5472 * Decide based on the configuration whether we should show the ANR,
5473 * crash, etc dialogs. The idea is that if there is no affordance to
5474 * press the on-screen buttons, or the user experience would be more
5475 * greatly impacted than the crash itself, we shouldn't show the dialog.
5476 *
5477 * A thought: SystemUI might also want to get told about this, the Power
5478 * dialog / global actions also might want different behaviors.
5479 */
5480 private void updateShouldShowDialogsLocked(Configuration config) {
5481 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5482 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5483 && config.navigation == Configuration.NAVIGATION_NONAV);
5484 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5485 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5486 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5487 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5488 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5489 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5490 HIDE_ERROR_DIALOGS, 0) != 0;
5491 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5492 }
5493
5494 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5495 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5496 FONT_SCALE, 1.0f, userId);
5497
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499 if (getGlobalConfiguration().fontScale == scaleFactor) {
5500 return;
5501 }
5502
5503 final Configuration configuration
5504 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5505 configuration.fontScale = scaleFactor;
5506 updatePersistentConfiguration(configuration, userId);
5507 }
5508 }
5509
5510 // Actually is sleeping or shutting down or whatever else in the future
5511 // is an inactive state.
5512 boolean isSleepingOrShuttingDownLocked() {
5513 return isSleepingLocked() || mShuttingDown;
5514 }
5515
5516 boolean isSleepingLocked() {
5517 return mSleeping;
5518 }
5519
Riddle Hsu16567132018-08-16 21:37:47 +08005520 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005522 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005523 if (task.isActivityTypeStandard()) {
5524 if (mCurAppTimeTracker != r.appTimeTracker) {
5525 // We are switching app tracking. Complete the current one.
5526 if (mCurAppTimeTracker != null) {
5527 mCurAppTimeTracker.stop();
5528 mH.obtainMessage(
5529 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005530 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005531 mCurAppTimeTracker = null;
5532 }
5533 if (r.appTimeTracker != null) {
5534 mCurAppTimeTracker = r.appTimeTracker;
5535 startTimeTrackingFocusedActivityLocked();
5536 }
5537 } else {
5538 startTimeTrackingFocusedActivityLocked();
5539 }
5540 } else {
5541 r.appTimeTracker = null;
5542 }
5543 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5544 // TODO: Probably not, because we don't want to resume voice on switching
5545 // back to this activity
5546 if (task.voiceInteractor != null) {
5547 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5548 } else {
5549 finishRunningVoiceLocked();
5550
5551 if (mLastResumedActivity != null) {
5552 final IVoiceInteractionSession session;
5553
Louis Changcdec0802019-11-11 11:45:07 +08005554 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005555 if (lastResumedActivityTask != null
5556 && lastResumedActivityTask.voiceSession != null) {
5557 session = lastResumedActivityTask.voiceSession;
5558 } else {
5559 session = mLastResumedActivity.voiceSession;
5560 }
5561
5562 if (session != null) {
5563 // We had been in a voice interaction session, but now focused has
5564 // move to something different. Just finish the session, we can't
5565 // return to it and retain the proper state and synchronization with
5566 // the voice interaction service.
5567 finishVoiceTask(session);
5568 }
5569 }
5570 }
5571
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005572 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5573 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 }
5575 updateResumedAppTrace(r);
5576 mLastResumedActivity = r;
5577
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005578 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579
5580 applyUpdateLockStateLocked(r);
5581 applyUpdateVrModeLocked(r);
5582
Jeff Changd136e772019-11-05 20:33:52 +08005583 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005584 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 r == null ? "NULL" : r.shortComponentName,
5586 reason);
5587 }
5588
5589 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5590 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005591 final ActivityTaskManagerInternal.SleepToken token =
5592 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005593 updateSleepIfNeededLocked();
5594 return token;
5595 }
5596 }
5597
5598 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005599 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 final boolean wasSleeping = mSleeping;
5601 boolean updateOomAdj = false;
5602
5603 if (!shouldSleep) {
5604 // If wasSleeping is true, we need to wake up activity manager state from when
5605 // we started sleeping. In either case, we need to apply the sleep tokens, which
5606 // will wake up stacks or put them to sleep as appropriate.
5607 if (wasSleeping) {
5608 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005609 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5610 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 startTimeTrackingFocusedActivityLocked();
5612 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005613 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005614 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5615 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005616 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005617 if (wasSleeping) {
5618 updateOomAdj = true;
5619 }
5620 } else if (!mSleeping && shouldSleep) {
5621 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005622 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5623 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624 if (mCurAppTimeTracker != null) {
5625 mCurAppTimeTracker.stop();
5626 }
5627 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005628 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005629 mStackSupervisor.goingToSleepLocked();
5630 updateResumedAppTrace(null /* resumed */);
5631 updateOomAdj = true;
5632 }
5633 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005634 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005635 }
5636 }
5637
5638 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005639 mH.removeCallbacks(mUpdateOomAdjRunnable);
5640 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005641 }
5642
Wale Ogunwale53783742018-09-16 10:21:51 -07005643 void updateCpuStats() {
5644 mH.post(mAmInternal::updateCpuStats);
5645 }
5646
Hui Yu03d12402018-12-06 18:00:37 -08005647 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5648 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005649 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5650 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005651 mH.sendMessage(m);
5652 }
5653
Hui Yu03d12402018-12-06 18:00:37 -08005654 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005655 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005656 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005657 if (task != null) {
5658 final ActivityRecord rootActivity = task.getRootActivity();
5659 if (rootActivity != null) {
5660 taskRoot = rootActivity.mActivityComponent;
5661 }
5662 }
5663
Hui Yu03d12402018-12-06 18:00:37 -08005664 final Message m = PooledLambda.obtainMessage(
5665 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005666 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005667 mH.sendMessage(m);
5668 }
5669
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005670 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5671 String hostingType) {
5672 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005673 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5674 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005675 + activity.processName);
5676 }
5677 // Post message to start process to avoid possible deadlock of calling into AMS with the
5678 // ATMS lock held.
5679 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5680 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5681 isTop, hostingType, activity.intent.getComponent());
5682 mH.sendMessage(m);
5683 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005684 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005685 }
5686 }
5687
Wale Ogunwale53783742018-09-16 10:21:51 -07005688 void setBooting(boolean booting) {
5689 mAmInternal.setBooting(booting);
5690 }
5691
5692 boolean isBooting() {
5693 return mAmInternal.isBooting();
5694 }
5695
5696 void setBooted(boolean booted) {
5697 mAmInternal.setBooted(booted);
5698 }
5699
5700 boolean isBooted() {
5701 return mAmInternal.isBooted();
5702 }
5703
5704 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5705 mH.post(() -> {
5706 if (finishBooting) {
5707 mAmInternal.finishBooting();
5708 }
5709 if (enableScreen) {
5710 mInternal.enableScreenAfterBoot(isBooted());
5711 }
5712 });
5713 }
5714
5715 void setHeavyWeightProcess(ActivityRecord root) {
5716 mHeavyWeightProcess = root.app;
5717 final Message m = PooledLambda.obtainMessage(
5718 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005719 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005720 mH.sendMessage(m);
5721 }
5722
5723 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5724 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5725 return;
5726 }
5727
5728 mHeavyWeightProcess = null;
5729 final Message m = PooledLambda.obtainMessage(
5730 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5731 proc.mUserId);
5732 mH.sendMessage(m);
5733 }
5734
5735 private void cancelHeavyWeightProcessNotification(int userId) {
5736 final INotificationManager inm = NotificationManager.getService();
5737 if (inm == null) {
5738 return;
5739 }
5740 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005741 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005742 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5743 } catch (RuntimeException e) {
5744 Slog.w(TAG, "Error canceling notification for service", e);
5745 } catch (RemoteException e) {
5746 }
5747
5748 }
5749
5750 private void postHeavyWeightProcessNotification(
5751 WindowProcessController proc, Intent intent, int userId) {
5752 if (proc == null) {
5753 return;
5754 }
5755
5756 final INotificationManager inm = NotificationManager.getService();
5757 if (inm == null) {
5758 return;
5759 }
5760
5761 try {
5762 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5763 String text = mContext.getString(R.string.heavy_weight_notification,
5764 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5765 Notification notification =
5766 new Notification.Builder(context,
5767 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5768 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5769 .setWhen(0)
5770 .setOngoing(true)
5771 .setTicker(text)
5772 .setColor(mContext.getColor(
5773 com.android.internal.R.color.system_notification_accent_color))
5774 .setContentTitle(text)
5775 .setContentText(
5776 mContext.getText(R.string.heavy_weight_notification_detail))
5777 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5778 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5779 new UserHandle(userId)))
5780 .build();
5781 try {
5782 inm.enqueueNotificationWithTag("android", "android", null,
5783 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5784 } catch (RuntimeException e) {
5785 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5786 } catch (RemoteException e) {
5787 }
5788 } catch (PackageManager.NameNotFoundException e) {
5789 Slog.w(TAG, "Unable to create context for heavy notification", e);
5790 }
5791
5792 }
5793
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005794 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5795 IBinder token, String resultWho, int requestCode, Intent[] intents,
5796 String[] resolvedTypes, int flags, Bundle bOptions) {
5797
5798 ActivityRecord activity = null;
5799 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5800 activity = ActivityRecord.isInStackLocked(token);
5801 if (activity == null) {
5802 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5803 return null;
5804 }
5805 if (activity.finishing) {
5806 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5807 return null;
5808 }
5809 }
5810
5811 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5812 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5813 bOptions);
5814 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5815 if (noCreate) {
5816 return rec;
5817 }
5818 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5819 if (activity.pendingResults == null) {
5820 activity.pendingResults = new HashSet<>();
5821 }
5822 activity.pendingResults.add(rec.ref);
5823 }
5824 return rec;
5825 }
5826
Andrii Kulian52d255c2018-07-13 11:32:19 -07005827 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005828 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005829 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005830 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5831 mCurAppTimeTracker.start(resumedActivity.packageName);
5832 }
5833 }
5834
5835 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5836 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005837 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005838 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5839 }
5840 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005841 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005842 constructResumedTraceName(resumed.packageName), 0);
5843 }
5844 mTracedResumedActivity = resumed;
5845 }
5846
5847 private String constructResumedTraceName(String packageName) {
5848 return "focused app: " + packageName;
5849 }
5850
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005851 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005852 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005853 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005854 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005855 // mainStack is null during startup.
5856 if (mainStack != null) {
5857 if (changes != 0 && starting == null) {
5858 // If the configuration changed, and the caller is not already
5859 // in the process of starting an activity, then find the top
5860 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005861 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005862 }
5863
5864 if (starting != null) {
5865 kept = starting.ensureActivityConfiguration(changes,
5866 false /* preserveWindow */);
5867 // And we need to make sure at this point that all other activities
5868 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005869 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005870 !PRESERVE_WINDOWS);
5871 }
5872 }
5873
5874 return kept;
5875 }
5876
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005877 void scheduleAppGcsLocked() {
5878 mH.post(() -> mAmInternal.scheduleAppGcs());
5879 }
5880
Wale Ogunwale53783742018-09-16 10:21:51 -07005881 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5882 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5883 }
5884
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005885 /**
5886 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5887 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5888 * on demand.
5889 */
5890 IPackageManager getPackageManager() {
5891 return AppGlobals.getPackageManager();
5892 }
5893
5894 PackageManagerInternal getPackageManagerInternalLocked() {
5895 if (mPmInternal == null) {
5896 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5897 }
5898 return mPmInternal;
5899 }
5900
Hai Zhangf4da9be2019-05-01 13:46:06 +08005901 PermissionPolicyInternal getPermissionPolicyInternal() {
5902 if (mPermissionPolicyInternal == null) {
5903 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5904 }
5905 return mPermissionPolicyInternal;
5906 }
5907
Wale Ogunwale008163e2018-07-23 23:11:08 -07005908 AppWarnings getAppWarningsLocked() {
5909 return mAppWarnings;
5910 }
5911
Wale Ogunwale214f3482018-10-04 11:00:47 -07005912 Intent getHomeIntent() {
5913 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5914 intent.setComponent(mTopComponent);
5915 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5916 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5917 intent.addCategory(Intent.CATEGORY_HOME);
5918 }
5919 return intent;
5920 }
5921
Chilun2ef71f72018-11-16 17:57:15 +08005922 /**
5923 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5924 * activities.
5925 *
5926 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5927 * component defined in config_secondaryHomeComponent.
5928 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5929 */
5930 Intent getSecondaryHomeIntent(String preferredPackage) {
5931 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005932 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5933 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5934 if (preferredPackage == null || useSystemProvidedLauncher) {
5935 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005936 final String secondaryHomeComponent = mContext.getResources().getString(
5937 com.android.internal.R.string.config_secondaryHomeComponent);
5938 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5939 } else {
5940 intent.setPackage(preferredPackage);
5941 }
5942 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5943 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5944 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5945 }
5946 return intent;
5947 }
5948
Wale Ogunwale214f3482018-10-04 11:00:47 -07005949 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5950 if (info == null) return null;
5951 ApplicationInfo newInfo = new ApplicationInfo(info);
5952 newInfo.initForUser(userId);
5953 return newInfo;
5954 }
5955
Wale Ogunwale9c103022018-10-18 07:44:54 -07005956 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005957 if (uid == SYSTEM_UID) {
5958 // The system gets to run in any process. If there are multiple processes with the same
5959 // uid, just pick the first (this should never happen).
5960 final SparseArray<WindowProcessController> procs =
5961 mProcessNames.getMap().get(processName);
5962 if (procs == null) return null;
5963 final int procCount = procs.size();
5964 for (int i = 0; i < procCount; i++) {
5965 final int procUid = procs.keyAt(i);
5966 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5967 // Don't use an app process or different user process for system component.
5968 continue;
5969 }
5970 return procs.valueAt(i);
5971 }
5972 }
5973
5974 return mProcessNames.get(processName, uid);
5975 }
5976
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005977 WindowProcessController getProcessController(IApplicationThread thread) {
5978 if (thread == null) {
5979 return null;
5980 }
5981
5982 final IBinder threadBinder = thread.asBinder();
5983 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5984 for (int i = pmap.size()-1; i >= 0; i--) {
5985 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5986 for (int j = procs.size() - 1; j >= 0; j--) {
5987 final WindowProcessController proc = procs.valueAt(j);
5988 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5989 return proc;
5990 }
5991 }
5992 }
5993
5994 return null;
5995 }
5996
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005997 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005998 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005999 if (proc == null) return null;
6000 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6001 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006002 }
6003 return null;
6004 }
6005
Riddle Hsua0536432019-02-16 00:38:59 +08006006 int getUidState(int uid) {
6007 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006008 }
6009
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006010 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006011 // A uid is considered to be foreground if it has a visible non-toast window.
6012 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006013 }
6014
Ricky Wai96f5c352019-04-10 18:40:17 +01006015 boolean isDeviceOwner(int uid) {
6016 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006017 }
6018
Ricky Wai96f5c352019-04-10 18:40:17 +01006019 void setDeviceOwnerUid(int uid) {
6020 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006021 }
6022
Wale Ogunwale9de19442018-10-18 19:05:03 -07006023 /**
6024 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6025 * the whitelist
6026 */
6027 String getPendingTempWhitelistTagForUidLocked(int uid) {
6028 return mPendingTempWhitelist.get(uid);
6029 }
6030
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006031 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6032 if (true || Build.IS_USER) {
6033 return;
6034 }
6035
6036 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6037 StrictMode.allowThreadDiskWrites();
6038 try {
6039 File tracesDir = new File("/data/anr");
6040 File tracesFile = null;
6041 try {
6042 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6043
6044 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006045 String timeString =
6046 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6047 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006048 sb.append(": ");
6049 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6050 sb.append(" since ");
6051 sb.append(msg);
6052 FileOutputStream fos = new FileOutputStream(tracesFile);
6053 fos.write(sb.toString().getBytes());
6054 if (app == null) {
6055 fos.write("\n*** No application process!".getBytes());
6056 }
6057 fos.close();
6058 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6059 } catch (IOException e) {
6060 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6061 return;
6062 }
6063
6064 if (app != null && app.getPid() > 0) {
6065 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6066 firstPids.add(app.getPid());
6067 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6068 }
6069
6070 File lastTracesFile = null;
6071 File curTracesFile = null;
6072 for (int i=9; i>=0; i--) {
6073 String name = String.format(Locale.US, "slow%02d.txt", i);
6074 curTracesFile = new File(tracesDir, name);
6075 if (curTracesFile.exists()) {
6076 if (lastTracesFile != null) {
6077 curTracesFile.renameTo(lastTracesFile);
6078 } else {
6079 curTracesFile.delete();
6080 }
6081 }
6082 lastTracesFile = curTracesFile;
6083 }
6084 tracesFile.renameTo(curTracesFile);
6085 } finally {
6086 StrictMode.setThreadPolicy(oldPolicy);
6087 }
6088 }
6089
Michal Karpinskida34cd42019-04-02 19:46:52 +01006090 boolean isAssociatedCompanionApp(int userId, int uid) {
6091 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6092 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006093 return false;
6094 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006095 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006096 }
6097
Issei Suzuki734bc942019-06-05 13:59:52 +02006098 void notifySingleTaskDisplayEmpty(int displayId) {
6099 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6100 }
6101
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006102 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006103 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006104
6105
Wale Ogunwale98875612018-10-12 07:53:02 -07006106 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6107 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006108
Riddle Hsud93a6c42018-11-29 21:50:06 +08006109 H(Looper looper) {
6110 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006111 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006112
6113 @Override
6114 public void handleMessage(Message msg) {
6115 switch (msg.what) {
6116 case REPORT_TIME_TRACKER_MSG: {
6117 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6118 tracker.deliverResult(mContext);
6119 } break;
6120 }
6121 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006122 }
6123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006124 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006125 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006126
6127 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006128 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006129 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006130
6131 @Override
6132 public void handleMessage(Message msg) {
6133 switch (msg.what) {
6134 case DISMISS_DIALOG_UI_MSG: {
6135 final Dialog d = (Dialog) msg.obj;
6136 d.dismiss();
6137 break;
6138 }
6139 }
6140 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006141 }
6142
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 final class LocalService extends ActivityTaskManagerInternal {
6144 @Override
6145 public SleepToken acquireSleepToken(String tag, int displayId) {
6146 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006147 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149
6150 @Override
6151 public ComponentName getHomeActivityForUser(int userId) {
6152 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006153 final ActivityRecord homeActivity =
6154 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006155 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156 }
6157 }
6158
6159 @Override
6160 public void onLocalVoiceInteractionStarted(IBinder activity,
6161 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6162 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006163 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165 }
6166
6167 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006168 public void notifySingleTaskDisplayDrawn(int displayId) {
6169 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6170 }
6171
6172 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 public void notifyAppTransitionFinished() {
6174 synchronized (mGlobalLock) {
6175 mStackSupervisor.notifyAppTransitionDone();
6176 }
6177 }
6178
6179 @Override
6180 public void notifyAppTransitionCancelled() {
6181 synchronized (mGlobalLock) {
6182 mStackSupervisor.notifyAppTransitionDone();
6183 }
6184 }
6185
6186 @Override
6187 public List<IBinder> getTopVisibleActivities() {
6188 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006189 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 }
6191 }
6192
6193 @Override
6194 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006196 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006197 }
6198 }
6199
6200 @Override
6201 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6202 Bundle bOptions) {
6203 Preconditions.checkNotNull(intents, "intents");
6204 final String[] resolvedTypes = new String[intents.length];
6205
6206 // UID of the package on user userId.
6207 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6208 // packageUid may not be initialized.
6209 int packageUid = 0;
6210 final long ident = Binder.clearCallingIdentity();
6211
6212 try {
6213 for (int i = 0; i < intents.length; i++) {
6214 resolvedTypes[i] =
6215 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6216 }
6217
6218 packageUid = AppGlobals.getPackageManager().getPackageUid(
6219 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6220 } catch (RemoteException e) {
6221 // Shouldn't happen.
6222 } finally {
6223 Binder.restoreCallingIdentity(ident);
6224 }
6225
Riddle Hsu591bf612019-02-14 17:55:31 +08006226 return getActivityStartController().startActivitiesInPackage(
6227 packageUid, packageName,
6228 intents, resolvedTypes, null /* resultTo */,
6229 SafeActivityOptions.fromBundle(bOptions), userId,
6230 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6231 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 }
6233
6234 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006235 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6236 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6237 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6238 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006239 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006240 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006241 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6242 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6243 userId, validateIncomingUser, originatingPendingIntent,
6244 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006245 }
6246 }
6247
6248 @Override
6249 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6250 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6251 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006252 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006253 PendingIntentRecord originatingPendingIntent,
6254 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006255 synchronized (mGlobalLock) {
6256 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6257 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6258 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006259 validateIncomingUser, originatingPendingIntent,
6260 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006261 }
6262 }
6263
6264 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6266 Intent intent, Bundle options, int userId) {
6267 return ActivityTaskManagerService.this.startActivityAsUser(
6268 caller, callerPacakge, intent,
6269 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6270 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6271 false /*validateIncomingUser*/);
6272 }
6273
6274 @Override
lumark588a3e82018-07-20 18:53:54 +08006275 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 synchronized (mGlobalLock) {
6277
6278 // We might change the visibilities here, so prepare an empty app transition which
6279 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006280 final DisplayContent displayContent =
6281 mRootActivityContainer.getDisplayContent(displayId);
6282 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006283 return;
6284 }
Louis Chang677921f2019-12-06 16:44:24 +08006285 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006286 final boolean wasTransitionSet =
6287 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006289 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006290 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006291 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006292
6293 // If there was a transition set already we don't want to interfere with it as we
6294 // might be starting it too early.
6295 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006296 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006297 }
6298 }
6299 if (callback != null) {
6300 callback.run();
6301 }
6302 }
6303
6304 @Override
6305 public void notifyKeyguardTrustedChanged() {
6306 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006307 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006308 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 }
6310 }
6311 }
6312
6313 /**
6314 * Called after virtual display Id is updated by
6315 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6316 * {@param vrVr2dDisplayId}.
6317 */
6318 @Override
6319 public void setVr2dDisplayId(int vr2dDisplayId) {
6320 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6321 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006322 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 }
6324 }
6325
6326 @Override
6327 public void setFocusedActivity(IBinder token) {
6328 synchronized (mGlobalLock) {
6329 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6330 if (r == null) {
6331 throw new IllegalArgumentException(
6332 "setFocusedActivity: No activity record matching token=" + token);
6333 }
Louis Chang19443452018-10-09 12:10:21 +08006334 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006335 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006336 }
6337 }
6338 }
6339
6340 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006341 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006342 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006343 }
6344
6345 @Override
6346 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006347 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006348 }
6349
6350 @Override
6351 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006352 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006353 }
6354
6355 @Override
6356 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6357 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6358 }
6359
6360 @Override
6361 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006362 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006363 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006364
6365 @Override
6366 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6367 synchronized (mGlobalLock) {
6368 mActiveVoiceInteractionServiceComponent = component;
6369 }
6370 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006371
6372 @Override
6373 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6374 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6375 return;
6376 }
6377 synchronized (mGlobalLock) {
6378 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6379 if (types == null) {
6380 if (uid < 0) {
6381 return;
6382 }
6383 types = new ArrayMap<>();
6384 mAllowAppSwitchUids.put(userId, types);
6385 }
6386 if (uid < 0) {
6387 types.remove(type);
6388 } else {
6389 types.put(type, uid);
6390 }
6391 }
6392 }
6393
6394 @Override
6395 public void onUserStopped(int userId) {
6396 synchronized (mGlobalLock) {
6397 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6398 mAllowAppSwitchUids.remove(userId);
6399 }
6400 }
6401
6402 @Override
6403 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6404 synchronized (mGlobalLock) {
6405 return ActivityTaskManagerService.this.isGetTasksAllowed(
6406 caller, callingPid, callingUid);
6407 }
6408 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006409
Riddle Hsua0536432019-02-16 00:38:59 +08006410 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006411 @Override
6412 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006413 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006414 mProcessNames.put(proc.mName, proc.mUid, proc);
6415 }
6416 }
6417
Riddle Hsua0536432019-02-16 00:38:59 +08006418 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006419 @Override
6420 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006421 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006422 mProcessNames.remove(name, uid);
6423 }
6424 }
6425
Riddle Hsua0536432019-02-16 00:38:59 +08006426 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006427 @Override
6428 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006429 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006430 if (proc == mHomeProcess) {
6431 mHomeProcess = null;
6432 }
6433 if (proc == mPreviousProcess) {
6434 mPreviousProcess = null;
6435 }
6436 }
6437 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006438
Riddle Hsua0536432019-02-16 00:38:59 +08006439 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006440 @Override
6441 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006442 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006443 return mTopProcessState;
6444 }
6445 }
6446
Riddle Hsua0536432019-02-16 00:38:59 +08006447 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006448 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006449 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006450 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 return proc == mHeavyWeightProcess;
6452 }
6453 }
6454
Riddle Hsua0536432019-02-16 00:38:59 +08006455 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006456 @Override
6457 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006458 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006459 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6460 }
6461 }
6462
6463 @Override
6464 public void finishHeavyWeightApp() {
6465 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006466 if (mHeavyWeightProcess != null) {
6467 mHeavyWeightProcess.finishActivities();
6468 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006469 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6470 mHeavyWeightProcess);
6471 }
6472 }
6473
Riddle Hsua0536432019-02-16 00:38:59 +08006474 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006475 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006476 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006477 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006478 return isSleepingLocked();
6479 }
6480 }
6481
6482 @Override
6483 public boolean isShuttingDown() {
6484 synchronized (mGlobalLock) {
6485 return mShuttingDown;
6486 }
6487 }
6488
6489 @Override
6490 public boolean shuttingDown(boolean booted, int timeout) {
6491 synchronized (mGlobalLock) {
6492 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006493 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006494 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006495 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 return mStackSupervisor.shutdownLocked(timeout);
6497 }
6498 }
6499
6500 @Override
6501 public void enableScreenAfterBoot(boolean booted) {
6502 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006503 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006504 mWindowManager.enableScreenAfterBoot();
6505 updateEventDispatchingLocked(booted);
6506 }
6507 }
6508
6509 @Override
6510 public boolean showStrictModeViolationDialog() {
6511 synchronized (mGlobalLock) {
6512 return mShowDialogs && !mSleeping && !mShuttingDown;
6513 }
6514 }
6515
6516 @Override
6517 public void showSystemReadyErrorDialogsIfNeeded() {
6518 synchronized (mGlobalLock) {
6519 try {
6520 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6521 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6522 + " data partition or your device will be unstable.");
6523 mUiHandler.post(() -> {
6524 if (mShowDialogs) {
6525 AlertDialog d = new BaseErrorDialog(mUiContext);
6526 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6527 d.setCancelable(false);
6528 d.setTitle(mUiContext.getText(R.string.android_system_label));
6529 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6530 d.setButton(DialogInterface.BUTTON_POSITIVE,
6531 mUiContext.getText(R.string.ok),
6532 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6533 d.show();
6534 }
6535 });
6536 }
6537 } catch (RemoteException e) {
6538 }
6539
6540 if (!Build.isBuildConsistent()) {
6541 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6542 mUiHandler.post(() -> {
6543 if (mShowDialogs) {
6544 AlertDialog d = new BaseErrorDialog(mUiContext);
6545 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6546 d.setCancelable(false);
6547 d.setTitle(mUiContext.getText(R.string.android_system_label));
6548 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6549 d.setButton(DialogInterface.BUTTON_POSITIVE,
6550 mUiContext.getText(R.string.ok),
6551 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6552 d.show();
6553 }
6554 });
6555 }
6556 }
6557 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006558
6559 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006560 public void onProcessMapped(int pid, WindowProcessController proc) {
6561 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006562 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006563 }
6564 }
6565
6566 @Override
6567 public void onProcessUnMapped(int pid) {
6568 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006569 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006570 }
6571 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006572
6573 @Override
6574 public void onPackageDataCleared(String name) {
6575 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006576 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006577 mAppWarnings.onPackageDataCleared(name);
6578 }
6579 }
6580
6581 @Override
6582 public void onPackageUninstalled(String name) {
6583 synchronized (mGlobalLock) {
6584 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006585 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006586 }
6587 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006588
6589 @Override
6590 public void onPackageAdded(String name, boolean replacing) {
6591 synchronized (mGlobalLock) {
6592 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6593 }
6594 }
6595
6596 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006597 public void onPackageReplaced(ApplicationInfo aInfo) {
6598 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006599 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 }
6601 }
6602
6603 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006604 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6605 synchronized (mGlobalLock) {
6606 return compatibilityInfoForPackageLocked(ai);
6607 }
6608 }
6609
Yunfan Chen75157d72018-07-27 14:47:21 +09006610 /**
6611 * Set the corresponding display information for the process global configuration. To be
6612 * called when we need to show IME on a different display.
6613 *
6614 * @param pid The process id associated with the IME window.
6615 * @param displayId The ID of the display showing the IME.
6616 */
6617 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006618 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006619 // Don't update process-level configuration for Multi-Client IME process since other
6620 // IMEs on other displays will also receive this configuration change due to IME
6621 // services use the same application config/context.
6622 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006623
Yunfan Chen75157d72018-07-27 14:47:21 +09006624 if (pid == MY_PID || pid < 0) {
6625 if (DEBUG_CONFIGURATION) {
6626 Slog.w(TAG,
6627 "Trying to update display configuration for system/invalid process.");
6628 }
6629 return;
6630 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006631 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006632 final DisplayContent displayContent =
6633 mRootActivityContainer.getDisplayContent(displayId);
6634 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006635 // Call might come when display is not yet added or has been removed.
6636 if (DEBUG_CONFIGURATION) {
6637 Slog.w(TAG, "Trying to update display configuration for non-existing "
6638 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006639 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006640 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006641 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006642 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006643 if (process == null) {
6644 if (DEBUG_CONFIGURATION) {
6645 Slog.w(TAG, "Trying to update display configuration for invalid "
6646 + "process, pid=" + pid);
6647 }
6648 return;
6649 }
lumarkddc77fb2019-06-27 22:22:23 +08006650 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006651 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006652 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006653 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006654
6655 @Override
6656 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006657 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006658 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006659 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6660 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006661 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006662 }
6663 }
6664 }
6665
6666 @Override
6667 public void clearPendingResultForActivity(IBinder activityToken,
6668 WeakReference<PendingIntentRecord> pir) {
6669 synchronized (mGlobalLock) {
6670 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6671 if (r != null && r.pendingResults != null) {
6672 r.pendingResults.remove(pir);
6673 }
6674 }
6675 }
6676
6677 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006678 public ActivityTokens getTopActivityForTask(int taskId) {
6679 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006680 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6681 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006682 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6683 + " Requested task not found");
6684 return null;
6685 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006686 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006687 if (activity == null) {
6688 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6689 + " Requested activity not found");
6690 return null;
6691 }
6692 if (!activity.attachedToProcess()) {
6693 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6694 + activity);
6695 return null;
6696 }
6697 return new ActivityTokens(activity.appToken, activity.assistToken,
6698 activity.app.getThread());
6699 }
6700 }
6701
6702 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006703 public IIntentSender getIntentSender(int type, String packageName,
6704 int callingUid, int userId, IBinder token, String resultWho,
6705 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6706 Bundle bOptions) {
6707 synchronized (mGlobalLock) {
6708 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6709 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6710 }
6711 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006712
6713 @Override
6714 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6715 synchronized (mGlobalLock) {
6716 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6717 if (r == null) {
6718 return null;
6719 }
6720 if (r.mServiceConnectionsHolder == null) {
6721 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6722 ActivityTaskManagerService.this, r);
6723 }
6724
6725 return r.mServiceConnectionsHolder;
6726 }
6727 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006728
6729 @Override
6730 public Intent getHomeIntent() {
6731 synchronized (mGlobalLock) {
6732 return ActivityTaskManagerService.this.getHomeIntent();
6733 }
6734 }
6735
6736 @Override
6737 public boolean startHomeActivity(int userId, String reason) {
6738 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006740 }
6741 }
6742
6743 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006744 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006745 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006746 synchronized (mGlobalLock) {
6747 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006748 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006749 }
Chilun8b1f1be2019-03-13 17:14:36 +08006750 }
6751
6752 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006753 public boolean startHomeOnAllDisplays(int userId, String reason) {
6754 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006755 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006756 }
6757 }
6758
Riddle Hsua0536432019-02-16 00:38:59 +08006759 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006760 @Override
6761 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006762 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763 if (mFactoryTest == FACTORY_TEST_OFF) {
6764 return false;
6765 }
6766 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6767 && wpc.mName.equals(mTopComponent.getPackageName())) {
6768 return true;
6769 }
6770 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6771 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6772 }
6773 }
6774
6775 @Override
6776 public void updateTopComponentForFactoryTest() {
6777 synchronized (mGlobalLock) {
6778 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6779 return;
6780 }
6781 final ResolveInfo ri = mContext.getPackageManager()
6782 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6783 final CharSequence errorMsg;
6784 if (ri != null) {
6785 final ActivityInfo ai = ri.activityInfo;
6786 final ApplicationInfo app = ai.applicationInfo;
6787 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6788 mTopAction = Intent.ACTION_FACTORY_TEST;
6789 mTopData = null;
6790 mTopComponent = new ComponentName(app.packageName, ai.name);
6791 errorMsg = null;
6792 } else {
6793 errorMsg = mContext.getResources().getText(
6794 com.android.internal.R.string.factorytest_not_system);
6795 }
6796 } else {
6797 errorMsg = mContext.getResources().getText(
6798 com.android.internal.R.string.factorytest_no_action);
6799 }
6800 if (errorMsg == null) {
6801 return;
6802 }
6803
6804 mTopAction = null;
6805 mTopData = null;
6806 mTopComponent = null;
6807 mUiHandler.post(() -> {
6808 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6809 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006810 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006811 });
6812 }
6813 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814
Riddle Hsua0536432019-02-16 00:38:59 +08006815 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 @Override
6817 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6818 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006819 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006821 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822
6823 wpc.clearRecentTasks();
6824 wpc.clearActivities();
6825
6826 if (wpc.isInstrumenting()) {
6827 finishInstrumentationCallback.run();
6828 }
6829
Jorim Jaggid0752812018-10-16 16:07:20 +02006830 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006831 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006832 try {
6833 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6834 // If there was nothing to resume, and we are not already restarting
6835 // this process, but there is a visible activity that is hosted by the
6836 // process...then make sure all visible activities are running, taking
6837 // care of restarting this process.
6838 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6839 !PRESERVE_WINDOWS);
6840 }
6841 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006842 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 }
6845 }
6846 }
6847
6848 @Override
6849 public void closeSystemDialogs(String reason) {
6850 enforceNotIsolatedCaller("closeSystemDialogs");
6851
6852 final int pid = Binder.getCallingPid();
6853 final int uid = Binder.getCallingUid();
6854 final long origId = Binder.clearCallingIdentity();
6855 try {
6856 synchronized (mGlobalLock) {
6857 // Only allow this from foreground processes, so that background
6858 // applications can't abuse it to prevent system UI from being shown.
6859 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006860 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 if (!proc.isPerceptible()) {
6862 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6863 + " from background process " + proc);
6864 return;
6865 }
6866 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 mWindowManager.closeSystemDialogs(reason);
6868
Wale Ogunwaled32da472018-11-16 07:19:28 -08006869 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006871 // Call into AM outside the synchronized block.
6872 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 } finally {
6874 Binder.restoreCallingIdentity(origId);
6875 }
6876 }
6877
6878 @Override
6879 public void cleanupDisabledPackageComponents(
6880 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6881 synchronized (mGlobalLock) {
6882 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006883 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006885 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 mStackSupervisor.scheduleIdleLocked();
6887 }
6888
6889 // Clean-up disabled tasks
6890 getRecentTasks().cleanupDisabledPackageTasksLocked(
6891 packageName, disabledClasses, userId);
6892 }
6893 }
6894
6895 @Override
6896 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6897 int userId) {
6898 synchronized (mGlobalLock) {
6899
6900 boolean didSomething =
6901 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006902 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 null, doit, evenPersistent, userId);
6904 return didSomething;
6905 }
6906 }
6907
6908 @Override
6909 public void resumeTopActivities(boolean scheduleIdle) {
6910 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 if (scheduleIdle) {
6913 mStackSupervisor.scheduleIdleLocked();
6914 }
6915 }
6916 }
6917
Riddle Hsua0536432019-02-16 00:38:59 +08006918 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 @Override
6920 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006921 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6923 }
6924 }
6925
Riddle Hsua0536432019-02-16 00:38:59 +08006926 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927 @Override
6928 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006929 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006930 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6931 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6932 }
6933 try {
6934 return mRootActivityContainer.attachApplication(wpc);
6935 } finally {
6936 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6937 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 }
6939 }
6940
6941 @Override
6942 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6943 try {
6944 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6945 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6946 }
6947 } catch (RemoteException ex) {
6948 throw new SecurityException("Fail to check is caller a privileged app", ex);
6949 }
6950
6951 synchronized (mGlobalLock) {
6952 final long ident = Binder.clearCallingIdentity();
6953 try {
6954 if (mAmInternal.shouldConfirmCredentials(userId)) {
6955 if (mKeyguardController.isKeyguardLocked()) {
6956 // Showing launcher to avoid user entering credential twice.
6957 startHomeActivity(currentUserId, "notifyLockedProfile");
6958 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006959 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 }
6961 } finally {
6962 Binder.restoreCallingIdentity(ident);
6963 }
6964 }
6965 }
6966
6967 @Override
6968 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6969 mAmInternal.enforceCallingPermission(
6970 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6971
6972 synchronized (mGlobalLock) {
6973 final long ident = Binder.clearCallingIdentity();
6974 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006975 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6976 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006977 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6979 UserHandle.CURRENT);
6980 } finally {
6981 Binder.restoreCallingIdentity(ident);
6982 }
6983 }
6984 }
6985
6986 @Override
6987 public void writeActivitiesToProto(ProtoOutputStream proto) {
6988 synchronized (mGlobalLock) {
6989 // The output proto of "activity --proto activities"
6990 // is ActivityManagerServiceDumpActivitiesProto
Jeffrey Huangcb782852019-12-05 11:28:11 -08006991 mRootActivityContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006992 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6993 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 }
6995 }
6996
6997 @Override
6998 public void saveANRState(String reason) {
6999 synchronized (mGlobalLock) {
7000 final StringWriter sw = new StringWriter();
7001 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7002 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7003 if (reason != null) {
7004 pw.println(" Reason: " + reason);
7005 }
7006 pw.println();
7007 getActivityStartController().dump(pw, " ", null);
7008 pw.println();
7009 pw.println("-------------------------------------------------------------------------------");
7010 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7011 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7012 "" /* header */);
7013 pw.println();
7014 pw.close();
7015
7016 mLastANRState = sw.toString();
7017 }
7018 }
7019
7020 @Override
7021 public void clearSavedANRState() {
7022 synchronized (mGlobalLock) {
7023 mLastANRState = null;
7024 }
7025 }
7026
7027 @Override
7028 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7029 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7030 synchronized (mGlobalLock) {
7031 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7032 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7033 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7034 dumpLastANRLocked(pw);
7035 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7036 dumpLastANRTracesLocked(pw);
7037 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7038 dumpActivityStarterLocked(pw, dumpPackage);
7039 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7040 dumpActivityContainersLocked(pw);
7041 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7042 if (getRecentTasks() != null) {
7043 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7044 }
7045 }
7046 }
7047 }
7048
7049 @Override
7050 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7051 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7052 int wakefulness) {
7053 synchronized (mGlobalLock) {
7054 if (mHomeProcess != null && (dumpPackage == null
7055 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7056 if (needSep) {
7057 pw.println();
7058 needSep = false;
7059 }
7060 pw.println(" mHomeProcess: " + mHomeProcess);
7061 }
7062 if (mPreviousProcess != null && (dumpPackage == null
7063 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7064 if (needSep) {
7065 pw.println();
7066 needSep = false;
7067 }
7068 pw.println(" mPreviousProcess: " + mPreviousProcess);
7069 }
7070 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7071 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7072 StringBuilder sb = new StringBuilder(128);
7073 sb.append(" mPreviousProcessVisibleTime: ");
7074 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7075 pw.println(sb);
7076 }
7077 if (mHeavyWeightProcess != null && (dumpPackage == null
7078 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7079 if (needSep) {
7080 pw.println();
7081 needSep = false;
7082 }
7083 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7084 }
7085 if (dumpPackage == null) {
7086 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007087 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 }
7089 if (dumpAll) {
7090 if (dumpPackage == null) {
7091 pw.println(" mConfigWillChange: "
7092 + getTopDisplayFocusedStack().mConfigWillChange);
7093 }
7094 if (mCompatModePackages.getPackages().size() > 0) {
7095 boolean printed = false;
7096 for (Map.Entry<String, Integer> entry
7097 : mCompatModePackages.getPackages().entrySet()) {
7098 String pkg = entry.getKey();
7099 int mode = entry.getValue();
7100 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7101 continue;
7102 }
7103 if (!printed) {
7104 pw.println(" mScreenCompatPackages:");
7105 printed = true;
7106 }
7107 pw.println(" " + pkg + ": " + mode);
7108 }
7109 }
7110 }
7111
7112 if (dumpPackage == null) {
7113 pw.println(" mWakefulness="
7114 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007115 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007116 if (mRunningVoice != null) {
7117 pw.println(" mRunningVoice=" + mRunningVoice);
7118 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7119 }
7120 pw.println(" mSleeping=" + mSleeping);
7121 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7122 pw.println(" mVrController=" + mVrController);
7123 }
7124 if (mCurAppTimeTracker != null) {
7125 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7126 }
7127 if (mAllowAppSwitchUids.size() > 0) {
7128 boolean printed = false;
7129 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7130 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7131 for (int j = 0; j < types.size(); j++) {
7132 if (dumpPackage == null ||
7133 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7134 if (needSep) {
7135 pw.println();
7136 needSep = false;
7137 }
7138 if (!printed) {
7139 pw.println(" mAllowAppSwitchUids:");
7140 printed = true;
7141 }
7142 pw.print(" User ");
7143 pw.print(mAllowAppSwitchUids.keyAt(i));
7144 pw.print(": Type ");
7145 pw.print(types.keyAt(j));
7146 pw.print(" = ");
7147 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7148 pw.println();
7149 }
7150 }
7151 }
7152 }
7153 if (dumpPackage == null) {
7154 if (mController != null) {
7155 pw.println(" mController=" + mController
7156 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7157 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007158 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7159 pw.println(" mLaunchingActivityWakeLock="
7160 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 }
7162
7163 return needSep;
7164 }
7165 }
7166
7167 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007168 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7169 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 synchronized (mGlobalLock) {
7171 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007172 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007174 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7175 if (mRunningVoice != null) {
7176 final long vrToken = proto.start(
7177 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7178 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7179 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007180 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007181 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7182 proto.end(vrToken);
7183 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007184 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007185 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 if (mController != null) {
7187 final long token = proto.start(CONTROLLER);
7188 proto.write(CONTROLLER, mController.toString());
7189 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7190 proto.end(token);
7191 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007192 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7193 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007194 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 }
7196
7197 if (mHomeProcess != null && (dumpPackage == null
7198 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007199 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007200 }
7201
7202 if (mPreviousProcess != null && (dumpPackage == null
7203 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007204 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007205 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7206 }
7207
7208 if (mHeavyWeightProcess != null && (dumpPackage == null
7209 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007210 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 }
7212
7213 for (Map.Entry<String, Integer> entry
7214 : mCompatModePackages.getPackages().entrySet()) {
7215 String pkg = entry.getKey();
7216 int mode = entry.getValue();
7217 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7218 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7219 proto.write(PACKAGE, pkg);
7220 proto.write(MODE, mode);
7221 proto.end(compatToken);
7222 }
7223 }
7224
7225 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007226 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007227 }
7228
7229 }
7230 }
7231
7232 @Override
7233 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7234 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7235 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007236 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7237 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007238 }
7239
7240 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007241 public void dumpForOom(PrintWriter pw) {
7242 synchronized (mGlobalLock) {
7243 pw.println(" mHomeProcess: " + mHomeProcess);
7244 pw.println(" mPreviousProcess: " + mPreviousProcess);
7245 if (mHeavyWeightProcess != null) {
7246 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7247 }
7248 }
7249 }
7250
7251 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007252 public boolean canGcNow() {
7253 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007254 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256 }
7257
Riddle Hsua0536432019-02-16 00:38:59 +08007258 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007259 @Override
7260 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007261 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007262 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007263 return top != null ? top.app : null;
7264 }
7265 }
7266
Riddle Hsua0536432019-02-16 00:38:59 +08007267 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007268 @Override
7269 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007270 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007271 if (mRootActivityContainer != null) {
7272 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 }
7274 }
7275 }
7276
7277 @Override
7278 public void scheduleDestroyAllActivities(String reason) {
7279 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007280 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007281 }
7282 }
7283
7284 @Override
7285 public void removeUser(int userId) {
7286 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007287 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007288 }
7289 }
7290
7291 @Override
7292 public boolean switchUser(int userId, UserState userState) {
7293 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007294 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007295 }
7296 }
7297
7298 @Override
7299 public void onHandleAppCrash(WindowProcessController wpc) {
7300 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007301 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007302 }
7303 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007304
7305 @Override
7306 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7307 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007308 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007309 }
7310 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007311
Riddle Hsua0536432019-02-16 00:38:59 +08007312 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007313 @Override
7314 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007315 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007316 }
7317
Riddle Hsua0536432019-02-16 00:38:59 +08007318 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007319 @Override
7320 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007321 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007322 }
7323
Riddle Hsua0536432019-02-16 00:38:59 +08007324 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007325 @Override
7326 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007327 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007328 }
7329
Riddle Hsua0536432019-02-16 00:38:59 +08007330 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007331 @Override
7332 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007333 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007334 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007335
7336 @Override
7337 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007338 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007339 mPendingTempWhitelist.put(uid, tag);
7340 }
7341 }
7342
7343 @Override
7344 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007345 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007346 mPendingTempWhitelist.remove(uid);
7347 }
7348 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007349
7350 @Override
7351 public boolean handleAppCrashInActivityController(String processName, int pid,
7352 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7353 Runnable killCrashingAppCallback) {
7354 synchronized (mGlobalLock) {
7355 if (mController == null) {
7356 return false;
7357 }
7358
7359 try {
7360 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7361 stackTrace)) {
7362 killCrashingAppCallback.run();
7363 return true;
7364 }
7365 } catch (RemoteException e) {
7366 mController = null;
7367 Watchdog.getInstance().setActivityController(null);
7368 }
7369 return false;
7370 }
7371 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007372
7373 @Override
7374 public void removeRecentTasksByPackageName(String packageName, int userId) {
7375 synchronized (mGlobalLock) {
7376 mRecentTasks.removeTasksByPackageName(packageName, userId);
7377 }
7378 }
7379
7380 @Override
7381 public void cleanupRecentTasksForUser(int userId) {
7382 synchronized (mGlobalLock) {
7383 mRecentTasks.cleanupLocked(userId);
7384 }
7385 }
7386
7387 @Override
7388 public void loadRecentTasksForUser(int userId) {
7389 synchronized (mGlobalLock) {
7390 mRecentTasks.loadUserRecentsLocked(userId);
7391 }
7392 }
7393
7394 @Override
7395 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7396 synchronized (mGlobalLock) {
7397 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7398 }
7399 }
7400
7401 @Override
7402 public void flushRecentTasks() {
7403 mRecentTasks.flush();
7404 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007405
7406 @Override
7407 public WindowProcessController getHomeProcess() {
7408 synchronized (mGlobalLock) {
7409 return mHomeProcess;
7410 }
7411 }
7412
7413 @Override
7414 public WindowProcessController getPreviousProcess() {
7415 synchronized (mGlobalLock) {
7416 return mPreviousProcess;
7417 }
7418 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007419
7420 @Override
7421 public void clearLockedTasks(String reason) {
7422 synchronized (mGlobalLock) {
7423 getLockTaskController().clearLockedTasks(reason);
7424 }
7425 }
7426
7427 @Override
7428 public void updateUserConfiguration() {
7429 synchronized (mGlobalLock) {
7430 final Configuration configuration = new Configuration(getGlobalConfiguration());
7431 final int currentUserId = mAmInternal.getCurrentUserId();
7432 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7433 configuration, currentUserId, Settings.System.canWrite(mContext));
7434 updateConfigurationLocked(configuration, null /* starting */,
7435 false /* initLocale */, false /* persistent */, currentUserId,
7436 false /* deferResume */);
7437 }
7438 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007439
7440 @Override
7441 public boolean canShowErrorDialogs() {
7442 synchronized (mGlobalLock) {
7443 return mShowDialogs && !mSleeping && !mShuttingDown
7444 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7445 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7446 mAmInternal.getCurrentUserId())
7447 && !(UserManager.isDeviceInDemoMode(mContext)
7448 && mAmInternal.getCurrentUser().isDemo());
7449 }
7450 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007451
7452 @Override
7453 public void setProfileApp(String profileApp) {
7454 synchronized (mGlobalLock) {
7455 mProfileApp = profileApp;
7456 }
7457 }
7458
7459 @Override
7460 public void setProfileProc(WindowProcessController wpc) {
7461 synchronized (mGlobalLock) {
7462 mProfileProc = wpc;
7463 }
7464 }
7465
7466 @Override
7467 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7468 synchronized (mGlobalLock) {
7469 mProfilerInfo = profilerInfo;
7470 }
7471 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007472
7473 @Override
7474 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7475 synchronized (mGlobalLock) {
7476 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7477 }
7478 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007479
7480 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007481 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7482 boolean reducedResolution) {
7483 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7484 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007485 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007486
7487 @Override
7488 public boolean isUidForeground(int uid) {
7489 synchronized (mGlobalLock) {
7490 return ActivityTaskManagerService.this.isUidForeground(uid);
7491 }
7492 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007493
7494 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007495 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007496 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007497 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007498 }
7499 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007500
7501 @Override
7502 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007503 // Translate package names into UIDs
7504 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007505 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007506 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7507 if (uid >= 0) {
7508 result.add(uid);
7509 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007510 }
7511 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007512 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007513 }
7514 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007515 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007516}