blob: 86adb34b24639da347886337bec0646ed73c6305 [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;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
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;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.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;
Robert Carr8a2f9132019-11-11 15:03:15 -0800229import android.view.ITaskOrganizer;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700232import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
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;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800309 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Evan Rosky226de132020-01-03 18:00:29 -0800347 /** Flag indicating that an applied transaction may have effected lifecycle */
348 private static final int TRANSACT_EFFECTS_CLIENT_CONFIG = 1;
349 private static final int TRANSACT_EFFECTS_LIFECYCLE = 1 << 1;
350
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700351 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700352
Wale Ogunwalef6733932018-06-27 05:14:34 -0700353 /**
354 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
355 * change at runtime. Use mContext for non-UI purposes.
356 */
357 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700359 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700360 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700361 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700362 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700363 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800364 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800365 @VisibleForTesting
366 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700367 PowerManagerInternal mPowerManagerInternal;
368 private UsageStatsManagerInternal mUsageStatsInternal;
369
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700370 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700371 IntentFirewall mIntentFirewall;
372
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700373 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800374 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800375 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700376 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800377 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
378 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
379 *
380 * @see WindowManagerThreadPriorityBooster
381 */
382 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700383 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800384 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700385 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700386 private UserManagerService mUserManager;
387 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700388 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800389 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700390 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /** All processes currently running that might have a window organized by name. */
392 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100393 /** All processes we currently have running mapped by pid and uid */
394 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /** This is the process holding what we currently consider to be the "home" activity. */
396 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700397 /** The currently running heavy-weight process, if any. */
398 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700399 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700400 /**
401 * This is the process holding the activity the user last visited that is in a different process
402 * from the one they are currently in.
403 */
404 WindowProcessController mPreviousProcess;
405 /** The time at which the previous process was last visible. */
406 long mPreviousProcessVisibleTime;
407
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700408 /** List of intents that were used to start the most recent tasks. */
409 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700410 /** State of external calls telling us if the device is awake or asleep. */
411 private boolean mKeyguardShown = false;
412
413 // Wrapper around VoiceInteractionServiceManager
414 private AssistUtils mAssistUtils;
415
416 // VoiceInteraction session ID that changes for each new request except when
417 // being called for multi-window assist in a single session.
418 private int mViSessionId = 1000;
419
420 // How long to wait in getAssistContextExtras for the activity and foreground services
421 // to respond with the result.
422 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
423
424 // How long top wait when going through the modern assist (which doesn't need to block
425 // on getting this result before starting to launch its UI).
426 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
427
428 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
429 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
430
Alison Cichowlas3e340502018-08-07 17:15:01 -0400431 // Permission tokens are used to temporarily granted a trusted app the ability to call
432 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
433 // showing any appropriate error messages to the user.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
435 10 * MINUTE_IN_MILLIS;
436
437 // How long before the service actually expires a token. This is slightly longer than
438 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
439 // expiration exception.
440 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
441 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
442
443 // How long the service will remember expired tokens, for the purpose of providing error
444 // messaging when a client uses an expired token.
445 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
446 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
447
448 // Activity tokens of system activities that are delegating their call to
449 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
450 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
451
452 // Permission tokens that have expired, but we remember for error reporting.
453 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
454
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700455 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
456
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 // Keeps track of the active voice interaction service component, notified from
458 // VoiceInteractionManagerService
459 ComponentName mActiveVoiceInteractionServiceComponent;
460
Michal Karpinskida34cd42019-04-02 19:46:52 +0100461 // A map userId and all its companion app uids
462 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000463
Wale Ogunwalee2172292018-10-25 10:11:10 -0700464 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465 KeyguardController mKeyguardController;
466 private final ClientLifecycleManager mLifecycleManager;
467 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700468 /** The controller for all operations related to locktask. */
469 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700470 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700471
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700472 boolean mSuppressResizeConfigChanges;
473
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700474 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700475 new UpdateConfigurationResult();
476
477 static final class UpdateConfigurationResult {
478 // Configuration changes that were updated.
479 int changes;
480 // If the activity was relaunched to match the new configuration.
481 boolean activityRelaunched;
482
483 void reset() {
484 changes = 0;
485 activityRelaunched = false;
486 }
487 }
488
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private int mConfigurationSeq;
491 // To cache the list of supported system locales
492 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700493
494 /**
495 * Temp object used when global and/or display override configuration is updated. It is also
496 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
497 * anyone...
498 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 private Configuration mTempConfig = new Configuration();
500
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 /** Temporary to avoid allocations. */
502 final StringBuilder mStringBuilder = new StringBuilder(256);
503
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 // Amount of time after a call to stopAppSwitches() during which we will
505 // prevent further untrusted switches from happening.
506 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
507
508 /**
509 * The time at which we will allow normal application switches again,
510 * after a call to {@link #stopAppSwitches()}.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 /**
514 * This is set to true after the first switch after mAppSwitchesAllowedTime
515 * is set; any switches after that will clear the time.
516 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700517 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518
Ricky Wai906af482019-06-03 17:25:28 +0100519 /**
520 * Last stop app switches time, apps finished before this time cannot start background activity
521 * even if they are in grace period.
522 */
523 private long mLastStopAppSwitchesTime;
524
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700525 IActivityController mController = null;
526 boolean mControllerIsAMonkey = false;
527
Wale Ogunwale214f3482018-10-04 11:00:47 -0700528 final int mFactoryTest;
529
530 /** Used to control how we initialize the service. */
531 ComponentName mTopComponent;
532 String mTopAction = Intent.ACTION_MAIN;
533 String mTopData;
534
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800535 /** Profiling app information. */
536 String mProfileApp = null;
537 WindowProcessController mProfileProc = null;
538 ProfilerInfo mProfilerInfo = null;
539
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700541 * Dump of the activity state at the time of the last ANR. Cleared after
542 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
543 */
544 String mLastANRState;
545
546 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547 * Used to retain an update lock when the foreground activity is in
548 * immersive mode.
549 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Packages that are being allowed to perform unrestricted app switches. Mapping is
554 * User -> Type -> uid.
555 */
556 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
557
558 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700559 private int mThumbnailWidth;
560 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700561
562 /**
563 * Flag that indicates if multi-window is enabled.
564 *
565 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
566 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
567 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
568 * At least one of the forms of multi-window must be enabled in order for this flag to be
569 * initialized to 'true'.
570 *
571 * @see #mSupportsSplitScreenMultiWindow
572 * @see #mSupportsFreeformWindowManagement
573 * @see #mSupportsPictureInPicture
574 * @see #mSupportsMultiDisplay
575 */
576 boolean mSupportsMultiWindow;
577 boolean mSupportsSplitScreenMultiWindow;
578 boolean mSupportsFreeformWindowManagement;
579 boolean mSupportsPictureInPicture;
580 boolean mSupportsMultiDisplay;
581 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700582 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700583
584 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
585
586 // VR Vr2d Display Id.
587 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700588
Wale Ogunwalef6733932018-06-27 05:14:34 -0700589 /**
590 * Set while we are wanting to sleep, to prevent any
591 * activities from being started/resumed.
592 *
593 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
594 *
595 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
596 * while in the sleep state until there is a pending transition out of sleep, in which case
597 * mSleeping is set to false, and remains false while awake.
598 *
599 * Whether mSleeping can quickly toggled between true/false without the device actually
600 * display changing states is undefined.
601 */
602 private boolean mSleeping = false;
603
604 /**
605 * The process state used for processes that are running the top activities.
606 * This changes between TOP and TOP_SLEEPING to following mSleeping.
607 */
608 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
609
Riddle Hsua0022cd2019-09-09 21:12:41 +0800610 @Retention(RetentionPolicy.SOURCE)
611 @IntDef({
612 LAYOUT_REASON_CONFIG_CHANGED,
613 LAYOUT_REASON_VISIBILITY_CHANGED,
614 })
615 @interface LayoutReason {}
616 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
617 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
618
619 /** The reasons to perform surface placement. */
620 @LayoutReason
621 private int mLayoutReasons;
622
Wale Ogunwalef6733932018-06-27 05:14:34 -0700623 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
624 // automatically. Important for devices without direct input devices.
625 private boolean mShowDialogs = true;
626
627 /** Set if we are shutting down the system, similar to sleeping. */
628 boolean mShuttingDown = false;
629
630 /**
631 * We want to hold a wake lock while running a voice interaction session, since
632 * this may happen with the screen off and we need to keep the CPU running to
633 * be able to continue to interact with the user.
634 */
635 PowerManager.WakeLock mVoiceWakeLock;
636
637 /**
638 * Set while we are running a voice interaction. This overrides sleeping while it is active.
639 */
640 IVoiceInteractionSession mRunningVoice;
641
642 /**
643 * The last resumed activity. This is identical to the current resumed activity most
644 * of the time but could be different when we're pausing one activity before we resume
645 * another activity.
646 */
647 ActivityRecord mLastResumedActivity;
648
649 /**
650 * The activity that is currently being traced as the active resumed activity.
651 *
652 * @see #updateResumedAppTrace
653 */
654 private @Nullable ActivityRecord mTracedResumedActivity;
655
656 /** If non-null, we are tracking the time the user spends in the currently focused app. */
657 AppTimeTracker mCurAppTimeTracker;
658
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700659 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700660
Wale Ogunwale53783742018-09-16 10:21:51 -0700661 /**
662 * Packages that the user has asked to have run in screen size
663 * compatibility mode instead of filling the screen.
664 */
665 CompatModePackages mCompatModePackages;
666
Wale Ogunwalef6733932018-06-27 05:14:34 -0700667 private FontScaleSettingObserver mFontScaleSettingObserver;
668
Robert Carr8a2f9132019-11-11 15:03:15 -0800669 /**
670 * Stores the registration and state of TaskOrganizers in use.
671 */
672 TaskOrganizerController mTaskOrganizerController =
673 new TaskOrganizerController(this, mGlobalLock);
674
Ricky Wai96f5c352019-04-10 18:40:17 +0100675 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000676
Wale Ogunwalef6733932018-06-27 05:14:34 -0700677 private final class FontScaleSettingObserver extends ContentObserver {
678 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
679 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
680
681 public FontScaleSettingObserver() {
682 super(mH);
683 final ContentResolver resolver = mContext.getContentResolver();
684 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
685 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
686 UserHandle.USER_ALL);
687 }
688
689 @Override
690 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
691 if (mFontScaleUri.equals(uri)) {
692 updateFontScaleIfNeeded(userId);
693 } else if (mHideErrorDialogsUri.equals(uri)) {
694 synchronized (mGlobalLock) {
695 updateShouldShowDialogsLocked(getGlobalConfiguration());
696 }
697 }
698 }
699 }
700
Riddle Hsua0536432019-02-16 00:38:59 +0800701 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
702 @Target(ElementType.METHOD)
703 @Retention(RetentionPolicy.SOURCE)
704 @interface HotPath {
705 int NONE = 0;
706 int OOM_ADJUSTMENT = 1;
707 int LRU_UPDATE = 2;
708 int PROCESS_CHANGE = 3;
709 int caller() default NONE;
710 }
711
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
713 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900714 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800715 mAmInternal.updateOomAdj();
716 }
717 };
718
Charles Chen8d98dd22018-12-26 17:36:54 +0800719 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
720 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700722 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 mSystemThread = ActivityThread.currentActivityThread();
724 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700725 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800726 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700727 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onSystemReady() {
731 synchronized (mGlobalLock) {
732 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
733 PackageManager.FEATURE_CANT_SAVE_STATE);
734 mAssistUtils = new AssistUtils(mContext);
735 mVrController.onSystemReady();
736 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700737 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700739 }
740
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700741 public void onInitPowerManagement() {
742 synchronized (mGlobalLock) {
743 mStackSupervisor.initPowerManagement();
744 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
745 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
746 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
747 mVoiceWakeLock.setReferenceCounted(false);
748 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 }
750
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700751 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700752 mFontScaleSettingObserver = new FontScaleSettingObserver();
753 }
754
Wale Ogunwale59507092018-10-29 09:00:30 -0700755 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 final boolean freeformWindowManagement =
757 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
758 || Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
760
761 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
762 final boolean supportsPictureInPicture = supportsMultiWindow &&
763 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
764 final boolean supportsSplitScreenMultiWindow =
765 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
766 final boolean supportsMultiDisplay = mContext.getPackageManager()
767 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
769 final boolean forceResizable = Settings.Global.getInt(
770 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700771 final boolean sizeCompatFreeform = Settings.Global.getInt(
772 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900775 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776
777 final Configuration configuration = new Configuration();
778 Settings.System.getConfiguration(resolver, configuration);
779 if (forceRtl) {
780 // This will take care of setting the correct layout direction flags
781 configuration.setLayoutDirection(configuration.locale);
782 }
783
784 synchronized (mGlobalLock) {
785 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700786 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700787 final boolean multiWindowFormEnabled = freeformWindowManagement
788 || supportsSplitScreenMultiWindow
789 || supportsPictureInPicture
790 || supportsMultiDisplay;
791 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
792 mSupportsMultiWindow = true;
793 mSupportsFreeformWindowManagement = freeformWindowManagement;
794 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
795 mSupportsPictureInPicture = supportsPictureInPicture;
796 mSupportsMultiDisplay = supportsMultiDisplay;
797 } else {
798 mSupportsMultiWindow = false;
799 mSupportsFreeformWindowManagement = false;
800 mSupportsSplitScreenMultiWindow = false;
801 mSupportsPictureInPicture = false;
802 mSupportsMultiDisplay = false;
803 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700804 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 // This happens before any activities are started, so we can change global configuration
806 // in-place.
807 updateConfigurationLocked(configuration, null, true);
808 final Configuration globalConfig = getGlobalConfiguration();
809 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
810
811 // Load resources only after the current configuration has been set.
812 final Resources res = mContext.getResources();
813 mThumbnailWidth = res.getDimensionPixelSize(
814 com.android.internal.R.dimen.thumbnail_width);
815 mThumbnailHeight = res.getDimensionPixelSize(
816 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 }
818 }
819
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800820 public WindowManagerGlobalLock getGlobalLock() {
821 return mGlobalLock;
822 }
823
Yunfan Chen585f2932019-01-29 16:04:45 +0900824 /** For test purpose only. */
825 @VisibleForTesting
826 public ActivityTaskManagerInternal getAtmInternal() {
827 return mInternal;
828 }
829
Riddle Hsud93a6c42018-11-29 21:50:06 +0800830 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
831 Looper looper) {
832 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700835 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800836 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700837 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700838 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700843 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700844 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700845 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700846 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 mKeyguardController = mStackSupervisor.getKeyguardController();
848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void onActivityManagerInternalAdded() {
851 synchronized (mGlobalLock) {
852 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
853 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
854 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 int increaseConfigurationSeqLocked() {
858 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
859 return mConfigurationSeq;
860 }
861
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700862 protected ActivityStackSupervisor createStackSupervisor() {
863 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
864 supervisor.initialize();
865 return supervisor;
866 }
867
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800868 protected AppWarnings createAppWarnings(
869 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
870 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
871 }
872
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 public void setWindowManager(WindowManagerService wm) {
874 synchronized (mGlobalLock) {
875 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800877 mTempConfig.setToDefaults();
878 mTempConfig.setLocales(LocaleList.getDefault());
879 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 mLockTaskController.setWindowManager(wm);
882 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800883 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700885 }
886
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700887 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
888 synchronized (mGlobalLock) {
889 mUsageStatsInternal = usageStatsManager;
890 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700891 }
892
Wale Ogunwalef6733932018-06-27 05:14:34 -0700893 UserManagerService getUserManager() {
894 if (mUserManager == null) {
895 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
896 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
897 }
898 return mUserManager;
899 }
900
901 AppOpsService getAppOpsService() {
902 if (mAppOpsService == null) {
903 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
904 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
905 }
906 return mAppOpsService;
907 }
908
909 boolean hasUserRestriction(String restriction, int userId) {
910 return getUserManager().hasUserRestriction(restriction, userId);
911 }
912
Michal Karpinski15486842019-04-25 17:33:42 +0100913 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
914 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800915 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100916 if (mode == AppOpsManager.MODE_DEFAULT) {
917 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
918 == PERMISSION_GRANTED;
919 }
920 return mode == AppOpsManager.MODE_ALLOWED;
921 }
922
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700923 @VisibleForTesting
924 protected void setRecentTasks(RecentTasks recentTasks) {
925 mRecentTasks = recentTasks;
926 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700927 }
928
929 RecentTasks getRecentTasks() {
930 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700931 }
932
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700933 ClientLifecycleManager getLifecycleManager() {
934 return mLifecycleManager;
935 }
936
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700937 ActivityStartController getActivityStartController() {
938 return mActivityStartController;
939 }
940
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700941 TaskChangeNotificationController getTaskChangeNotificationController() {
942 return mTaskChangeNotificationController;
943 }
944
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700945 LockTaskController getLockTaskController() {
946 return mLockTaskController;
947 }
948
Yunfan Chen75157d72018-07-27 14:47:21 +0900949 /**
950 * Return the global configuration used by the process corresponding to the input pid. This is
951 * usually the global configuration with some overrides specific to that process.
952 */
953 Configuration getGlobalConfigurationForCallingPid() {
954 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800955 return getGlobalConfigurationForPid(pid);
956 }
957
958 /**
959 * Return the global configuration used by the process corresponding to the given pid.
960 */
961 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900962 if (pid == MY_PID || pid < 0) {
963 return getGlobalConfiguration();
964 }
965 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100966 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900967 return app != null ? app.getConfiguration() : getGlobalConfiguration();
968 }
969 }
970
971 /**
972 * Return the device configuration info used by the process corresponding to the input pid.
973 * The value is consistent with the global configuration for the process.
974 */
975 @Override
976 public ConfigurationInfo getDeviceConfigurationInfo() {
977 ConfigurationInfo config = new ConfigurationInfo();
978 synchronized (mGlobalLock) {
979 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
980 config.reqTouchScreen = globalConfig.touchscreen;
981 config.reqKeyboardType = globalConfig.keyboard;
982 config.reqNavigation = globalConfig.navigation;
983 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
984 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
985 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
986 }
987 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
988 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
989 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
990 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700991 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900992 }
993 return config;
994 }
995
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700996 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700997 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700998 }
999
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 public static final class Lifecycle extends SystemService {
1001 private final ActivityTaskManagerService mService;
1002
1003 public Lifecycle(Context context) {
1004 super(context);
1005 mService = new ActivityTaskManagerService(context);
1006 }
1007
1008 @Override
1009 public void onStart() {
1010 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001011 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001012 }
1013
Garfield Tan891146c2018-10-09 12:14:00 -07001014 @Override
1015 public void onUnlockUser(int userId) {
1016 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001017 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001018 }
1019 }
1020
1021 @Override
1022 public void onCleanupUser(int userId) {
1023 synchronized (mService.getGlobalLock()) {
1024 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1025 }
1026 }
1027
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001028 public ActivityTaskManagerService getService() {
1029 return mService;
1030 }
1031 }
1032
1033 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 public final int startActivity(IApplicationThread caller, String callingPackage,
1035 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1036 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1037 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1038 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1039 UserHandle.getCallingUserId());
1040 }
1041
1042 @Override
1043 public final int startActivities(IApplicationThread caller, String callingPackage,
1044 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1045 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001046 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001048 enforceNotIsolatedCaller(reason);
1049 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001051 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1052 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1053 reason, null /* originatingPendingIntent */,
1054 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 }
1056
1057 @Override
1058 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1059 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1060 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1061 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1062 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1063 true /*validateIncomingUser*/);
1064 }
1065
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001066 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1068 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1069 boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001070 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001071 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001073 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1075
1076 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001077 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 .setCaller(caller)
1079 .setCallingPackage(callingPackage)
1080 .setResolvedType(resolvedType)
1081 .setResultTo(resultTo)
1082 .setResultWho(resultWho)
1083 .setRequestCode(requestCode)
1084 .setStartFlags(startFlags)
1085 .setProfilerInfo(profilerInfo)
1086 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001087 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 .execute();
1089
1090 }
1091
1092 @Override
1093 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1094 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001095 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1096 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 // Refuse possible leaked file descriptors
1098 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1099 throw new IllegalArgumentException("File descriptors passed in Intent");
1100 }
1101
1102 if (!(target instanceof PendingIntentRecord)) {
1103 throw new IllegalArgumentException("Bad PendingIntent object");
1104 }
1105
1106 PendingIntentRecord pir = (PendingIntentRecord)target;
1107
1108 synchronized (mGlobalLock) {
1109 // If this is coming from the currently resumed activity, it is
1110 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001111 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 if (stack.mResumedActivity != null &&
1113 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001114 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 }
1116 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001117 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001118 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001119 }
1120
1121 @Override
1122 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1123 Bundle bOptions) {
1124 // Refuse possible leaked file descriptors
1125 if (intent != null && intent.hasFileDescriptors()) {
1126 throw new IllegalArgumentException("File descriptors passed in Intent");
1127 }
1128 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1129
1130 synchronized (mGlobalLock) {
1131 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1132 if (r == null) {
1133 SafeActivityOptions.abort(options);
1134 return false;
1135 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001136 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001137 // The caller is not running... d'oh!
1138 SafeActivityOptions.abort(options);
1139 return false;
1140 }
1141 intent = new Intent(intent);
1142 // The caller is not allowed to change the data.
1143 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1144 // And we are resetting to find the next component...
1145 intent.setComponent(null);
1146
1147 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1148
1149 ActivityInfo aInfo = null;
1150 try {
1151 List<ResolveInfo> resolves =
1152 AppGlobals.getPackageManager().queryIntentActivities(
1153 intent, r.resolvedType,
1154 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1155 UserHandle.getCallingUserId()).getList();
1156
1157 // Look for the original activity in the list...
1158 final int N = resolves != null ? resolves.size() : 0;
1159 for (int i=0; i<N; i++) {
1160 ResolveInfo rInfo = resolves.get(i);
1161 if (rInfo.activityInfo.packageName.equals(r.packageName)
1162 && rInfo.activityInfo.name.equals(r.info.name)) {
1163 // We found the current one... the next matching is
1164 // after it.
1165 i++;
1166 if (i<N) {
1167 aInfo = resolves.get(i).activityInfo;
1168 }
1169 if (debug) {
1170 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1171 + "/" + r.info.name);
1172 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1173 ? "null" : aInfo.packageName + "/" + aInfo.name));
1174 }
1175 break;
1176 }
1177 }
1178 } catch (RemoteException e) {
1179 }
1180
1181 if (aInfo == null) {
1182 // Nobody who is next!
1183 SafeActivityOptions.abort(options);
1184 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1185 return false;
1186 }
1187
1188 intent.setComponent(new ComponentName(
1189 aInfo.applicationInfo.packageName, aInfo.name));
1190 intent.setFlags(intent.getFlags()&~(
1191 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1192 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1193 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1194 FLAG_ACTIVITY_NEW_TASK));
1195
1196 // Okay now we need to start the new activity, replacing the currently running activity.
1197 // This is a little tricky because we want to start the new one as if the current one is
1198 // finished, but not finish the current one first so that there is no flicker.
1199 // And thus...
1200 final boolean wasFinishing = r.finishing;
1201 r.finishing = true;
1202
1203 // Propagate reply information over to the new activity.
1204 final ActivityRecord resultTo = r.resultTo;
1205 final String resultWho = r.resultWho;
1206 final int requestCode = r.requestCode;
1207 r.resultTo = null;
1208 if (resultTo != null) {
1209 resultTo.removeResultsLocked(r, resultWho, requestCode);
1210 }
1211
1212 final long origId = Binder.clearCallingIdentity();
1213 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001214 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001216 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 .setResolvedType(r.resolvedType)
1218 .setActivityInfo(aInfo)
1219 .setResultTo(resultTo != null ? resultTo.appToken : null)
1220 .setResultWho(resultWho)
1221 .setRequestCode(requestCode)
1222 .setCallingPid(-1)
1223 .setCallingUid(r.launchedFromUid)
1224 .setCallingPackage(r.launchedFromPackage)
1225 .setRealCallingPid(-1)
1226 .setRealCallingUid(r.launchedFromUid)
1227 .setActivityOptions(options)
1228 .execute();
1229 Binder.restoreCallingIdentity(origId);
1230
1231 r.finishing = wasFinishing;
1232 if (res != ActivityManager.START_SUCCESS) {
1233 return false;
1234 }
1235 return true;
1236 }
1237 }
1238
1239 @Override
1240 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1241 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1242 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001243 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001245 enforceNotIsolatedCaller("startActivityAndWait");
1246 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1247 userId, "startActivityAndWait");
1248 // TODO: Switch to user app stacks here.
1249 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1250 .setCaller(caller)
1251 .setCallingPackage(callingPackage)
1252 .setResolvedType(resolvedType)
1253 .setResultTo(resultTo)
1254 .setResultWho(resultWho)
1255 .setRequestCode(requestCode)
1256 .setStartFlags(startFlags)
1257 .setActivityOptions(bOptions)
1258 .setUserId(userId)
1259 .setProfilerInfo(profilerInfo)
1260 .setWaitResult(res)
1261 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001262 return res;
1263 }
1264
1265 @Override
1266 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1267 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1268 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001269 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001270 enforceNotIsolatedCaller("startActivityWithConfig");
1271 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1272 "startActivityWithConfig");
1273 // TODO: Switch to user app stacks here.
1274 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1275 .setCaller(caller)
1276 .setCallingPackage(callingPackage)
1277 .setResolvedType(resolvedType)
1278 .setResultTo(resultTo)
1279 .setResultWho(resultWho)
1280 .setRequestCode(requestCode)
1281 .setStartFlags(startFlags)
1282 .setGlobalConfiguration(config)
1283 .setActivityOptions(bOptions)
1284 .setUserId(userId)
1285 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 }
1287
Robert Carr8a2f9132019-11-11 15:03:15 -08001288 @Override
1289 public final void registerTaskOrganizer(ITaskOrganizer organizer, int windowingMode) {
1290 enforceCallerIsRecentsOrHasPermission(
1291 MANAGE_ACTIVITY_STACKS, "registerTaskOrganizer()");
1292 synchronized (mGlobalLock) {
1293 mTaskOrganizerController.registerTaskOrganizer(organizer, windowingMode);
1294 }
1295 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296
1297 @Override
1298 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1299 int callingUid = Binder.getCallingUid();
1300 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1301 throw new SecurityException("Only the system process can request a permission token, "
1302 + "received request from uid: " + callingUid);
1303 }
1304 IBinder permissionToken = new Binder();
1305 synchronized (mGlobalLock) {
1306 mStartActivitySources.put(permissionToken, delegatorToken);
1307 }
1308
1309 Message expireMsg = PooledLambda.obtainMessage(
1310 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1311 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1312
1313 Message forgetMsg = PooledLambda.obtainMessage(
1314 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1315 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1316
1317 return permissionToken;
1318 }
1319
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 @Override
1321 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1322 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1324 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001326 // permission grants) as any app that may launch one of your own activities. So we only
1327 // allow this in two cases:
1328 // 1) The caller is an activity that is part of the core framework, and then only when it
1329 // is running as the system.
1330 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1331 // can only be requested by a system activity, which may then delegate this call to
1332 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001333 final ActivityRecord sourceRecord;
1334 final int targetUid;
1335 final String targetPackage;
1336 final boolean isResolver;
1337 synchronized (mGlobalLock) {
1338 if (resultTo == null) {
1339 throw new SecurityException("Must be called from an activity");
1340 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001341 final IBinder sourceToken;
1342 if (permissionToken != null) {
1343 // To even attempt to use a permissionToken, an app must also have this signature
1344 // permission.
1345 mAmInternal.enforceCallingPermission(
1346 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1347 "startActivityAsCaller");
1348 // If called with a permissionToken, we want the sourceRecord from the delegator
1349 // activity that requested this token.
1350 sourceToken = mStartActivitySources.remove(permissionToken);
1351 if (sourceToken == null) {
1352 // Invalid permissionToken, check if it recently expired.
1353 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1354 throw new SecurityException("Called with expired permission token: "
1355 + permissionToken);
1356 } else {
1357 throw new SecurityException("Called with invalid permission token: "
1358 + permissionToken);
1359 }
1360 }
1361 } else {
1362 // This method was called directly by the source.
1363 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001365
Louis Chang149d5c82019-12-30 09:47:39 +08001366 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001367 if (sourceRecord == null) {
1368 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 }
1370 if (sourceRecord.app == null) {
1371 throw new SecurityException("Called without a process attached to activity");
1372 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001373
1374 // Whether called directly or from a delegate, the source activity must be from the
1375 // android package.
1376 if (!sourceRecord.info.packageName.equals("android")) {
1377 throw new SecurityException("Must be called from an activity that is "
1378 + "declared in the android package");
1379 }
1380
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001381 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 // This is still okay, as long as this activity is running under the
1383 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001384 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001386 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 + " must be system uid or original calling uid "
1388 + sourceRecord.launchedFromUid);
1389 }
1390 }
1391 if (ignoreTargetSecurity) {
1392 if (intent.getComponent() == null) {
1393 throw new SecurityException(
1394 "Component must be specified with ignoreTargetSecurity");
1395 }
1396 if (intent.getSelector() != null) {
1397 throw new SecurityException(
1398 "Selector not allowed with ignoreTargetSecurity");
1399 }
1400 }
1401 targetUid = sourceRecord.launchedFromUid;
1402 targetPackage = sourceRecord.launchedFromPackage;
1403 isResolver = sourceRecord.isResolverOrChildActivity();
1404 }
1405
1406 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001407 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 }
1409
1410 // TODO: Switch to user app stacks here.
1411 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001412 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 .setCallingUid(targetUid)
1414 .setCallingPackage(targetPackage)
1415 .setResolvedType(resolvedType)
1416 .setResultTo(resultTo)
1417 .setResultWho(resultWho)
1418 .setRequestCode(requestCode)
1419 .setStartFlags(startFlags)
1420 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001421 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1423 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001424 // The target may well be in the background, which would normally prevent it
1425 // from starting an activity. Here we definitely want the start to succeed.
1426 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .execute();
1428 } catch (SecurityException e) {
1429 // XXX need to figure out how to propagate to original app.
1430 // A SecurityException here is generally actually a fault of the original
1431 // calling activity (such as a fairly granting permissions), so propagate it
1432 // back to them.
1433 /*
1434 StringBuilder msg = new StringBuilder();
1435 msg.append("While launching");
1436 msg.append(intent.toString());
1437 msg.append(": ");
1438 msg.append(e.getMessage());
1439 */
1440 throw e;
1441 }
1442 }
1443
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001444 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1445 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001446 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001447 }
1448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 @Override
1450 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1451 Intent intent, String resolvedType, IVoiceInteractionSession session,
1452 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1453 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001454 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 if (session == null || interactor == null) {
1457 throw new NullPointerException("null session or interactor");
1458 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001459 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001461 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setCallingUid(callingUid)
1463 .setCallingPackage(callingPackage)
1464 .setResolvedType(resolvedType)
1465 .setVoiceSession(session)
1466 .setVoiceInteractor(interactor)
1467 .setStartFlags(startFlags)
1468 .setProfilerInfo(profilerInfo)
1469 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001470 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001471 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 .execute();
1473 }
1474
1475 @Override
1476 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1477 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001478 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1480 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001482 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 .setCallingUid(callingUid)
1484 .setCallingPackage(callingPackage)
1485 .setResolvedType(resolvedType)
1486 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001487 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001488 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 .execute();
1490 }
1491
Riddle Hsu609a8e22019-06-27 16:46:29 -06001492 /**
1493 * Start the recents activity to perform the recents animation.
1494 *
1495 * @param intent The intent to start the recents activity.
1496 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1497 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001498 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001499 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1500 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001503 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 final long origId = Binder.clearCallingIdentity();
1505 try {
1506 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001507 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1508 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001509 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510
1511 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001513 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001514 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001515 if (recentsAnimationRunner == null) {
1516 anim.preloadRecentsActivity();
1517 } else {
1518 anim.startRecentsActivity(recentsAnimationRunner);
1519 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 }
1521 } finally {
1522 Binder.restoreCallingIdentity(origId);
1523 }
1524 }
1525
1526 @Override
1527 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001528 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529 "startActivityFromRecents()");
1530
1531 final int callingPid = Binder.getCallingPid();
1532 final int callingUid = Binder.getCallingUid();
1533 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1534 final long origId = Binder.clearCallingIdentity();
1535 try {
1536 synchronized (mGlobalLock) {
1537 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1538 safeOptions);
1539 }
1540 } finally {
1541 Binder.restoreCallingIdentity(origId);
1542 }
1543 }
1544
1545 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001546 * Public API to check if the client is allowed to start an activity on specified display.
1547 *
1548 * If the target display is private or virtual, some restrictions will apply.
1549 *
1550 * @param displayId Target display id.
1551 * @param intent Intent used to launch the activity.
1552 * @param resolvedType The MIME type of the intent.
1553 * @param userId The id of the user for whom the call is made.
1554 * @return {@code true} if a call to start an activity on the target display should succeed and
1555 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1556 */
1557 @Override
1558 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1559 String resolvedType, int userId) {
1560 final int callingUid = Binder.getCallingUid();
1561 final int callingPid = Binder.getCallingPid();
1562 final long origId = Binder.clearCallingIdentity();
1563
1564 try {
1565 // Collect information about the target of the Intent.
1566 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1567 0 /* startFlags */, null /* profilerInfo */, userId,
1568 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1569 UserHandle.USER_NULL));
1570 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1571
1572 synchronized (mGlobalLock) {
1573 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1574 aInfo);
1575 }
1576 } finally {
1577 Binder.restoreCallingIdentity(origId);
1578 }
1579 }
1580
1581 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 * This is the internal entry point for handling Activity.finish().
1583 *
1584 * @param token The Binder token referencing the Activity we want to finish.
1585 * @param resultCode Result code, if any, from this Activity.
1586 * @param resultData Result data (Intent), if any, from this Activity.
1587 * @param finishTask Whether to finish the task associated with this Activity.
1588 *
1589 * @return Returns true if the activity successfully finished, or false if it is still running.
1590 */
1591 @Override
1592 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1593 int finishTask) {
1594 // Refuse possible leaked file descriptors
1595 if (resultData != null && resultData.hasFileDescriptors()) {
1596 throw new IllegalArgumentException("File descriptors passed in Intent");
1597 }
1598
1599 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001600 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 if (r == null) {
1602 return true;
1603 }
1604 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001605 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001606 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001607 if (rootR == null) {
1608 Slog.w(TAG, "Finishing task with all activities already finished");
1609 }
1610 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1611 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001612 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 return false;
1614 }
1615
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001616 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1617 // We should consolidate.
1618 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001620 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001621 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 if (next != null) {
1623 // ask watcher if this is allowed
1624 boolean resumeOK = true;
1625 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001626 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001627 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001628 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 Watchdog.getInstance().setActivityController(null);
1630 }
1631
1632 if (!resumeOK) {
1633 Slog.i(TAG, "Not finishing activity because controller resumed");
1634 return false;
1635 }
1636 }
1637 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001638
1639 // note down that the process has finished an activity and is in background activity
1640 // starts grace period
1641 if (r.app != null) {
1642 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1643 }
1644
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001646 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 try {
1648 boolean res;
1649 final boolean finishWithRootActivity =
1650 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1651 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1652 || (finishWithRootActivity && r == rootR)) {
1653 // If requested, remove the task that is associated to this activity only if it
1654 // was the root activity in the task. The result code and data is ignored
1655 // because we don't support returning them across task boundaries. Also, to
1656 // keep backwards compatibility we remove the task from recents when finishing
1657 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001658 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001660 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001661 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001662 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001664 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001665 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 if (!res) {
1667 Slog.i(TAG, "Failed to finish by app-request");
1668 }
1669 }
1670 return res;
1671 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001672 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 Binder.restoreCallingIdentity(origId);
1674 }
1675 }
1676 }
1677
1678 @Override
1679 public boolean finishActivityAffinity(IBinder token) {
1680 synchronized (mGlobalLock) {
1681 final long origId = Binder.clearCallingIdentity();
1682 try {
1683 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1684 if (r == null) {
1685 return false;
1686 }
1687
1688 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1689 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001690 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 return false;
1692 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001693
1694 final PooledFunction p = PooledLambda.obtainFunction(
1695 ActivityRecord::finishIfSameAffinity, r,
1696 PooledLambda.__(ActivityRecord.class));
1697 r.getTask().forAllActivities(
1698 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1699 p.recycle();
1700
Andrii Kuliande93eff2019-07-12 12:21:27 -07001701 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 } finally {
1703 Binder.restoreCallingIdentity(origId);
1704 }
1705 }
1706 }
1707
1708 @Override
1709 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1710 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001711 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001712 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001713 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001714 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1715 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001716 return;
1717 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001718 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1719 false /* processPausingActivities */, config);
1720 if (stopProfiling && r.hasProcess()) {
1721 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 }
1723 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001724 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001725 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001726 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 }
1729
1730 @Override
1731 public final void activityResumed(IBinder token) {
1732 final long origId = Binder.clearCallingIdentity();
1733 synchronized (mGlobalLock) {
1734 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 }
1736 Binder.restoreCallingIdentity(origId);
1737 }
1738
1739 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001740 public final void activityTopResumedStateLost() {
1741 final long origId = Binder.clearCallingIdentity();
1742 synchronized (mGlobalLock) {
1743 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1744 }
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747
1748 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 public final void activityPaused(IBinder token) {
1750 final long origId = Binder.clearCallingIdentity();
1751 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001752 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001753 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1754 if (r != null) {
1755 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 }
1759 Binder.restoreCallingIdentity(origId);
1760 }
1761
1762 @Override
1763 public final void activityStopped(IBinder token, Bundle icicle,
1764 PersistableBundle persistentState, CharSequence description) {
1765 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1766
1767 // Refuse possible leaked file descriptors
1768 if (icicle != null && icicle.hasFileDescriptors()) {
1769 throw new IllegalArgumentException("File descriptors passed in Bundle");
1770 }
1771
1772 final long origId = Binder.clearCallingIdentity();
1773
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001774 String restartingName = null;
1775 int restartingUid = 0;
1776 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001778 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001779 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001780 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001781 if (r.attachedToProcess()
1782 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1783 // The activity was requested to restart from
1784 // {@link #restartActivityProcessIfVisible}.
1785 restartingName = r.app.mName;
1786 restartingUid = r.app.mUid;
1787 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001788 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001790 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001793 if (restartingName != null) {
1794 // In order to let the foreground activity can be restarted with its saved state from
1795 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1796 // until the activity reports stopped with the state. And the activity record will be
1797 // kept because the record state is restarting, then the activity will be restarted
1798 // immediately if it is still the top one.
1799 mStackSupervisor.removeRestartTimeouts(r);
1800 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1801 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803
1804 Binder.restoreCallingIdentity(origId);
1805 }
1806
1807 @Override
1808 public final void activityDestroyed(IBinder token) {
1809 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1810 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001811 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001812 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001813 try {
1814 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1815 if (activity != null) {
1816 activity.destroyed("activityDestroyed");
1817 }
1818 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001819 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001820 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 }
1822 }
1823 }
1824
1825 @Override
1826 public final void activityRelaunched(IBinder token) {
1827 final long origId = Binder.clearCallingIdentity();
1828 synchronized (mGlobalLock) {
1829 mStackSupervisor.activityRelaunchedLocked(token);
1830 }
1831 Binder.restoreCallingIdentity(origId);
1832 }
1833
1834 public final void activitySlept(IBinder token) {
1835 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1836
1837 final long origId = Binder.clearCallingIdentity();
1838
1839 synchronized (mGlobalLock) {
1840 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1841 if (r != null) {
1842 mStackSupervisor.activitySleptLocked(r);
1843 }
1844 }
1845
1846 Binder.restoreCallingIdentity(origId);
1847 }
1848
1849 @Override
1850 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1851 synchronized (mGlobalLock) {
1852 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1853 if (r == null) {
1854 return;
1855 }
1856 final long origId = Binder.clearCallingIdentity();
1857 try {
1858 r.setRequestedOrientation(requestedOrientation);
1859 } finally {
1860 Binder.restoreCallingIdentity(origId);
1861 }
1862 }
1863 }
1864
1865 @Override
1866 public int getRequestedOrientation(IBinder token) {
1867 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001868 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1869 return (r != null)
1870 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 }
1872 }
1873
1874 @Override
1875 public void setImmersive(IBinder token, boolean immersive) {
1876 synchronized (mGlobalLock) {
1877 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1878 if (r == null) {
1879 throw new IllegalArgumentException();
1880 }
1881 r.immersive = immersive;
1882
1883 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001884 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 }
1888 }
1889 }
1890
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 void applyUpdateLockStateLocked(ActivityRecord r) {
1892 // Modifications to the UpdateLock state are done on our handler, outside
1893 // the activity manager's locks. The new state is determined based on the
1894 // state *now* of the relevant activity record. The object is passed to
1895 // the handler solely for logging detail, not to be consulted/modified.
1896 final boolean nextState = r != null && r.immersive;
1897 mH.post(() -> {
1898 if (mUpdateLock.isHeld() != nextState) {
1899 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1900 "Applying new update lock state '" + nextState + "' for " + r);
1901 if (nextState) {
1902 mUpdateLock.acquire();
1903 } else {
1904 mUpdateLock.release();
1905 }
1906 }
1907 });
1908 }
1909
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 @Override
1911 public boolean isImmersive(IBinder token) {
1912 synchronized (mGlobalLock) {
1913 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 throw new IllegalArgumentException();
1916 }
1917 return r.immersive;
1918 }
1919 }
1920
1921 @Override
1922 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001925 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 return (r != null) ? r.immersive : false;
1927 }
1928 }
1929
1930 @Override
1931 public void overridePendingTransition(IBinder token, String packageName,
1932 int enterAnim, int exitAnim) {
1933 synchronized (mGlobalLock) {
1934 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1935 if (self == null) {
1936 return;
1937 }
1938
1939 final long origId = Binder.clearCallingIdentity();
1940
1941 if (self.isState(
1942 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001943 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001944 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946
1947 Binder.restoreCallingIdentity(origId);
1948 }
1949 }
1950
1951 @Override
1952 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001953 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001955 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 if (r == null) {
1957 return ActivityManager.COMPAT_MODE_UNKNOWN;
1958 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001959 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 }
1962
1963 @Override
1964 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001965 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001967 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001969 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001970 if (r == null) {
1971 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1972 return;
1973 }
1974 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001975 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 }
1978
1979 @Override
1980 public int getLaunchedFromUid(IBinder activityToken) {
1981 ActivityRecord srec;
1982 synchronized (mGlobalLock) {
1983 srec = ActivityRecord.forTokenLocked(activityToken);
1984 }
1985 if (srec == null) {
1986 return -1;
1987 }
1988 return srec.launchedFromUid;
1989 }
1990
1991 @Override
1992 public String getLaunchedFromPackage(IBinder activityToken) {
1993 ActivityRecord srec;
1994 synchronized (mGlobalLock) {
1995 srec = ActivityRecord.forTokenLocked(activityToken);
1996 }
1997 if (srec == null) {
1998 return null;
1999 }
2000 return srec.launchedFromPackage;
2001 }
2002
2003 @Override
2004 public boolean convertFromTranslucent(IBinder token) {
2005 final long origId = Binder.clearCallingIdentity();
2006 try {
2007 synchronized (mGlobalLock) {
2008 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2009 if (r == null) {
2010 return false;
2011 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002012 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(origId);
2016 }
2017 }
2018
2019 @Override
2020 public boolean convertToTranslucent(IBinder token, Bundle options) {
2021 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2022 final long origId = Binder.clearCallingIdentity();
2023 try {
2024 synchronized (mGlobalLock) {
2025 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2026 if (r == null) {
2027 return false;
2028 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002029 final ActivityRecord under = r.getTask().getActivityBelow(r);
2030 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2032 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002033 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 }
2035 } finally {
2036 Binder.restoreCallingIdentity(origId);
2037 }
2038 }
2039
2040 @Override
2041 public void notifyActivityDrawn(IBinder token) {
2042 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2043 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002044 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002046 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 }
2048 }
2049 }
2050
2051 @Override
2052 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2053 synchronized (mGlobalLock) {
2054 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2055 if (r == null) {
2056 return;
2057 }
2058 r.reportFullyDrawnLocked(restoredFromBundle);
2059 }
2060 }
2061
2062 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002063 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 synchronized (mGlobalLock) {
2065 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002066 if (stack != null) {
2067 final int displayId = stack.getDisplayId();
2068 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 }
2070 return DEFAULT_DISPLAY;
2071 }
2072 }
2073
2074 @Override
2075 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 long ident = Binder.clearCallingIdentity();
2078 try {
2079 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002080 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002082 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 }
2084 return null;
2085 }
2086 } finally {
2087 Binder.restoreCallingIdentity(ident);
2088 }
2089 }
2090
2091 @Override
2092 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002093 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002098 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 if (stack == null) {
2100 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2101 return;
2102 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002103 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002104 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002105 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 }
2107 }
2108 } finally {
2109 Binder.restoreCallingIdentity(callingId);
2110 }
2111 }
2112
2113 @Override
2114 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002115 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2117 final long callingId = Binder.clearCallingIdentity();
2118 try {
2119 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002120 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002121 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 if (task == null) {
2123 return;
2124 }
2125 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002126 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002127 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 }
2129 }
2130 } finally {
2131 Binder.restoreCallingIdentity(callingId);
2132 }
2133 }
2134
2135 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002136 public void restartActivityProcessIfVisible(IBinder activityToken) {
2137 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2138 final long callingId = Binder.clearCallingIdentity();
2139 try {
2140 synchronized (mGlobalLock) {
2141 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2142 if (r == null) {
2143 return;
2144 }
2145 r.restartProcessIfVisible();
2146 }
2147 } finally {
2148 Binder.restoreCallingIdentity(callingId);
2149 }
2150 }
2151
2152 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002154 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 synchronized (mGlobalLock) {
2156 final long ident = Binder.clearCallingIdentity();
2157 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002158 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 "remove-task");
2160 } finally {
2161 Binder.restoreCallingIdentity(ident);
2162 }
2163 }
2164 }
2165
2166 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002167 public void removeAllVisibleRecentTasks() {
2168 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2169 synchronized (mGlobalLock) {
2170 final long ident = Binder.clearCallingIdentity();
2171 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002172 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002173 } finally {
2174 Binder.restoreCallingIdentity(ident);
2175 }
2176 }
2177 }
2178
2179 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2181 synchronized (mGlobalLock) {
2182 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2183 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002184 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 }
2186 }
2187 return false;
2188 }
2189
2190 @Override
2191 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2192 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002193
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002194 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002195 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2196 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002197 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002198 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002199 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002200 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 }
2202 }
2203
2204 /**
2205 * Attempts to move a task backwards in z-order (the order of activities within the task is
2206 * unchanged).
2207 *
2208 * There are several possible results of this call:
2209 * - if the task is locked, then we will show the lock toast
2210 * - if there is a task behind the provided task, then that task is made visible and resumed as
2211 * this task is moved to the back
2212 * - otherwise, if there are no other tasks in the stack:
2213 * - if this task is in the pinned stack, then we remove the stack completely, which will
2214 * have the effect of moving the task to the top or bottom of the fullscreen stack
2215 * (depending on whether it is visible)
2216 * - otherwise, we simply return home and hide this task
2217 *
2218 * @param token A reference to the activity we wish to move
2219 * @param nonRoot If false then this only works if the activity is the root
2220 * of a task; if true it will work for any activity in a task.
2221 * @return Returns true if the move completed, false if not.
2222 */
2223 @Override
2224 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002225 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 synchronized (mGlobalLock) {
2227 final long origId = Binder.clearCallingIdentity();
2228 try {
2229 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002230 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002231 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002232 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 }
2234 } finally {
2235 Binder.restoreCallingIdentity(origId);
2236 }
2237 }
2238 return false;
2239 }
2240
2241 @Override
2242 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 long ident = Binder.clearCallingIdentity();
2245 Rect rect = new Rect();
2246 try {
2247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002248 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2250 if (task == null) {
2251 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2252 return rect;
2253 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002254 if (task.getParent() != null) {
2255 rect.set(task.getBounds());
2256 } else if (task.mLastNonFullscreenBounds != null) {
2257 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002258 }
2259 }
2260 } finally {
2261 Binder.restoreCallingIdentity(ident);
2262 }
2263 return rect;
2264 }
2265
2266 @Override
2267 public ActivityManager.TaskDescription getTaskDescription(int id) {
2268 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002269 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002271 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002272 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2273 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002274 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 }
2276 }
2277 return null;
2278 }
2279
2280 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002281 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2282 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2283 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2284 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2285 return;
2286 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002287 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002288 synchronized (mGlobalLock) {
2289 final long ident = Binder.clearCallingIdentity();
2290 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002291 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002292 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002293 if (task == null) {
2294 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2295 return;
2296 }
2297
2298 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2299 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2300
2301 if (!task.isActivityTypeStandardOrUndefined()) {
2302 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2303 + " non-standard task " + taskId + " to windowing mode="
2304 + windowingMode);
2305 }
2306
2307 final ActivityStack stack = task.getStack();
2308 if (toTop) {
2309 stack.moveToFront("setTaskWindowingMode", task);
2310 }
2311 stack.setWindowingMode(windowingMode);
2312 } finally {
2313 Binder.restoreCallingIdentity(ident);
2314 }
2315 }
2316 }
2317
2318 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002320 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321 ActivityRecord r = getCallingRecordLocked(token);
2322 return r != null ? r.info.packageName : null;
2323 }
2324 }
2325
2326 @Override
2327 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 ActivityRecord r = getCallingRecordLocked(token);
2330 return r != null ? r.intent.getComponent() : null;
2331 }
2332 }
2333
2334 private ActivityRecord getCallingRecordLocked(IBinder token) {
2335 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2336 if (r == null) {
2337 return null;
2338 }
2339 return r.resultTo;
2340 }
2341
2342 @Override
2343 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345
2346 synchronized (mGlobalLock) {
2347 final long origId = Binder.clearCallingIdentity();
2348 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002349 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 } finally {
2351 Binder.restoreCallingIdentity(origId);
2352 }
2353 }
2354 }
2355
Mark Renouf446251d2019-04-26 10:22:41 -04002356 @Override
2357 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2358 synchronized (mGlobalLock) {
2359 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2360 if (r == null) {
2361 return;
2362 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002363 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002364 if (stack != null && stack.isSingleTaskInstance()) {
2365 // Single-task stacks are used for activities which are presented in floating
2366 // windows above full screen activities. Instead of directly finishing the
2367 // task, a task change listener is used to notify SystemUI so the action can be
2368 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002369 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002370 mTaskChangeNotificationController
2371 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2372 } else {
2373 try {
2374 callback.requestFinish();
2375 } catch (RemoteException e) {
2376 Slog.e(TAG, "Failed to invoke request finish callback", e);
2377 }
2378 }
2379 }
2380 }
2381
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 /**
2383 * TODO: Add mController hook
2384 */
2385 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2387 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002388 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389
2390 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2391 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2393 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 }
2395 }
2396
Ricky Waiaca8a772019-04-04 16:01:06 +01002397 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2398 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002400 final int callingPid = Binder.getCallingPid();
2401 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002402 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002403 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 SafeActivityOptions.abort(options);
2405 return;
2406 }
2407 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002408 WindowProcessController callerApp = null;
2409 if (appThread != null) {
2410 callerApp = getProcessController(appThread);
2411 }
2412 final ActivityStarter starter = getActivityStartController().obtainStarter(
2413 null /* intent */, "moveTaskToFront");
2414 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2415 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002416 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002417 return;
2418 }
2419 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002421 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002422 if (task == null) {
2423 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002424 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 return;
2426 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002427 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002429 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 return;
2431 }
2432 ActivityOptions realOptions = options != null
2433 ? options.getOptions(mStackSupervisor)
2434 : null;
2435 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2436 false /* forceNonResizable */);
2437
Wale Ogunwale21e06482019-11-18 05:14:15 -08002438 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002439 if (topActivity != null) {
2440
2441 // We are reshowing a task, use a starting window to hide the initial draw delay
2442 // so the transition can start earlier.
2443 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2444 true /* taskSwitch */, fromRecents);
2445 }
2446 } finally {
2447 Binder.restoreCallingIdentity(origId);
2448 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449 }
2450
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 /**
2452 * Return true if callingUid is system, or packageName belongs to that callingUid.
2453 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002454 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002455 try {
2456 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2457 if (packageName == null) {
2458 return false;
2459 }
2460 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2461 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2462 UserHandle.getUserId(callingUid));
2463 return UserHandle.isSameApp(callingUid, uid);
2464 }
2465 } catch (RemoteException e) {
2466 // Should not happen
2467 }
2468 return true;
2469 }
2470
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002471 /**
2472 * Checks that the provided package name matches the current calling UID, throws a security
2473 * exception if it doesn't.
2474 */
2475 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2476 final int callingUid = Binder.getCallingUid();
2477 if (isSameApp(callingUid, packageName)) {
2478 return;
2479 }
2480 final String msg = "Permission Denial: package=" + packageName
2481 + " does not belong to uid=" + callingUid;
2482 Slog.w(TAG, msg);
2483 throw new SecurityException(msg);
2484 }
2485
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002486 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2487 int callingPid, int callingUid, String name) {
2488 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2489 return true;
2490 }
2491
2492 if (getRecentTasks().isCallerRecents(sourceUid)) {
2493 return true;
2494 }
2495
2496 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2497 if (perm == PackageManager.PERMISSION_GRANTED) {
2498 return true;
2499 }
2500 if (checkAllowAppSwitchUid(sourceUid)) {
2501 return true;
2502 }
2503
2504 // If the actual IPC caller is different from the logical source, then
2505 // also see if they are allowed to control app switches.
2506 if (callingUid != -1 && callingUid != sourceUid) {
2507 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2508 if (perm == PackageManager.PERMISSION_GRANTED) {
2509 return true;
2510 }
2511 if (checkAllowAppSwitchUid(callingUid)) {
2512 return true;
2513 }
2514 }
2515
2516 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2517 return false;
2518 }
2519
2520 private boolean checkAllowAppSwitchUid(int uid) {
2521 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2522 if (types != null) {
2523 for (int i = types.size() - 1; i >= 0; i--) {
2524 if (types.valueAt(i).intValue() == uid) {
2525 return true;
2526 }
2527 }
2528 }
2529 return false;
2530 }
2531
2532 @Override
2533 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2534 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2535 "setActivityController()");
2536 synchronized (mGlobalLock) {
2537 mController = controller;
2538 mControllerIsAMonkey = imAMonkey;
2539 Watchdog.getInstance().setActivityController(controller);
2540 }
2541 }
2542
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002543 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 synchronized (mGlobalLock) {
2545 return mController != null && mControllerIsAMonkey;
2546 }
2547 }
2548
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 @Override
2550 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2551 synchronized (mGlobalLock) {
2552 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2553 }
2554 }
2555
2556 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2558 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2559 }
2560
2561 @Override
2562 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2563 @WindowConfiguration.ActivityType int ignoreActivityType,
2564 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2565 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002566 final int callingPid = Binder.getCallingPid();
2567 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002568 final int[] profileIds = getUserManager().getProfileIds(
2569 UserHandle.getUserId(callingUid), true);
2570 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2571 for (int i = 0; i < profileIds.length; i++) {
2572 callingProfileIds.add(profileIds[i]);
2573 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002574 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2575
2576 synchronized (mGlobalLock) {
2577 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2578
Nicholas Sauer0259e532019-08-30 08:24:55 -07002579 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002580 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002581 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 }
2583
2584 return list;
2585 }
2586
2587 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002588 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2589 synchronized (mGlobalLock) {
2590 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002591 try {
2592 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2593 if (r == null) return;
2594
2595 final PooledConsumer c = PooledLambda.obtainConsumer(
2596 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2597 r, resultWho, requestCode);
2598 // TODO: This should probably only loop over the task since you need to be in the
2599 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002600 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002601 c.recycle();
2602
2603 updateOomAdj();
2604 } finally {
2605 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002606 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 }
2608 }
2609
2610 @Override
2611 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002612 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002613 ActivityStack stack = ActivityRecord.getStackLocked(token);
2614 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002615 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002616 }
2617 return false;
2618 }
2619 }
2620
2621 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002623 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 synchronized (mGlobalLock) {
2625 final long ident = Binder.clearCallingIdentity();
2626 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002627 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 if (task == null) {
2629 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2630 return;
2631 }
2632
2633 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2634 + " to stackId=" + stackId + " toTop=" + toTop);
2635
Louis Chang149d5c82019-12-30 09:47:39 +08002636 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 if (stack == null) {
2638 throw new IllegalStateException(
2639 "moveTaskToStack: No stack for stackId=" + stackId);
2640 }
2641 if (!stack.isActivityTypeStandardOrUndefined()) {
2642 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2643 + taskId + " to stack " + stackId);
2644 }
2645 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002646 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002647 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2648 }
2649 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2650 "moveTaskToStack");
2651 } finally {
2652 Binder.restoreCallingIdentity(ident);
2653 }
2654 }
2655 }
2656
2657 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002658 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2659 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002660
2661 final long ident = Binder.clearCallingIdentity();
2662 try {
2663 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002664 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002665 if (stack == null) {
2666 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2667 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002669 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2670 throw new IllegalArgumentException("Stack: " + stackId
2671 + " doesn't support animated resize.");
2672 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002673 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002674 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 }
2676 } finally {
2677 Binder.restoreCallingIdentity(ident);
2678 }
2679 }
2680
wilsonshih5c4cf522019-01-25 09:03:47 +08002681 @Override
2682 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2683 int animationDuration) {
2684 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2685
2686 final long ident = Binder.clearCallingIdentity();
2687 try {
2688 synchronized (mGlobalLock) {
2689 if (xOffset == 0 && yOffset == 0) {
2690 return;
2691 }
Louis Chang149d5c82019-12-30 09:47:39 +08002692 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002693 if (stack == null) {
2694 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2695 return;
2696 }
2697 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2698 throw new IllegalArgumentException("Stack: " + stackId
2699 + " doesn't support animated resize.");
2700 }
2701 final Rect destBounds = new Rect();
2702 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002703 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002704 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2705 return;
2706 }
2707 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002708 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002709 animationDuration, false /* fromFullscreen */);
2710 }
2711 } finally {
2712 Binder.restoreCallingIdentity(ident);
2713 }
2714 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 /**
2716 * Moves the specified task to the primary-split-screen stack.
2717 *
2718 * @param taskId Id of task to move.
2719 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2720 * exist already. See
2721 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2722 * and
2723 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2724 * @param toTop If the task and stack should be moved to the top.
2725 * @param animate Whether we should play an animation for the moving the task.
2726 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2727 * stack. Pass {@code null} to use default bounds.
2728 * @param showRecents If the recents activity should be shown on the other side of the task
2729 * going into split-screen mode.
2730 */
2731 @Override
2732 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2733 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002735 "setTaskWindowingModeSplitScreenPrimary()");
2736 synchronized (mGlobalLock) {
2737 final long ident = Binder.clearCallingIdentity();
2738 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002739 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002740 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002741 if (task == null) {
2742 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2743 return false;
2744 }
2745 if (DEBUG_STACK) Slog.d(TAG_STACK,
2746 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2747 + " to createMode=" + createMode + " toTop=" + toTop);
2748 if (!task.isActivityTypeStandardOrUndefined()) {
2749 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2750 + " non-standard task " + taskId + " to split-screen windowing mode");
2751 }
2752
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002753 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002754 final int windowingMode = task.getWindowingMode();
2755 final ActivityStack stack = task.getStack();
2756 if (toTop) {
2757 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2758 }
2759 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002760 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2761 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002762 return windowingMode != task.getWindowingMode();
2763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
2766 }
2767 }
2768
2769 /**
2770 * Removes stacks in the input windowing modes from the system if they are of activity type
2771 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2772 */
2773 @Override
2774 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002776 "removeStacksInWindowingModes()");
2777
2778 synchronized (mGlobalLock) {
2779 final long ident = Binder.clearCallingIdentity();
2780 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002781 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002782 } finally {
2783 Binder.restoreCallingIdentity(ident);
2784 }
2785 }
2786 }
2787
2788 @Override
2789 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002790 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002791 "removeStacksWithActivityTypes()");
2792
2793 synchronized (mGlobalLock) {
2794 final long ident = Binder.clearCallingIdentity();
2795 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002796 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002797 } finally {
2798 Binder.restoreCallingIdentity(ident);
2799 }
2800 }
2801 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802
2803 @Override
2804 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2805 int userId) {
2806 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2808 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 final boolean detailed = checkGetTasksPermission(
2811 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2812 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 == PackageManager.PERMISSION_GRANTED;
2814
2815 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002816 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 callingUid);
2818 }
2819 }
2820
2821 @Override
2822 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002823 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 long ident = Binder.clearCallingIdentity();
2825 try {
2826 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002827 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002836 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 long ident = Binder.clearCallingIdentity();
2838 try {
2839 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002840 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 }
2842 } finally {
2843 Binder.restoreCallingIdentity(ident);
2844 }
2845 }
2846
2847 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002848 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2849 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2850 long ident = Binder.clearCallingIdentity();
2851 try {
2852 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002853 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002854 }
2855 } finally {
2856 Binder.restoreCallingIdentity(ident);
2857 }
2858 }
2859
2860 @Override
2861 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2862 int displayId) {
2863 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2864 long ident = Binder.clearCallingIdentity();
2865 try {
2866 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002867 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002868 }
2869 } finally {
2870 Binder.restoreCallingIdentity(ident);
2871 }
2872 }
2873
2874 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002876 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 final long callingUid = Binder.getCallingUid();
2878 final long origId = Binder.clearCallingIdentity();
2879 try {
2880 synchronized (mGlobalLock) {
2881 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002882 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2884 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2885 }
2886 } finally {
2887 Binder.restoreCallingIdentity(origId);
2888 }
2889 }
2890
2891 @Override
2892 public void startLockTaskModeByToken(IBinder token) {
2893 synchronized (mGlobalLock) {
2894 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2895 if (r == null) {
2896 return;
2897 }
Louis Changcdec0802019-11-11 11:45:07 +08002898 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899 }
2900 }
2901
2902 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002903 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002904 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002905 // This makes inner call to look as if it was initiated by system.
2906 long ident = Binder.clearCallingIdentity();
2907 try {
2908 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002909 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002910 MATCH_TASK_IN_STACKS_ONLY);
2911 if (task == null) {
2912 return;
2913 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914
2915 // When starting lock task mode the stack must be in front and focused
2916 task.getStack().moveToFront("startSystemLockTaskMode");
2917 startLockTaskModeLocked(task, true /* isSystemCaller */);
2918 }
2919 } finally {
2920 Binder.restoreCallingIdentity(ident);
2921 }
2922 }
2923
2924 @Override
2925 public void stopLockTaskModeByToken(IBinder token) {
2926 synchronized (mGlobalLock) {
2927 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2928 if (r == null) {
2929 return;
2930 }
Louis Changcdec0802019-11-11 11:45:07 +08002931 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932 }
2933 }
2934
2935 /**
2936 * This API should be called by SystemUI only when user perform certain action to dismiss
2937 * lock task mode. We should only dismiss pinned lock task mode in this case.
2938 */
2939 @Override
2940 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2943 }
2944
Louis Changcdec0802019-11-11 11:45:07 +08002945 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2947 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2948 return;
2949 }
2950
Louis Chang149d5c82019-12-30 09:47:39 +08002951 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002952 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 throw new IllegalArgumentException("Invalid task, not in foreground");
2954 }
2955
2956 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2957 // system or a specific app.
2958 // * System-initiated requests will only start the pinned mode (screen pinning)
2959 // * App-initiated requests
2960 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2961 // - will start the pinned mode, otherwise
2962 final int callingUid = Binder.getCallingUid();
2963 long ident = Binder.clearCallingIdentity();
2964 try {
2965 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002966 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002967
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002968 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
Louis Changcdec0802019-11-11 11:45:07 +08002974 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 final int callingUid = Binder.getCallingUid();
2976 long ident = Binder.clearCallingIdentity();
2977 try {
2978 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002979 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 }
2981 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2982 // task and jumping straight into a call in the case of emergency call back.
2983 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2984 if (tm != null) {
2985 tm.showInCallScreen(false);
2986 }
2987 } finally {
2988 Binder.restoreCallingIdentity(ident);
2989 }
2990 }
2991
2992 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002993 public void updateLockTaskPackages(int userId, String[] packages) {
2994 final int callingUid = Binder.getCallingUid();
2995 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2996 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2997 "updateLockTaskPackages()");
2998 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002999 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003000 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3001 + Arrays.toString(packages));
3002 getLockTaskController().updateLockTaskPackages(userId, packages);
3003 }
3004 }
3005
3006 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007 public boolean isInLockTaskMode() {
3008 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3009 }
3010
3011 @Override
3012 public int getLockTaskModeState() {
3013 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003014 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015 }
3016 }
3017
3018 @Override
3019 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3020 synchronized (mGlobalLock) {
3021 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3022 if (r != null) {
3023 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003024 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 }
3027 }
3028 }
3029
3030 @Override
3031 public Bundle getActivityOptions(IBinder token) {
3032 final long origId = Binder.clearCallingIdentity();
3033 try {
3034 synchronized (mGlobalLock) {
3035 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3036 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003037 final ActivityOptions activityOptions = r.takeOptionsLocked(
3038 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 return activityOptions == null ? null : activityOptions.toBundle();
3040 }
3041 return null;
3042 }
3043 } finally {
3044 Binder.restoreCallingIdentity(origId);
3045 }
3046 }
3047
3048 @Override
3049 public List<IBinder> getAppTasks(String callingPackage) {
3050 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003051 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 long ident = Binder.clearCallingIdentity();
3053 try {
3054 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003055 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 }
3057 } finally {
3058 Binder.restoreCallingIdentity(ident);
3059 }
3060 }
3061
3062 @Override
3063 public void finishVoiceTask(IVoiceInteractionSession session) {
3064 synchronized (mGlobalLock) {
3065 final long origId = Binder.clearCallingIdentity();
3066 try {
3067 // TODO: VI Consider treating local voice interactions and voice tasks
3068 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003069 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 } finally {
3071 Binder.restoreCallingIdentity(origId);
3072 }
3073 }
3074
3075 }
3076
3077 @Override
3078 public boolean isTopOfTask(IBinder token) {
3079 synchronized (mGlobalLock) {
3080 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003081 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003082 }
3083 }
3084
3085 @Override
3086 public void notifyLaunchTaskBehindComplete(IBinder token) {
3087 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3088 }
3089
3090 @Override
3091 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003092 mH.post(() -> {
3093 synchronized (mGlobalLock) {
3094 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003095 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003096 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003097 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003098 } catch (RemoteException e) {
3099 }
3100 }
3101 }
3102
3103 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003104 }
3105
3106 /** Called from an app when assist data is ready. */
3107 @Override
3108 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3109 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 synchronized (pae) {
3112 pae.result = extras;
3113 pae.structure = structure;
3114 pae.content = content;
3115 if (referrer != null) {
3116 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3117 }
3118 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003119 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003120 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003121 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 structure.setHomeActivity(pae.isHome);
3123 }
3124 pae.haveResult = true;
3125 pae.notifyAll();
3126 if (pae.intent == null && pae.receiver == null) {
3127 // Caller is just waiting for the result.
3128 return;
3129 }
3130 }
3131 // We are now ready to launch the assist activity.
3132 IAssistDataReceiver sendReceiver = null;
3133 Bundle sendBundle = null;
3134 synchronized (mGlobalLock) {
3135 buildAssistBundleLocked(pae, extras);
3136 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003137 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 if (!exists) {
3139 // Timed out.
3140 return;
3141 }
3142
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003143 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 // Caller wants result sent back to them.
3145 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003146 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003147 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003148 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3149 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3151 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3152 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3153 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3154 }
3155 }
3156 if (sendReceiver != null) {
3157 try {
3158 sendReceiver.onHandleAssistData(sendBundle);
3159 } catch (RemoteException e) {
3160 }
3161 return;
3162 }
3163
3164 final long ident = Binder.clearCallingIdentity();
3165 try {
3166 if (TextUtils.equals(pae.intent.getAction(),
3167 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003168 // Start voice interaction through VoiceInteractionManagerService.
3169 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3170 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 } else {
3172 pae.intent.replaceExtras(pae.extras);
3173 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3174 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3175 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003176 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177
3178 try {
3179 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3180 } catch (ActivityNotFoundException e) {
3181 Slog.w(TAG, "No activity to handle assist action.", e);
3182 }
3183 }
3184 } finally {
3185 Binder.restoreCallingIdentity(ident);
3186 }
3187 }
3188
3189 @Override
3190 public int addAppTask(IBinder activityToken, Intent intent,
3191 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3192 final int callingUid = Binder.getCallingUid();
3193 final long callingIdent = Binder.clearCallingIdentity();
3194
3195 try {
3196 synchronized (mGlobalLock) {
3197 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3198 if (r == null) {
3199 throw new IllegalArgumentException("Activity does not exist; token="
3200 + activityToken);
3201 }
3202 ComponentName comp = intent.getComponent();
3203 if (comp == null) {
3204 throw new IllegalArgumentException("Intent " + intent
3205 + " must specify explicit component");
3206 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003207 if (thumbnail.getWidth() != mThumbnailWidth
3208 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 throw new IllegalArgumentException("Bad thumbnail size: got "
3210 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 }
3213 if (intent.getSelector() != null) {
3214 intent.setSelector(null);
3215 }
3216 if (intent.getSourceBounds() != null) {
3217 intent.setSourceBounds(null);
3218 }
3219 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3220 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3221 // The caller has added this as an auto-remove task... that makes no
3222 // sense, so turn off auto-remove.
3223 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3224 }
3225 }
3226 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3227 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3228 if (ainfo.applicationInfo.uid != callingUid) {
3229 throw new SecurityException(
3230 "Can't add task for another application: target uid="
3231 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3232 }
3233
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003234 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003235 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003236 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003237 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003239 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 return INVALID_TASK_ID;
3241 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003242 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243
3244 // TODO: Send the thumbnail to WM to store it.
3245
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003246 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 }
3248 } finally {
3249 Binder.restoreCallingIdentity(callingIdent);
3250 }
3251 }
3252
3253 @Override
3254 public Point getAppTaskThumbnailSize() {
3255 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003256 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 }
3258 }
3259
3260 @Override
3261 public void setTaskResizeable(int taskId, int resizeableMode) {
3262 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003263 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3265 if (task == null) {
3266 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3267 return;
3268 }
3269 task.setResizeMode(resizeableMode);
3270 }
3271 }
3272
3273 @Override
3274 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003275 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 long ident = Binder.clearCallingIdentity();
3277 try {
3278 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003279 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003280 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 if (task == null) {
3282 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3283 return;
3284 }
3285 // Place the task in the right stack if it isn't there already based on
3286 // the requested bounds.
3287 // The stack transition logic is:
3288 // - a null bounds on a freeform task moves that task to fullscreen
3289 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3290 // that task to freeform
3291 // - otherwise the task is not moved
3292 ActivityStack stack = task.getStack();
3293 if (!task.getWindowConfiguration().canResizeTask()) {
3294 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3295 }
3296 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3297 stack = stack.getDisplay().getOrCreateStack(
3298 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3299 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3300 stack = stack.getDisplay().getOrCreateStack(
3301 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3302 }
3303
3304 // Reparent the task to the right stack if necessary
3305 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3306 if (stack != task.getStack()) {
3307 // Defer resume until the task is resized below
3308 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3309 DEFER_RESUME, "resizeTask");
3310 preserveWindow = false;
3311 }
3312
3313 // After reparenting (which only resizes the task to the stack bounds), resize the
3314 // task to the actual bounds provided
3315 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3316 }
3317 } finally {
3318 Binder.restoreCallingIdentity(ident);
3319 }
3320 }
3321
Evan Rosky226de132020-01-03 18:00:29 -08003322 private int sanitizeAndApplyChange(ConfigurationContainer container,
Evan Roskyddedfd42019-10-04 13:38:38 -07003323 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003324 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003325 throw new RuntimeException("Invalid token in task transaction");
3326 }
3327 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3328 // masks here.
3329 int configMask = change.getConfigSetMask();
3330 int windowMask = change.getWindowSetMask();
3331 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3332 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3333 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
Evan Rosky226de132020-01-03 18:00:29 -08003334 int effects = 0;
3335 if (configMask != 0) {
3336 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3337 c.setTo(change.getConfiguration(), configMask, windowMask);
3338 container.onRequestedOverrideConfigurationChanged(c);
3339 // TODO(b/145675353): remove the following once we could apply new bounds to the
3340 // pinned stack together with its children.
3341 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3342 effects |= TRANSACT_EFFECTS_CLIENT_CONFIG;
3343 }
3344 if ((change.getChangeMask() & WindowContainerTransaction.Change.CHANGE_FOCUSABLE) != 0) {
3345 if (container.setFocusable(change.getFocusable())) {
3346 effects |= TRANSACT_EFFECTS_LIFECYCLE;
3347 }
3348 }
3349 return effects;
Hongwei Wangebf18082019-09-26 14:25:11 -07003350 }
3351
3352 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3353 int windowMask, Configuration config) {
3354 if ((container instanceof ActivityStack)
3355 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3356 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3357 final ActivityStack stack = (ActivityStack) container;
3358 if (stack.inPinnedWindowingMode()) {
3359 stack.resize(config.windowConfiguration.getBounds(),
3360 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3361 PRESERVE_WINDOWS, true /* deferResume */);
3362 }
3363 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003364 }
3365
Evan Rosky226de132020-01-03 18:00:29 -08003366 private int applyWindowContainerChange(ConfigurationContainer cc,
Robert Carr8a2f9132019-11-11 15:03:15 -08003367 WindowContainerTransaction.Change c) {
Evan Rosky226de132020-01-03 18:00:29 -08003368 int effects = sanitizeAndApplyChange(cc, c);
Robert Carr8a2f9132019-11-11 15:03:15 -08003369
3370 Rect enterPipBounds = c.getEnterPipBounds();
3371 if (enterPipBounds != null) {
3372 Task tr = (Task) cc;
3373 mStackSupervisor.updatePictureInPictureMode(tr,
3374 enterPipBounds, true);
3375 }
Evan Rosky226de132020-01-03 18:00:29 -08003376 return effects;
Robert Carr8a2f9132019-11-11 15:03:15 -08003377 }
3378
Evan Roskyddedfd42019-10-04 13:38:38 -07003379 @Override
3380 public void applyContainerTransaction(WindowContainerTransaction t) {
3381 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
Evan Rosky226de132020-01-03 18:00:29 -08003382 if (t == null) {
3383 return;
3384 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003385 long ident = Binder.clearCallingIdentity();
3386 try {
Evan Roskyddedfd42019-10-04 13:38:38 -07003387 synchronized (mGlobalLock) {
Evan Rosky226de132020-01-03 18:00:29 -08003388 int effects = 0;
3389 deferWindowLayout();
3390 try {
3391 ArraySet<WindowContainer> haveConfigChanges = new ArraySet<>();
3392 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3393 t.getChanges().entrySet().iterator();
3394 while (entries.hasNext()) {
3395 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3396 entries.next();
3397 final ConfigurationContainer cc =
3398 ConfigurationContainer.RemoteToken.fromBinder(
3399 entry.getKey()).getContainer();
3400 int containerEffect = applyWindowContainerChange(cc, entry.getValue());
3401 effects |= containerEffect;
3402 // Lifecycle changes will trigger ensureConfig for everything.
3403 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) == 0
3404 && (containerEffect & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3405 if (cc instanceof WindowContainer) {
3406 haveConfigChanges.add((WindowContainer) cc);
3407 }
3408 }
3409 }
3410 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) != 0) {
3411 // Already calls ensureActivityConfig
3412 mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
3413 } else if ((effects & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3414 final PooledConsumer f = PooledLambda.obtainConsumer(
3415 ActivityRecord::ensureActivityConfiguration,
3416 PooledLambda.__(ActivityRecord.class), 0,
3417 false /* preserveWindow */);
3418 try {
3419 for (int i = haveConfigChanges.size() - 1; i >= 0; --i) {
3420 haveConfigChanges.valueAt(i).forAllActivities(f);
3421 }
3422 } finally {
3423 f.recycle();
3424 }
3425 }
3426 } finally {
3427 continueWindowLayout();
Evan Roskyddedfd42019-10-04 13:38:38 -07003428 }
3429 }
3430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 @Override
3436 public boolean releaseActivityInstance(IBinder token) {
3437 synchronized (mGlobalLock) {
3438 final long origId = Binder.clearCallingIdentity();
3439 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003440 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3441 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 return false;
3443 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003444 r.destroyImmediately(true /* removeFromApp */, "app-req");
3445 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 } finally {
3447 Binder.restoreCallingIdentity(origId);
3448 }
3449 }
3450 }
3451
3452 @Override
3453 public void releaseSomeActivities(IApplicationThread appInt) {
3454 synchronized (mGlobalLock) {
3455 final long origId = Binder.clearCallingIdentity();
3456 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003457 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003458 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 } finally {
3460 Binder.restoreCallingIdentity(origId);
3461 }
3462 }
3463 }
3464
3465 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003466 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003467 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 != PackageManager.PERMISSION_GRANTED) {
3469 throw new SecurityException("Requires permission "
3470 + android.Manifest.permission.DEVICE_POWER);
3471 }
3472
3473 synchronized (mGlobalLock) {
3474 long ident = Binder.clearCallingIdentity();
3475 if (mKeyguardShown != keyguardShowing) {
3476 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003477 final Message msg = PooledLambda.obtainMessage(
3478 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3479 keyguardShowing);
3480 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 }
3482 try {
wilsonshih177261f2019-02-22 12:02:18 +08003483 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 } finally {
3485 Binder.restoreCallingIdentity(ident);
3486 }
3487 }
3488
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 mH.post(() -> {
3490 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3491 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3492 }
3493 });
3494 }
3495
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003496 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003497 mH.post(() -> {
3498 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3499 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3500 }
3501 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 }
3503
3504 @Override
3505 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3507 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508
3509 final File passedIconFile = new File(filePath);
3510 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3511 passedIconFile.getName());
3512 if (!legitIconFile.getPath().equals(filePath)
3513 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3514 throw new IllegalArgumentException("Bad file path: " + filePath
3515 + " passed for userId " + userId);
3516 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003517 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003518 }
3519
3520 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003522 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 synchronized (mGlobalLock) {
3524 final long ident = Binder.clearCallingIdentity();
3525 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003526 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 if (stack == null) {
3528 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3529 return;
3530 }
3531 if (!stack.isActivityTypeStandardOrUndefined()) {
3532 throw new IllegalArgumentException(
3533 "Removing non-standard stack is not allowed.");
3534 }
3535 mStackSupervisor.removeStack(stack);
3536 } finally {
3537 Binder.restoreCallingIdentity(ident);
3538 }
3539 }
3540 }
3541
3542 @Override
3543 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003544 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545
3546 synchronized (mGlobalLock) {
3547 final long ident = Binder.clearCallingIdentity();
3548 try {
3549 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3550 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003551 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 } finally {
3553 Binder.restoreCallingIdentity(ident);
3554 }
3555 }
3556 }
3557
3558 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003559 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 synchronized (mGlobalLock) {
3561 long ident = Binder.clearCallingIdentity();
3562 try {
3563 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3564 if (r == null) {
3565 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003566 "toggleFreeformWindowingMode: No activity record matching token="
3567 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003568 }
3569
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003570 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003571 if (stack == null) {
3572 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3573 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 }
3575
Yunfan Chend967af82019-01-17 18:30:18 +09003576 if (!stack.inFreeformWindowingMode()
3577 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3578 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3579 + "toggle between fullscreen and freeform.");
3580 }
3581
3582 if (stack.inFreeformWindowingMode()) {
3583 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003584 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003585 throw new IllegalStateException("Size-compat windows are currently not"
3586 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003587 } else if (stack.getParent().inFreeformWindowingMode()) {
3588 // If the window is on a freeform display, set it to undefined. It will be
3589 // resolved to freeform and it can adjust windowing mode when the display mode
3590 // changes in runtime.
3591 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003592 } else {
3593 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3594 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 } finally {
3596 Binder.restoreCallingIdentity(ident);
3597 }
3598 }
3599 }
3600
3601 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3602 @Override
3603 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003604 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003606 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 }
3608
3609 /** Unregister a task stack listener so that it stops receiving callbacks. */
3610 @Override
3611 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003612 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003613 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003614 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003615 }
3616
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003617 @Override
3618 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3619 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3620 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3621 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3622 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3623 }
3624
3625 @Override
3626 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3627 IBinder activityToken, int flags) {
3628 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3629 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3630 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3631 }
3632
3633 @Override
3634 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3635 Bundle args) {
3636 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3637 true /* focused */, true /* newSessionId */, userHandle, args,
3638 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3639 }
3640
3641 @Override
3642 public Bundle getAssistContextExtras(int requestType) {
3643 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3644 null, null, true /* focused */, true /* newSessionId */,
3645 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3646 if (pae == null) {
3647 return null;
3648 }
3649 synchronized (pae) {
3650 while (!pae.haveResult) {
3651 try {
3652 pae.wait();
3653 } catch (InterruptedException e) {
3654 }
3655 }
3656 }
3657 synchronized (mGlobalLock) {
3658 buildAssistBundleLocked(pae, pae.result);
3659 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003660 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 }
3662 return pae.extras;
3663 }
3664
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003665 /**
3666 * Binder IPC calls go through the public entry point.
3667 * This can be called with or without the global lock held.
3668 */
3669 private static int checkCallingPermission(String permission) {
3670 return checkPermission(
3671 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3672 }
3673
3674 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003675 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003676 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3677 mAmInternal.enforceCallingPermission(permission, func);
3678 }
3679 }
3680
3681 @VisibleForTesting
3682 int checkGetTasksPermission(String permission, int pid, int uid) {
3683 return checkPermission(permission, pid, uid);
3684 }
3685
3686 static int checkPermission(String permission, int pid, int uid) {
3687 if (permission == null) {
3688 return PackageManager.PERMISSION_DENIED;
3689 }
3690 return checkComponentPermission(permission, pid, uid, -1, true);
3691 }
3692
Wale Ogunwale214f3482018-10-04 11:00:47 -07003693 public static int checkComponentPermission(String permission, int pid, int uid,
3694 int owningUid, boolean exported) {
3695 return ActivityManagerService.checkComponentPermission(
3696 permission, pid, uid, owningUid, exported);
3697 }
3698
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003699 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3700 if (getRecentTasks().isCallerRecents(callingUid)) {
3701 // Always allow the recents component to get tasks
3702 return true;
3703 }
3704
3705 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3706 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3707 if (!allowed) {
3708 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3709 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3710 // Temporary compatibility: some existing apps on the system image may
3711 // still be requesting the old permission and not switched to the new
3712 // one; if so, we'll still allow them full access. This means we need
3713 // to see if they are holding the old permission and are a system app.
3714 try {
3715 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3716 allowed = true;
3717 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3718 + " is using old GET_TASKS but privileged; allowing");
3719 }
3720 } catch (RemoteException e) {
3721 }
3722 }
3723 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3724 + " does not hold REAL_GET_TASKS; limiting output");
3725 }
3726 return allowed;
3727 }
3728
Nicholas Sauer0259e532019-08-30 08:24:55 -07003729 boolean isCrossUserAllowed(int pid, int uid) {
3730 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3731 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3732 }
3733
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003734 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3735 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3736 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3737 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 "enqueueAssistContext()");
3740
3741 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003742 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003743 if (activity == null) {
3744 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3745 return null;
3746 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003747 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3749 return null;
3750 }
3751 if (focused) {
3752 if (activityToken != null) {
3753 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3754 if (activity != caller) {
3755 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3756 + " is not current top " + activity);
3757 return null;
3758 }
3759 }
3760 } else {
3761 activity = ActivityRecord.forTokenLocked(activityToken);
3762 if (activity == null) {
3763 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3764 + " couldn't be found");
3765 return null;
3766 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003767 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3769 return null;
3770 }
3771 }
3772
3773 PendingAssistExtras pae;
3774 Bundle extras = new Bundle();
3775 if (args != null) {
3776 extras.putAll(args);
3777 }
3778 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003779 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003780
3781 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3782 userHandle);
3783 pae.isHome = activity.isActivityTypeHome();
3784
3785 // Increment the sessionId if necessary
3786 if (newSessionId) {
3787 mViSessionId++;
3788 }
3789 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003790 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3791 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003793 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 } catch (RemoteException e) {
3795 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3796 return null;
3797 }
3798 return pae;
3799 }
3800 }
3801
3802 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3803 if (result != null) {
3804 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3805 }
3806 if (pae.hint != null) {
3807 pae.extras.putBoolean(pae.hint, true);
3808 }
3809 }
3810
3811 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3812 IAssistDataReceiver receiver;
3813 synchronized (mGlobalLock) {
3814 mPendingAssistExtras.remove(pae);
3815 receiver = pae.receiver;
3816 }
3817 if (receiver != null) {
3818 // Caller wants result sent back to them.
3819 Bundle sendBundle = new Bundle();
3820 // At least return the receiver extras
3821 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3822 try {
3823 pae.receiver.onHandleAssistData(sendBundle);
3824 } catch (RemoteException e) {
3825 }
3826 }
3827 }
3828
3829 public class PendingAssistExtras extends Binder implements Runnable {
3830 public final ActivityRecord activity;
3831 public boolean isHome;
3832 public final Bundle extras;
3833 public final Intent intent;
3834 public final String hint;
3835 public final IAssistDataReceiver receiver;
3836 public final int userHandle;
3837 public boolean haveResult = false;
3838 public Bundle result = null;
3839 public AssistStructure structure = null;
3840 public AssistContent content = null;
3841 public Bundle receiverExtras;
3842
3843 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3844 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3845 int _userHandle) {
3846 activity = _activity;
3847 extras = _extras;
3848 intent = _intent;
3849 hint = _hint;
3850 receiver = _receiver;
3851 receiverExtras = _receiverExtras;
3852 userHandle = _userHandle;
3853 }
3854
3855 @Override
3856 public void run() {
3857 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3858 synchronized (this) {
3859 haveResult = true;
3860 notifyAll();
3861 }
3862 pendingAssistExtrasTimedOut(this);
3863 }
3864 }
3865
3866 @Override
3867 public boolean isAssistDataAllowedOnCurrentActivity() {
3868 int userId;
3869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003870 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3872 return false;
3873 }
3874
Wale Ogunwale21e06482019-11-18 05:14:15 -08003875 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 if (activity == null) {
3877 return false;
3878 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003879 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 }
3881 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3882 }
3883
3884 @Override
3885 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3886 long ident = Binder.clearCallingIdentity();
3887 try {
3888 synchronized (mGlobalLock) {
3889 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003890 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 if (top != caller) {
3892 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3893 + " is not current top " + top);
3894 return false;
3895 }
3896 if (!top.nowVisible) {
3897 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3898 + " is not visible");
3899 return false;
3900 }
3901 }
3902 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3903 token);
3904 } finally {
3905 Binder.restoreCallingIdentity(ident);
3906 }
3907 }
3908
3909 @Override
3910 public boolean isRootVoiceInteraction(IBinder token) {
3911 synchronized (mGlobalLock) {
3912 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3913 if (r == null) {
3914 return false;
3915 }
3916 return r.rootVoiceInteraction;
3917 }
3918 }
3919
Wale Ogunwalef6733932018-06-27 05:14:34 -07003920 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3921 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3922 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3923 if (activityToCallback == null) return;
3924 activityToCallback.setVoiceSessionLocked(voiceSession);
3925
3926 // Inform the activity
3927 try {
3928 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3929 voiceInteractor);
3930 long token = Binder.clearCallingIdentity();
3931 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003932 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003933 } finally {
3934 Binder.restoreCallingIdentity(token);
3935 }
3936 // TODO: VI Should we cache the activity so that it's easier to find later
3937 // rather than scan through all the stacks and activities?
3938 } catch (RemoteException re) {
3939 activityToCallback.clearVoiceSessionLocked();
3940 // TODO: VI Should this terminate the voice session?
3941 }
3942 }
3943
3944 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3945 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3946 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3947 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3948 boolean wasRunningVoice = mRunningVoice != null;
3949 mRunningVoice = session;
3950 if (!wasRunningVoice) {
3951 mVoiceWakeLock.acquire();
3952 updateSleepIfNeededLocked();
3953 }
3954 }
3955 }
3956
3957 void finishRunningVoiceLocked() {
3958 if (mRunningVoice != null) {
3959 mRunningVoice = null;
3960 mVoiceWakeLock.release();
3961 updateSleepIfNeededLocked();
3962 }
3963 }
3964
3965 @Override
3966 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3967 synchronized (mGlobalLock) {
3968 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3969 if (keepAwake) {
3970 mVoiceWakeLock.acquire();
3971 } else {
3972 mVoiceWakeLock.release();
3973 }
3974 }
3975 }
3976 }
3977
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 @Override
3979 public ComponentName getActivityClassForToken(IBinder token) {
3980 synchronized (mGlobalLock) {
3981 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3982 if (r == null) {
3983 return null;
3984 }
3985 return r.intent.getComponent();
3986 }
3987 }
3988
3989 @Override
3990 public String getPackageForToken(IBinder token) {
3991 synchronized (mGlobalLock) {
3992 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3993 if (r == null) {
3994 return null;
3995 }
3996 return r.packageName;
3997 }
3998 }
3999
4000 @Override
4001 public void showLockTaskEscapeMessage(IBinder token) {
4002 synchronized (mGlobalLock) {
4003 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4004 if (r == null) {
4005 return;
4006 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004007 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 }
4009 }
4010
4011 @Override
4012 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004013 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 final long token = Binder.clearCallingIdentity();
4015 try {
4016 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004017 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 }
4019 } finally {
4020 Binder.restoreCallingIdentity(token);
4021 }
4022 }
4023
4024 /**
4025 * Try to place task to provided position. The final position might be different depending on
4026 * current user and stacks state. The task will be moved to target stack if it's currently in
4027 * different stack.
4028 */
4029 @Override
4030 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 synchronized (mGlobalLock) {
4033 long ident = Binder.clearCallingIdentity();
4034 try {
4035 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
4036 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08004037 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 if (task == null) {
4039 throw new IllegalArgumentException("positionTaskInStack: no task for id="
4040 + taskId);
4041 }
4042
Louis Chang149d5c82019-12-30 09:47:39 +08004043 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044
4045 if (stack == null) {
4046 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
4047 + stackId);
4048 }
4049 if (!stack.isActivityTypeStandardOrUndefined()) {
4050 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
4051 + " the position of task " + taskId + " in/to non-standard stack");
4052 }
4053
4054 // TODO: Have the callers of this API call a separate reparent method if that is
4055 // what they intended to do vs. having this method also do reparenting.
4056 if (task.getStack() == stack) {
4057 // Change position in current stack.
4058 stack.positionChildAt(task, position);
4059 } else {
4060 // Reparent to new stack.
4061 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4062 !DEFER_RESUME, "positionTaskInStack");
4063 }
4064 } finally {
4065 Binder.restoreCallingIdentity(ident);
4066 }
4067 }
4068 }
4069
4070 @Override
4071 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4072 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4073 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004074 + Arrays.toString(horizontalSizeConfiguration) + " "
4075 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 synchronized (mGlobalLock) {
4077 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4078 if (record == null) {
4079 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4080 + "found for: " + token);
4081 }
4082 record.setSizeConfigurations(horizontalSizeConfiguration,
4083 verticalSizeConfigurations, smallestSizeConfigurations);
4084 }
4085 }
4086
4087 /**
4088 * Dismisses split-screen multi-window mode.
4089 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4090 */
4091 @Override
4092 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004093 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4095 final long ident = Binder.clearCallingIdentity();
4096 try {
4097 synchronized (mGlobalLock) {
4098 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004099 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100 if (stack == null) {
4101 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4102 return;
4103 }
4104
4105 if (toTop) {
4106 // Caller wants the current split-screen primary stack to be the top stack after
4107 // it goes fullscreen, so move it to the front.
4108 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004109 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004110 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004111 // stack after it goes fullscreen, so we move the focus to the top-most
4112 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4114 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4115 if (otherStack != null) {
4116 otherStack.moveToFront("dismissSplitScreenMode_other");
4117 }
4118 }
4119
Evan Rosky10475742018-09-05 19:02:48 -07004120 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122 } finally {
4123 Binder.restoreCallingIdentity(ident);
4124 }
4125 }
4126
4127 /**
4128 * Dismisses Pip
4129 * @param animate True if the dismissal should be animated.
4130 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4131 * default animation duration should be used.
4132 */
4133 @Override
4134 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004136 final long ident = Binder.clearCallingIdentity();
4137 try {
4138 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004139 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004140 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 if (stack == null) {
4142 Slog.w(TAG, "dismissPip: pinned stack not found.");
4143 return;
4144 }
4145 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4146 throw new IllegalArgumentException("Stack: " + stack
4147 + " doesn't support animated resize.");
4148 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004149 /**
4150 * TODO(b/146594635): Remove all PIP animation code from WM
4151 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4152 */
4153 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004154 stack.animateResizePinnedStack(null /* destBounds */,
4155 null /* sourceHintBounds */, animationDuration,
4156 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004158 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 }
4160 }
4161 } finally {
4162 Binder.restoreCallingIdentity(ident);
4163 }
4164 }
4165
4166 @Override
4167 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004168 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 synchronized (mGlobalLock) {
4170 mSuppressResizeConfigChanges = suppress;
4171 }
4172 }
4173
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 @Override
4175 // TODO: API should just be about changing windowing modes...
4176 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004177 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 "moveTasksToFullscreenStack()");
4179 synchronized (mGlobalLock) {
4180 final long origId = Binder.clearCallingIdentity();
4181 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004182 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004183 if (stack != null){
4184 if (!stack.isActivityTypeStandardOrUndefined()) {
4185 throw new IllegalArgumentException(
4186 "You can't move tasks from non-standard stacks.");
4187 }
4188 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4189 }
4190 } finally {
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194 }
4195
4196 /**
4197 * Moves the top activity in the input stackId to the pinned stack.
4198 *
4199 * @param stackId Id of stack to move the top activity to pinned stack.
4200 * @param bounds Bounds to use for pinned stack.
4201 *
4202 * @return True if the top activity of the input stack was successfully moved to the pinned
4203 * stack.
4204 */
4205 @Override
4206 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004207 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004208 "moveTopActivityToPinnedStack()");
4209 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4212 + "Device doesn't support picture-in-picture mode");
4213 }
4214
4215 long ident = Binder.clearCallingIdentity();
4216 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004217 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 } finally {
4219 Binder.restoreCallingIdentity(ident);
4220 }
4221 }
4222 }
4223
4224 @Override
4225 public boolean isInMultiWindowMode(IBinder token) {
4226 final long origId = Binder.clearCallingIdentity();
4227 try {
4228 synchronized (mGlobalLock) {
4229 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4230 if (r == null) {
4231 return false;
4232 }
4233 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4234 return r.inMultiWindowMode();
4235 }
4236 } finally {
4237 Binder.restoreCallingIdentity(origId);
4238 }
4239 }
4240
4241 @Override
4242 public boolean isInPictureInPictureMode(IBinder token) {
4243 final long origId = Binder.clearCallingIdentity();
4244 try {
4245 synchronized (mGlobalLock) {
4246 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4247 }
4248 } finally {
4249 Binder.restoreCallingIdentity(origId);
4250 }
4251 }
4252
4253 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004254 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4255 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 return false;
4257 }
4258
4259 // If we are animating to fullscreen then we have already dispatched the PIP mode
4260 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004261 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004262 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 }
4264
4265 @Override
4266 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4267 final long origId = Binder.clearCallingIdentity();
4268 try {
4269 synchronized (mGlobalLock) {
4270 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4271 "enterPictureInPictureMode", token, params);
4272
4273 // If the activity is already in picture in picture mode, then just return early
4274 if (isInPictureInPictureMode(r)) {
4275 return true;
4276 }
4277
4278 // Activity supports picture-in-picture, now check that we can enter PiP at this
4279 // point, if it is
4280 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4281 false /* beforeStopping */)) {
4282 return false;
4283 }
4284
4285 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004286 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004287 if (r.getParent() == null) {
4288 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4289 return;
4290 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004291 // Only update the saved args from the args that are set
4292 r.pictureInPictureArgs.copyOnlySet(params);
4293 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4294 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4295 // Adjust the source bounds by the insets for the transition down
4296 final Rect sourceBounds = new Rect(
4297 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004298 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004299 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004300 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004301 stack.setPictureInPictureAspectRatio(aspectRatio);
4302 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004303 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4304 r.info.applicationInfo.uid, r.shortComponentName,
4305 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004306 logPictureInPictureArgs(params);
4307 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 };
4309
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004310 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 // If the keyguard is showing or occluded, then try and dismiss it before
4312 // entering picture-in-picture (this will prompt the user to authenticate if the
4313 // device is currently locked).
4314 dismissKeyguard(token, new KeyguardDismissCallback() {
4315 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 public void onDismissSucceeded() {
4317 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
4319 }, null /* message */);
4320 } else {
4321 // Enter picture in picture immediately otherwise
4322 enterPipRunnable.run();
4323 }
4324 return true;
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(origId);
4328 }
4329 }
4330
4331 @Override
4332 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4333 final long origId = Binder.clearCallingIdentity();
4334 try {
4335 synchronized (mGlobalLock) {
4336 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4337 "setPictureInPictureParams", token, params);
4338
4339 // Only update the saved args from the args that are set
4340 r.pictureInPictureArgs.copyOnlySet(params);
4341 if (r.inPinnedWindowingMode()) {
4342 // If the activity is already in picture-in-picture, update the pinned stack now
4343 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4344 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004345 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 if (!stack.isAnimatingBoundsToFullscreen()) {
4347 stack.setPictureInPictureAspectRatio(
4348 r.pictureInPictureArgs.getAspectRatio());
4349 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4350 }
4351 }
4352 logPictureInPictureArgs(params);
4353 }
4354 } finally {
4355 Binder.restoreCallingIdentity(origId);
4356 }
4357 }
4358
4359 @Override
4360 public int getMaxNumPictureInPictureActions(IBinder token) {
4361 // Currently, this is a static constant, but later, we may change this to be dependent on
4362 // the context of the activity
4363 return 3;
4364 }
4365
4366 private void logPictureInPictureArgs(PictureInPictureParams params) {
4367 if (params.hasSetActions()) {
4368 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4369 params.getActions().size());
4370 }
4371 if (params.hasSetAspectRatio()) {
4372 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4373 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4374 MetricsLogger.action(lm);
4375 }
4376 }
4377
4378 /**
4379 * Checks the state of the system and the activity associated with the given {@param token} to
4380 * verify that picture-in-picture is supported for that activity.
4381 *
4382 * @return the activity record for the given {@param token} if all the checks pass.
4383 */
4384 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4385 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 throw new IllegalStateException(caller
4388 + ": Device doesn't support picture-in-picture mode.");
4389 }
4390
4391 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4392 if (r == null) {
4393 throw new IllegalStateException(caller
4394 + ": Can't find activity for token=" + token);
4395 }
4396
4397 if (!r.supportsPictureInPicture()) {
4398 throw new IllegalStateException(caller
4399 + ": Current activity does not support picture-in-picture.");
4400 }
4401
4402 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004403 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004404 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004405 final float minAspectRatio = mContext.getResources().getFloat(
4406 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4407 final float maxAspectRatio = mContext.getResources().getFloat(
4408 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4409 throw new IllegalArgumentException(String.format(caller
4410 + ": Aspect ratio is too extreme (must be between %f and %f).",
4411 minAspectRatio, maxAspectRatio));
4412 }
4413
4414 // Truncate the number of actions if necessary
4415 params.truncateActions(getMaxNumPictureInPictureActions(token));
4416
4417 return r;
4418 }
4419
4420 @Override
4421 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 synchronized (mGlobalLock) {
4424 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4425 if (r == null) {
4426 throw new IllegalArgumentException("Activity does not exist; token="
4427 + activityToken);
4428 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004429 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431 }
4432
4433 @Override
4434 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4435 Rect tempDockedTaskInsetBounds,
4436 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 long ident = Binder.clearCallingIdentity();
4439 try {
4440 synchronized (mGlobalLock) {
4441 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4442 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4443 PRESERVE_WINDOWS);
4444 }
4445 } finally {
4446 Binder.restoreCallingIdentity(ident);
4447 }
4448 }
4449
4450 @Override
4451 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 final long ident = Binder.clearCallingIdentity();
4454 try {
4455 synchronized (mGlobalLock) {
4456 mStackSupervisor.setSplitScreenResizing(resizing);
4457 }
4458 } finally {
4459 Binder.restoreCallingIdentity(ident);
4460 }
4461 }
4462
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004463 /**
4464 * Check that we have the features required for VR-related API calls, and throw an exception if
4465 * not.
4466 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004467 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 if (!mContext.getPackageManager().hasSystemFeature(
4469 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4470 throw new UnsupportedOperationException("VR mode not supported on this device!");
4471 }
4472 }
4473
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 @Override
4475 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004476 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477
4478 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4479
4480 ActivityRecord r;
4481 synchronized (mGlobalLock) {
4482 r = ActivityRecord.isInStackLocked(token);
4483 }
4484
4485 if (r == null) {
4486 throw new IllegalArgumentException();
4487 }
4488
4489 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004490 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 VrManagerInternal.NO_ERROR) {
4492 return err;
4493 }
4494
4495 // Clear the binder calling uid since this path may call moveToTask().
4496 final long callingId = Binder.clearCallingIdentity();
4497 try {
4498 synchronized (mGlobalLock) {
4499 r.requestedVrComponent = (enabled) ? packageName : null;
4500
4501 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004502 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004503 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 }
4505 return 0;
4506 }
4507 } finally {
4508 Binder.restoreCallingIdentity(callingId);
4509 }
4510 }
4511
4512 @Override
4513 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4514 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4515 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004516 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4518 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4519 }
Louis Changcdec0802019-11-11 11:45:07 +08004520 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 || activity.voiceSession != null) {
4522 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4523 return;
4524 }
4525 if (activity.pendingVoiceInteractionStart) {
4526 Slog.w(TAG, "Pending start of voice interaction already.");
4527 return;
4528 }
4529 activity.pendingVoiceInteractionStart = true;
4530 }
4531 LocalServices.getService(VoiceInteractionManagerInternal.class)
4532 .startLocalVoiceInteraction(callingActivity, options);
4533 }
4534
4535 @Override
4536 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4537 LocalServices.getService(VoiceInteractionManagerInternal.class)
4538 .stopLocalVoiceInteraction(callingActivity);
4539 }
4540
4541 @Override
4542 public boolean supportsLocalVoiceInteraction() {
4543 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4544 .supportsLocalVoiceInteraction();
4545 }
4546
4547 /** Notifies all listeners when the pinned stack animation starts. */
4548 @Override
4549 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004550 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 }
4552
4553 /** Notifies all listeners when the pinned stack animation ends. */
4554 @Override
4555 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004556 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 }
4558
4559 @Override
4560 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004561 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004562 final long ident = Binder.clearCallingIdentity();
4563 try {
4564 synchronized (mGlobalLock) {
4565 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4566 }
4567 } finally {
4568 Binder.restoreCallingIdentity(ident);
4569 }
4570 }
4571
4572 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004574 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575
4576 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004577 if (mWindowManager == null) {
4578 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4579 return false;
4580 }
4581
4582 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004584 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 }
4586
Riddle Hsua0022cd2019-09-09 21:12:41 +08004587 mH.sendMessage(PooledLambda.obtainMessage(
4588 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4589 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590
4591 final long origId = Binder.clearCallingIdentity();
4592 try {
4593 if (values != null) {
4594 Settings.System.clearConfiguration(values);
4595 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004596 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 UserHandle.USER_NULL, false /* deferResume */,
4598 mTmpUpdateConfigurationResult);
4599 return mTmpUpdateConfigurationResult.changes != 0;
4600 } finally {
4601 Binder.restoreCallingIdentity(origId);
4602 }
4603 }
4604 }
4605
4606 @Override
4607 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4608 CharSequence message) {
4609 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004610 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004611 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4612 }
4613 final long callingId = Binder.clearCallingIdentity();
4614 try {
4615 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004616 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 }
4618 } finally {
4619 Binder.restoreCallingIdentity(callingId);
4620 }
4621 }
4622
4623 @Override
4624 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004625 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 "cancelTaskWindowTransition()");
4627 final long ident = Binder.clearCallingIdentity();
4628 try {
4629 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004630 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 MATCH_TASK_IN_STACKS_ONLY);
4632 if (task == null) {
4633 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4634 return;
4635 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004636 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 }
4638 } finally {
4639 Binder.restoreCallingIdentity(ident);
4640 }
4641 }
4642
4643 @Override
4644 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004645 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004646 final long ident = Binder.clearCallingIdentity();
4647 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004648 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004649 } finally {
4650 Binder.restoreCallingIdentity(ident);
4651 }
4652 }
4653
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004654 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4655 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004656 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004657 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004658 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004659 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4660 if (task == null) {
4661 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4662 return null;
4663 }
4664 }
4665 // Don't call this while holding the lock as this operation might hit the disk.
4666 return task.getSnapshot(reducedResolution, restoreFromDisk);
4667 }
4668
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 @Override
4670 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4671 synchronized (mGlobalLock) {
4672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4673 if (r == null) {
4674 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4675 + token);
4676 return;
4677 }
4678 final long origId = Binder.clearCallingIdentity();
4679 try {
4680 r.setDisablePreviewScreenshots(disable);
4681 } finally {
4682 Binder.restoreCallingIdentity(origId);
4683 }
4684 }
4685 }
4686
Riddle Hsu440f88b2019-11-06 22:17:35 +08004687 @Override
4688 public void invalidateHomeTaskSnapshot(IBinder token) {
4689 synchronized (mGlobalLock) {
4690 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4691 if (r == null || !r.isActivityTypeHome()) {
4692 return;
4693 }
4694 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4695 }
4696 }
4697
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004698 /** Return the user id of the last resumed activity. */
4699 @Override
4700 public @UserIdInt
4701 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004702 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004703 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4704 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004705 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004706 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004707 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004708 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004709 }
4710 }
4711
4712 @Override
4713 public void updateLockTaskFeatures(int userId, int flags) {
4714 final int callingUid = Binder.getCallingUid();
4715 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004716 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004717 "updateLockTaskFeatures()");
4718 }
4719 synchronized (mGlobalLock) {
4720 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4721 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004722 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004723 }
4724 }
4725
4726 @Override
4727 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4728 synchronized (mGlobalLock) {
4729 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4730 if (r == null) {
4731 return;
4732 }
4733 final long origId = Binder.clearCallingIdentity();
4734 try {
4735 r.setShowWhenLocked(showWhenLocked);
4736 } finally {
4737 Binder.restoreCallingIdentity(origId);
4738 }
4739 }
4740 }
4741
4742 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004743 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4744 synchronized (mGlobalLock) {
4745 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4746 if (r == null) {
4747 return;
4748 }
4749 final long origId = Binder.clearCallingIdentity();
4750 try {
4751 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4752 } finally {
4753 Binder.restoreCallingIdentity(origId);
4754 }
4755 }
4756 }
4757
4758 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004759 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4760 synchronized (mGlobalLock) {
4761 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4762 if (r == null) {
4763 return;
4764 }
4765 final long origId = Binder.clearCallingIdentity();
4766 try {
4767 r.setTurnScreenOn(turnScreenOn);
4768 } finally {
4769 Binder.restoreCallingIdentity(origId);
4770 }
4771 }
4772 }
4773
4774 @Override
4775 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004776 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004777 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004778 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004779 synchronized (mGlobalLock) {
4780 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4781 if (r == null) {
4782 return;
4783 }
4784 final long origId = Binder.clearCallingIdentity();
4785 try {
4786 r.registerRemoteAnimations(definition);
4787 } finally {
4788 Binder.restoreCallingIdentity(origId);
4789 }
4790 }
4791 }
4792
4793 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004794 public void unregisterRemoteAnimations(IBinder token) {
4795 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4796 "unregisterRemoteAnimations");
4797 synchronized (mGlobalLock) {
4798 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4799 if (r == null) {
4800 return;
4801 }
4802 final long origId = Binder.clearCallingIdentity();
4803 try {
4804 r.unregisterRemoteAnimations();
4805 } finally {
4806 Binder.restoreCallingIdentity(origId);
4807 }
4808 }
4809 }
4810
4811 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004812 public void registerRemoteAnimationForNextActivityStart(String packageName,
4813 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004814 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004815 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004816 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004817 synchronized (mGlobalLock) {
4818 final long origId = Binder.clearCallingIdentity();
4819 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004820 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004821 packageName, adapter);
4822 } finally {
4823 Binder.restoreCallingIdentity(origId);
4824 }
4825 }
4826 }
4827
Evan Rosky966759f2019-01-15 10:33:58 -08004828 @Override
4829 public void registerRemoteAnimationsForDisplay(int displayId,
4830 RemoteAnimationDefinition definition) {
4831 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4832 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004833 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004834 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004835 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004836 if (display == null) {
4837 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4838 return;
4839 }
4840 final long origId = Binder.clearCallingIdentity();
4841 try {
4842 display.mDisplayContent.registerRemoteAnimations(definition);
4843 } finally {
4844 Binder.restoreCallingIdentity(origId);
4845 }
4846 }
4847 }
4848
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004849 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4850 @Override
4851 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4852 synchronized (mGlobalLock) {
4853 final long origId = Binder.clearCallingIdentity();
4854 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004855 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004856 } finally {
4857 Binder.restoreCallingIdentity(origId);
4858 }
4859 }
4860 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004861
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004862 @Override
4863 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004864 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004865 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004866 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004867 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004868 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 }
4870 }
4871
4872 @Override
4873 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004875 != PERMISSION_GRANTED) {
4876 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4877 + Binder.getCallingPid()
4878 + ", uid=" + Binder.getCallingUid()
4879 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4880 Slog.w(TAG, msg);
4881 throw new SecurityException(msg);
4882 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004883 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004884 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004885 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004886 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004887 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004888 }
4889 }
4890
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004891 @Override
4892 public void stopAppSwitches() {
4893 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4894 synchronized (mGlobalLock) {
4895 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004896 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 mDidAppSwitch = false;
4898 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4899 }
4900 }
4901
4902 @Override
4903 public void resumeAppSwitches() {
4904 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4905 synchronized (mGlobalLock) {
4906 // Note that we don't execute any pending app switches... we will
4907 // let those wait until either the timeout, or the next start
4908 // activity request.
4909 mAppSwitchesAllowedTime = 0;
4910 }
4911 }
4912
Ricky Wai906af482019-06-03 17:25:28 +01004913 long getLastStopAppSwitchesTime() {
4914 return mLastStopAppSwitchesTime;
4915 }
4916
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004917 void onStartActivitySetDidAppSwitch() {
4918 if (mDidAppSwitch) {
4919 // This is the second allowed switch since we stopped switches, so now just generally
4920 // allow switches. Use case:
4921 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4922 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4923 // anyone to switch again).
4924 mAppSwitchesAllowedTime = 0;
4925 } else {
4926 mDidAppSwitch = true;
4927 }
4928 }
4929
4930 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004931 boolean shouldDisableNonVrUiLocked() {
4932 return mVrController.shouldDisableNonVrUiLocked();
4933 }
4934
Wale Ogunwale53783742018-09-16 10:21:51 -07004935 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004936 // 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 +00004937 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004938 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004939 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4940 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004941 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004942 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004943 }
4944 mH.post(() -> {
4945 if (!mVrController.onVrModeChanged(r)) {
4946 return;
4947 }
4948 synchronized (mGlobalLock) {
4949 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4950 mWindowManager.disableNonVrUi(disableNonVrUi);
4951 if (disableNonVrUi) {
4952 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4953 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004954 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004955 }
4956 }
4957 });
4958 }
4959
Wale Ogunwale53783742018-09-16 10:21:51 -07004960 @Override
4961 public int getPackageScreenCompatMode(String packageName) {
4962 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4963 synchronized (mGlobalLock) {
4964 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4965 }
4966 }
4967
4968 @Override
4969 public void setPackageScreenCompatMode(String packageName, int mode) {
4970 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4971 "setPackageScreenCompatMode");
4972 synchronized (mGlobalLock) {
4973 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4974 }
4975 }
4976
4977 @Override
4978 public boolean getPackageAskScreenCompat(String packageName) {
4979 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4980 synchronized (mGlobalLock) {
4981 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4982 }
4983 }
4984
4985 @Override
4986 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4987 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4988 "setPackageAskScreenCompat");
4989 synchronized (mGlobalLock) {
4990 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4991 }
4992 }
4993
Wale Ogunwale64258362018-10-16 15:13:37 -07004994 public static String relaunchReasonToString(int relaunchReason) {
4995 switch (relaunchReason) {
4996 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4997 return "window_resize";
4998 case RELAUNCH_REASON_FREE_RESIZE:
4999 return "free_resize";
5000 default:
5001 return null;
5002 }
5003 }
5004
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005005 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08005006 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005007 }
5008
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005009 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08005010 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005011 mRecentTasks.notifyTaskPersisterLocked(task, flush);
5012 }
5013
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005014 boolean isKeyguardLocked() {
5015 return mKeyguardController.isKeyguardLocked();
5016 }
5017
Garfield Tan01548632018-11-27 10:15:48 -08005018 /**
5019 * Clears launch params for the given package.
5020 * @param packageNames the names of the packages of which the launch params are to be cleared
5021 */
5022 @Override
5023 public void clearLaunchParamsForPackages(List<String> packageNames) {
5024 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5025 "clearLaunchParamsForPackages");
5026 synchronized (mGlobalLock) {
5027 for (int i = 0; i < packageNames.size(); ++i) {
5028 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
5029 }
5030 }
5031 }
5032
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005033 /**
5034 * Makes the display with the given id a single task instance display. I.e the display can only
5035 * contain one task.
5036 */
5037 @Override
5038 public void setDisplayToSingleTaskInstance(int displayId) {
5039 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5040 "setDisplayToSingleTaskInstance");
5041 final long origId = Binder.clearCallingIdentity();
5042 try {
Louis Chang677921f2019-12-06 16:44:24 +08005043 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08005044 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005045 if (display != null) {
5046 display.setDisplayToSingleTaskInstance();
5047 }
5048 } finally {
5049 Binder.restoreCallingIdentity(origId);
5050 }
5051 }
5052
jorgegil@google.com06bc3232019-10-31 14:51:22 -07005053 /**
5054 * Requests that an activity should enter picture-in-picture mode if possible.
5055 */
5056 @Override
5057 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
5058 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5059 "requestPictureInPictureMode");
5060 final long origId = Binder.clearCallingIdentity();
5061 try {
5062 synchronized (mGlobalLock) {
5063 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5064 if (activity == null) {
5065 return;
5066 }
5067
5068 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5069 "requestPictureInPictureMode", /* beforeStopping */ false);
5070 if (!canEnterPictureInPicture) {
5071 throw new IllegalStateException(
5072 "Requested PIP on an activity that doesn't support it");
5073 }
5074
5075 try {
5076 final ClientTransaction transaction = ClientTransaction.obtain(
5077 activity.app.getThread(),
5078 activity.token);
5079 transaction.addCallback(EnterPipRequestedItem.obtain());
5080 getLifecycleManager().scheduleTransaction(transaction);
5081 } catch (Exception e) {
5082 Slog.w(TAG, "Failed to send enter pip requested item: "
5083 + activity.intent.getComponent(), e);
5084 }
5085 }
5086 } finally {
5087 Binder.restoreCallingIdentity(origId);
5088 }
5089 }
5090
Wale Ogunwale31913b52018-10-13 08:29:31 -07005091 void dumpLastANRLocked(PrintWriter pw) {
5092 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5093 if (mLastANRState == null) {
5094 pw.println(" <no ANR has occurred since boot>");
5095 } else {
5096 pw.println(mLastANRState);
5097 }
5098 }
5099
5100 void dumpLastANRTracesLocked(PrintWriter pw) {
5101 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5102
5103 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5104 if (ArrayUtils.isEmpty(files)) {
5105 pw.println(" <no ANR has occurred since boot>");
5106 return;
5107 }
5108 // Find the latest file.
5109 File latest = null;
5110 for (File f : files) {
5111 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5112 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005113 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005114 }
5115 pw.print("File: ");
5116 pw.print(latest.getName());
5117 pw.println();
5118 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5119 String line;
5120 while ((line = in.readLine()) != null) {
5121 pw.println(line);
5122 }
5123 } catch (IOException e) {
5124 pw.print("Unable to read: ");
5125 pw.print(e);
5126 pw.println();
5127 }
5128 }
5129
5130 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5131 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5132 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5133 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5134 }
5135
5136 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5137 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5138 pw.println(header);
5139
Louis Chang149d5c82019-12-30 09:47:39 +08005140 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005141 dumpPackage);
5142 boolean needSep = printedAnything;
5143
5144 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005145 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005146 " ResumedActivity: ");
5147 if (printed) {
5148 printedAnything = true;
5149 needSep = false;
5150 }
5151
5152 if (dumpPackage == null) {
5153 if (needSep) {
5154 pw.println();
5155 }
5156 printedAnything = true;
5157 mStackSupervisor.dump(pw, " ");
5158 }
5159
5160 if (!printedAnything) {
5161 pw.println(" (nothing)");
5162 }
5163 }
5164
5165 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005166 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005167 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005168 pw.println(" ");
5169 }
5170
5171 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5172 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5173 getActivityStartController().dump(pw, "", dumpPackage);
5174 }
5175
5176 /**
5177 * There are three things that cmd can be:
5178 * - a flattened component name that matches an existing activity
5179 * - the cmd arg isn't the flattened component name of an existing activity:
5180 * dump all activity whose component contains the cmd as a substring
5181 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005182 * <p>
5183 * The caller should not hold lock when calling this method because it will wait for the
5184 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005185 *
5186 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5187 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5188 */
5189 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5190 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5191 ArrayList<ActivityRecord> activities;
5192
5193 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005194 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005195 dumpFocusedStackOnly);
5196 }
5197
5198 if (activities.size() <= 0) {
5199 return false;
5200 }
5201
5202 String[] newArgs = new String[args.length - opti];
5203 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5204
Louis Changcdec0802019-11-11 11:45:07 +08005205 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005206 boolean needSep = false;
5207 for (int i = activities.size() - 1; i >= 0; i--) {
5208 ActivityRecord r = activities.get(i);
5209 if (needSep) {
5210 pw.println();
5211 }
5212 needSep = true;
5213 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005214 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005215 if (lastTask != task) {
5216 lastTask = task;
5217 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005218 pw.print(" id="); pw.print(lastTask.mTaskId);
5219 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005220 if (dumpAll) {
5221 lastTask.dump(pw, " ");
5222 }
5223 }
5224 }
5225 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5226 }
5227 return true;
5228 }
5229
5230 /**
5231 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5232 * there is a thread associated with the activity.
5233 */
5234 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5235 final ActivityRecord r, String[] args, boolean dumpAll) {
5236 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005237 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005238 synchronized (mGlobalLock) {
5239 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5240 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5241 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005242 if (r.hasProcess()) {
5243 pw.println(r.app.getPid());
5244 appThread = r.app.getThread();
5245 } else {
5246 pw.println("(not running)");
5247 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005248 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005249 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005250 }
5251 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005252 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005253 // flush anything that is already in the PrintWriter since the thread is going
5254 // to write to the file descriptor directly
5255 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005256 try (TransferPipe tp = new TransferPipe()) {
5257 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5258 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005259 } catch (IOException e) {
5260 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5261 } catch (RemoteException e) {
5262 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5263 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005264 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005265 }
5266
sanryhuang498e77e2018-12-06 14:57:01 +08005267 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5268 boolean testPssMode) {
5269 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5270 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5271 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005272 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5274 st.toString());
5275 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5277 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5278 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005279 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5280 testPssMode);
5281 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005282 }
5283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284 int getCurrentUserId() {
5285 return mAmInternal.getCurrentUserId();
5286 }
5287
5288 private void enforceNotIsolatedCaller(String caller) {
5289 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5290 throw new SecurityException("Isolated process not allowed to call " + caller);
5291 }
5292 }
5293
Wale Ogunwalef6733932018-06-27 05:14:34 -07005294 public Configuration getConfiguration() {
5295 Configuration ci;
5296 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005297 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005298 ci.userSetLocale = false;
5299 }
5300 return ci;
5301 }
5302
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005303 /**
5304 * Current global configuration information. Contains general settings for the entire system,
5305 * also corresponds to the merged configuration of the default display.
5306 */
5307 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005308 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005309 // while initializing process record for system, see {@link
5310 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005311 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005312 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313 }
5314
5315 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5316 boolean initLocale) {
5317 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5318 }
5319
5320 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5321 boolean initLocale, boolean deferResume) {
5322 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5323 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5324 UserHandle.USER_NULL, deferResume);
5325 }
5326
Wale Ogunwale59507092018-10-29 09:00:30 -07005327 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005328 final long origId = Binder.clearCallingIdentity();
5329 try {
5330 synchronized (mGlobalLock) {
5331 updateConfigurationLocked(values, null, false, true, userId,
5332 false /* deferResume */);
5333 }
5334 } finally {
5335 Binder.restoreCallingIdentity(origId);
5336 }
5337 }
5338
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005339 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5340 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5341 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5342 deferResume, null /* result */);
5343 }
5344
5345 /**
5346 * Do either or both things: (1) change the current configuration, and (2)
5347 * make sure the given activity is running with the (now) current
5348 * configuration. Returns true if the activity has been left running, or
5349 * false if <var>starting</var> is being destroyed to match the new
5350 * configuration.
5351 *
5352 * @param userId is only used when persistent parameter is set to true to persist configuration
5353 * for that particular user
5354 */
5355 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5356 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5357 ActivityTaskManagerService.UpdateConfigurationResult result) {
5358 int changes = 0;
5359 boolean kept = true;
5360
Riddle Hsua0022cd2019-09-09 21:12:41 +08005361 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362 try {
5363 if (values != null) {
5364 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5365 deferResume);
5366 }
5367
5368 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5369 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005370 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005371 }
5372
5373 if (result != null) {
5374 result.changes = changes;
5375 result.activityRelaunched = !kept;
5376 }
5377 return kept;
5378 }
5379
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005380 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005381 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005383
Louis Chang677921f2019-12-06 16:44:24 +08005384 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005385 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005386
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005387 mTempConfig.setTo(getGlobalConfiguration());
5388 final int changes = mTempConfig.updateFrom(values);
5389 if (changes == 0) {
5390 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5391 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5392 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5393 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005394 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005395 return 0;
5396 }
5397
5398 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5399 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005400 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005401 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5402 values.colorMode,
5403 values.densityDpi,
5404 values.fontScale,
5405 values.hardKeyboardHidden,
5406 values.keyboard,
5407 values.keyboardHidden,
5408 values.mcc,
5409 values.mnc,
5410 values.navigation,
5411 values.navigationHidden,
5412 values.orientation,
5413 values.screenHeightDp,
5414 values.screenLayout,
5415 values.screenWidthDp,
5416 values.smallestScreenWidthDp,
5417 values.touchscreen,
5418 values.uiMode);
5419
5420
5421 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5422 final LocaleList locales = values.getLocales();
5423 int bestLocaleIndex = 0;
5424 if (locales.size() > 1) {
5425 if (mSupportedSystemLocales == null) {
5426 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5427 }
5428 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5429 }
5430 SystemProperties.set("persist.sys.locale",
5431 locales.get(bestLocaleIndex).toLanguageTag());
5432 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005433
5434 final Message m = PooledLambda.obtainMessage(
5435 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5436 locales.get(bestLocaleIndex));
5437 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005438 }
5439
Yunfan Chen75157d72018-07-27 14:47:21 +09005440 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005441
5442 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005443 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005444
5445 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5446 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005447 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005448
5449 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005451
5452 AttributeCache ac = AttributeCache.instance();
5453 if (ac != null) {
5454 ac.updateConfiguration(mTempConfig);
5455 }
5456
5457 // Make sure all resources in our process are updated right now, so that anyone who is going
5458 // to retrieve resource values after we return will be sure to get the new ones. This is
5459 // especially important during boot, where the first config change needs to guarantee all
5460 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005461 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005462
5463 // We need another copy of global config because we're scheduling some calls instead of
5464 // running them in place. We need to be sure that object we send will be handled unchanged.
5465 final Configuration configCopy = new Configuration(mTempConfig);
5466 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005467 final Message msg = PooledLambda.obtainMessage(
5468 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5469 this, userId, configCopy);
5470 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005471 }
5472
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005473 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5474 for (int i = pidMap.size() - 1; i >= 0; i--) {
5475 final int pid = pidMap.keyAt(i);
5476 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005477 if (DEBUG_CONFIGURATION) {
5478 Slog.v(TAG_CONFIGURATION, "Update process config of "
5479 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005480 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005481 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005482 }
5483
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005484 final Message msg = PooledLambda.obtainMessage(
5485 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5486 mAmInternal, changes, initLocale);
5487 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005488
5489 // Override configuration of the default display duplicates global config, so we need to
5490 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005491 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005492 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005493
5494 return changes;
5495 }
5496
Riddle Hsua0022cd2019-09-09 21:12:41 +08005497 /** @see WindowSurfacePlacer#deferLayout */
5498 void deferWindowLayout() {
5499 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5500 // Reset the reasons at the first entrance because we only care about the changes in the
5501 // deferred scope.
5502 mLayoutReasons = 0;
5503 }
5504
5505 mWindowManager.mWindowPlacerLocked.deferLayout();
5506 }
5507
5508 /** @see WindowSurfacePlacer#continueLayout */
5509 void continueWindowLayout() {
5510 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5511 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5512 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5513 }
5514 }
5515
5516 /**
5517 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5518 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5519 * defer count is gone.
5520 */
5521 void addWindowLayoutReasons(@LayoutReason int reasons) {
5522 mLayoutReasons |= reasons;
5523 }
5524
Wale Ogunwalef6733932018-06-27 05:14:34 -07005525 private void updateEventDispatchingLocked(boolean booted) {
5526 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5527 }
5528
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005529 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5530 final ContentResolver resolver = mContext.getContentResolver();
5531 Settings.System.putConfigurationForUser(resolver, config, userId);
5532 }
5533
5534 private void sendLocaleToMountDaemonMsg(Locale l) {
5535 try {
5536 IBinder service = ServiceManager.getService("mount");
5537 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5538 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5539 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5540 } catch (RemoteException e) {
5541 Log.e(TAG, "Error storing locale for decryption UI", e);
5542 }
5543 }
5544
Alison Cichowlas3e340502018-08-07 17:15:01 -04005545 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5546 mStartActivitySources.remove(permissionToken);
5547 mExpiredStartAsCallerTokens.add(permissionToken);
5548 }
5549
5550 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5551 mExpiredStartAsCallerTokens.remove(permissionToken);
5552 }
5553
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005554 boolean isActivityStartsLoggingEnabled() {
5555 return mAmInternal.isActivityStartsLoggingEnabled();
5556 }
5557
Michal Karpinski8596ded2018-11-14 14:43:48 +00005558 boolean isBackgroundActivityStartsEnabled() {
5559 return mAmInternal.isBackgroundActivityStartsEnabled();
5560 }
5561
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005563 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 mWindowManager.enableScreenAfterBoot();
5565
5566 synchronized (mGlobalLock) {
5567 updateEventDispatchingLocked(booted);
5568 }
5569 }
5570
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005571 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5572 if (r == null || !r.hasProcess()) {
5573 return KEY_DISPATCHING_TIMEOUT_MS;
5574 }
5575 return getInputDispatchingTimeoutLocked(r.app);
5576 }
5577
5578 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005579 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005580 }
5581
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 /**
5583 * Decide based on the configuration whether we should show the ANR,
5584 * crash, etc dialogs. The idea is that if there is no affordance to
5585 * press the on-screen buttons, or the user experience would be more
5586 * greatly impacted than the crash itself, we shouldn't show the dialog.
5587 *
5588 * A thought: SystemUI might also want to get told about this, the Power
5589 * dialog / global actions also might want different behaviors.
5590 */
5591 private void updateShouldShowDialogsLocked(Configuration config) {
5592 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5593 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5594 && config.navigation == Configuration.NAVIGATION_NONAV);
5595 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5596 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5597 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5598 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5599 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5600 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5601 HIDE_ERROR_DIALOGS, 0) != 0;
5602 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5603 }
5604
5605 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5606 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5607 FONT_SCALE, 1.0f, userId);
5608
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005609 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005610 if (getGlobalConfiguration().fontScale == scaleFactor) {
5611 return;
5612 }
5613
5614 final Configuration configuration
5615 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5616 configuration.fontScale = scaleFactor;
5617 updatePersistentConfiguration(configuration, userId);
5618 }
5619 }
5620
5621 // Actually is sleeping or shutting down or whatever else in the future
5622 // is an inactive state.
5623 boolean isSleepingOrShuttingDownLocked() {
5624 return isSleepingLocked() || mShuttingDown;
5625 }
5626
5627 boolean isSleepingLocked() {
5628 return mSleeping;
5629 }
5630
Riddle Hsu16567132018-08-16 21:37:47 +08005631 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005633 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005634 if (task.isActivityTypeStandard()) {
5635 if (mCurAppTimeTracker != r.appTimeTracker) {
5636 // We are switching app tracking. Complete the current one.
5637 if (mCurAppTimeTracker != null) {
5638 mCurAppTimeTracker.stop();
5639 mH.obtainMessage(
5640 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005641 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005642 mCurAppTimeTracker = null;
5643 }
5644 if (r.appTimeTracker != null) {
5645 mCurAppTimeTracker = r.appTimeTracker;
5646 startTimeTrackingFocusedActivityLocked();
5647 }
5648 } else {
5649 startTimeTrackingFocusedActivityLocked();
5650 }
5651 } else {
5652 r.appTimeTracker = null;
5653 }
5654 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5655 // TODO: Probably not, because we don't want to resume voice on switching
5656 // back to this activity
5657 if (task.voiceInteractor != null) {
5658 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5659 } else {
5660 finishRunningVoiceLocked();
5661
5662 if (mLastResumedActivity != null) {
5663 final IVoiceInteractionSession session;
5664
Louis Changcdec0802019-11-11 11:45:07 +08005665 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005666 if (lastResumedActivityTask != null
5667 && lastResumedActivityTask.voiceSession != null) {
5668 session = lastResumedActivityTask.voiceSession;
5669 } else {
5670 session = mLastResumedActivity.voiceSession;
5671 }
5672
5673 if (session != null) {
5674 // We had been in a voice interaction session, but now focused has
5675 // move to something different. Just finish the session, we can't
5676 // return to it and retain the proper state and synchronization with
5677 // the voice interaction service.
5678 finishVoiceTask(session);
5679 }
5680 }
5681 }
5682
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005683 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5684 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005685 }
5686 updateResumedAppTrace(r);
5687 mLastResumedActivity = r;
5688
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005689 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005690
5691 applyUpdateLockStateLocked(r);
5692 applyUpdateVrModeLocked(r);
5693
Jeff Changd136e772019-11-05 20:33:52 +08005694 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005695 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005696 r == null ? "NULL" : r.shortComponentName,
5697 reason);
5698 }
5699
5700 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5701 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005702 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005703 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005704 updateSleepIfNeededLocked();
5705 return token;
5706 }
5707 }
5708
5709 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005710 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005711 final boolean wasSleeping = mSleeping;
5712 boolean updateOomAdj = false;
5713
5714 if (!shouldSleep) {
5715 // If wasSleeping is true, we need to wake up activity manager state from when
5716 // we started sleeping. In either case, we need to apply the sleep tokens, which
5717 // will wake up stacks or put them to sleep as appropriate.
5718 if (wasSleeping) {
5719 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005720 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5721 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005722 startTimeTrackingFocusedActivityLocked();
5723 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005724 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005725 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5726 }
Louis Chang149d5c82019-12-30 09:47:39 +08005727 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005728 if (wasSleeping) {
5729 updateOomAdj = true;
5730 }
5731 } else if (!mSleeping && shouldSleep) {
5732 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005733 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5734 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005735 if (mCurAppTimeTracker != null) {
5736 mCurAppTimeTracker.stop();
5737 }
5738 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005739 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005740 mStackSupervisor.goingToSleepLocked();
5741 updateResumedAppTrace(null /* resumed */);
5742 updateOomAdj = true;
5743 }
5744 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005745 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005746 }
5747 }
5748
5749 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005750 mH.removeCallbacks(mUpdateOomAdjRunnable);
5751 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005752 }
5753
Wale Ogunwale53783742018-09-16 10:21:51 -07005754 void updateCpuStats() {
5755 mH.post(mAmInternal::updateCpuStats);
5756 }
5757
Hui Yu03d12402018-12-06 18:00:37 -08005758 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5759 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005760 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5761 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005762 mH.sendMessage(m);
5763 }
5764
Hui Yu03d12402018-12-06 18:00:37 -08005765 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005766 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005767 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005768 if (task != null) {
5769 final ActivityRecord rootActivity = task.getRootActivity();
5770 if (rootActivity != null) {
5771 taskRoot = rootActivity.mActivityComponent;
5772 }
5773 }
5774
Hui Yu03d12402018-12-06 18:00:37 -08005775 final Message m = PooledLambda.obtainMessage(
5776 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005777 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005778 mH.sendMessage(m);
5779 }
5780
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005781 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5782 String hostingType) {
5783 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005784 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5785 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005786 + activity.processName);
5787 }
5788 // Post message to start process to avoid possible deadlock of calling into AMS with the
5789 // ATMS lock held.
5790 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5791 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5792 isTop, hostingType, activity.intent.getComponent());
5793 mH.sendMessage(m);
5794 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005795 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005796 }
5797 }
5798
Wale Ogunwale53783742018-09-16 10:21:51 -07005799 void setBooting(boolean booting) {
5800 mAmInternal.setBooting(booting);
5801 }
5802
5803 boolean isBooting() {
5804 return mAmInternal.isBooting();
5805 }
5806
5807 void setBooted(boolean booted) {
5808 mAmInternal.setBooted(booted);
5809 }
5810
5811 boolean isBooted() {
5812 return mAmInternal.isBooted();
5813 }
5814
5815 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5816 mH.post(() -> {
5817 if (finishBooting) {
5818 mAmInternal.finishBooting();
5819 }
5820 if (enableScreen) {
5821 mInternal.enableScreenAfterBoot(isBooted());
5822 }
5823 });
5824 }
5825
5826 void setHeavyWeightProcess(ActivityRecord root) {
5827 mHeavyWeightProcess = root.app;
5828 final Message m = PooledLambda.obtainMessage(
5829 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005830 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005831 mH.sendMessage(m);
5832 }
5833
5834 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5835 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5836 return;
5837 }
5838
5839 mHeavyWeightProcess = null;
5840 final Message m = PooledLambda.obtainMessage(
5841 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5842 proc.mUserId);
5843 mH.sendMessage(m);
5844 }
5845
5846 private void cancelHeavyWeightProcessNotification(int userId) {
5847 final INotificationManager inm = NotificationManager.getService();
5848 if (inm == null) {
5849 return;
5850 }
5851 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005852 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005853 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5854 } catch (RuntimeException e) {
5855 Slog.w(TAG, "Error canceling notification for service", e);
5856 } catch (RemoteException e) {
5857 }
5858
5859 }
5860
5861 private void postHeavyWeightProcessNotification(
5862 WindowProcessController proc, Intent intent, int userId) {
5863 if (proc == null) {
5864 return;
5865 }
5866
5867 final INotificationManager inm = NotificationManager.getService();
5868 if (inm == null) {
5869 return;
5870 }
5871
5872 try {
5873 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5874 String text = mContext.getString(R.string.heavy_weight_notification,
5875 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5876 Notification notification =
5877 new Notification.Builder(context,
5878 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5879 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5880 .setWhen(0)
5881 .setOngoing(true)
5882 .setTicker(text)
5883 .setColor(mContext.getColor(
5884 com.android.internal.R.color.system_notification_accent_color))
5885 .setContentTitle(text)
5886 .setContentText(
5887 mContext.getText(R.string.heavy_weight_notification_detail))
5888 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5889 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5890 new UserHandle(userId)))
5891 .build();
5892 try {
5893 inm.enqueueNotificationWithTag("android", "android", null,
5894 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5895 } catch (RuntimeException e) {
5896 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5897 } catch (RemoteException e) {
5898 }
5899 } catch (PackageManager.NameNotFoundException e) {
5900 Slog.w(TAG, "Unable to create context for heavy notification", e);
5901 }
5902
5903 }
5904
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005905 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5906 IBinder token, String resultWho, int requestCode, Intent[] intents,
5907 String[] resolvedTypes, int flags, Bundle bOptions) {
5908
5909 ActivityRecord activity = null;
5910 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5911 activity = ActivityRecord.isInStackLocked(token);
5912 if (activity == null) {
5913 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5914 return null;
5915 }
5916 if (activity.finishing) {
5917 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5918 return null;
5919 }
5920 }
5921
5922 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5923 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5924 bOptions);
5925 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5926 if (noCreate) {
5927 return rec;
5928 }
5929 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5930 if (activity.pendingResults == null) {
5931 activity.pendingResults = new HashSet<>();
5932 }
5933 activity.pendingResults.add(rec.ref);
5934 }
5935 return rec;
5936 }
5937
Andrii Kulian52d255c2018-07-13 11:32:19 -07005938 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005939 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005940 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005941 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5942 mCurAppTimeTracker.start(resumedActivity.packageName);
5943 }
5944 }
5945
5946 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5947 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005948 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005949 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5950 }
5951 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005952 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005953 constructResumedTraceName(resumed.packageName), 0);
5954 }
5955 mTracedResumedActivity = resumed;
5956 }
5957
5958 private String constructResumedTraceName(String packageName) {
5959 return "focused app: " + packageName;
5960 }
5961
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005962 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005963 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005964 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005965 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005966 // mainStack is null during startup.
5967 if (mainStack != null) {
5968 if (changes != 0 && starting == null) {
5969 // If the configuration changed, and the caller is not already
5970 // in the process of starting an activity, then find the top
5971 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005972 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005973 }
5974
5975 if (starting != null) {
5976 kept = starting.ensureActivityConfiguration(changes,
5977 false /* preserveWindow */);
5978 // And we need to make sure at this point that all other activities
5979 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005980 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005981 !PRESERVE_WINDOWS);
5982 }
5983 }
5984
5985 return kept;
5986 }
5987
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005988 void scheduleAppGcsLocked() {
5989 mH.post(() -> mAmInternal.scheduleAppGcs());
5990 }
5991
Wale Ogunwale53783742018-09-16 10:21:51 -07005992 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5993 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5994 }
5995
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005996 /**
5997 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5998 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5999 * on demand.
6000 */
6001 IPackageManager getPackageManager() {
6002 return AppGlobals.getPackageManager();
6003 }
6004
6005 PackageManagerInternal getPackageManagerInternalLocked() {
6006 if (mPmInternal == null) {
6007 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
6008 }
6009 return mPmInternal;
6010 }
6011
Hai Zhangf4da9be2019-05-01 13:46:06 +08006012 PermissionPolicyInternal getPermissionPolicyInternal() {
6013 if (mPermissionPolicyInternal == null) {
6014 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
6015 }
6016 return mPermissionPolicyInternal;
6017 }
6018
Wale Ogunwale008163e2018-07-23 23:11:08 -07006019 AppWarnings getAppWarningsLocked() {
6020 return mAppWarnings;
6021 }
6022
Wale Ogunwale214f3482018-10-04 11:00:47 -07006023 Intent getHomeIntent() {
6024 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
6025 intent.setComponent(mTopComponent);
6026 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6027 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6028 intent.addCategory(Intent.CATEGORY_HOME);
6029 }
6030 return intent;
6031 }
6032
Chilun2ef71f72018-11-16 17:57:15 +08006033 /**
6034 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
6035 * activities.
6036 *
6037 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
6038 * component defined in config_secondaryHomeComponent.
6039 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
6040 */
6041 Intent getSecondaryHomeIntent(String preferredPackage) {
6042 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07006043 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
6044 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
6045 if (preferredPackage == null || useSystemProvidedLauncher) {
6046 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08006047 final String secondaryHomeComponent = mContext.getResources().getString(
6048 com.android.internal.R.string.config_secondaryHomeComponent);
6049 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
6050 } else {
6051 intent.setPackage(preferredPackage);
6052 }
6053 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6054 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6055 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
6056 }
6057 return intent;
6058 }
6059
Wale Ogunwale214f3482018-10-04 11:00:47 -07006060 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
6061 if (info == null) return null;
6062 ApplicationInfo newInfo = new ApplicationInfo(info);
6063 newInfo.initForUser(userId);
6064 return newInfo;
6065 }
6066
Wale Ogunwale9c103022018-10-18 07:44:54 -07006067 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006068 if (uid == SYSTEM_UID) {
6069 // The system gets to run in any process. If there are multiple processes with the same
6070 // uid, just pick the first (this should never happen).
6071 final SparseArray<WindowProcessController> procs =
6072 mProcessNames.getMap().get(processName);
6073 if (procs == null) return null;
6074 final int procCount = procs.size();
6075 for (int i = 0; i < procCount; i++) {
6076 final int procUid = procs.keyAt(i);
6077 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6078 // Don't use an app process or different user process for system component.
6079 continue;
6080 }
6081 return procs.valueAt(i);
6082 }
6083 }
6084
6085 return mProcessNames.get(processName, uid);
6086 }
6087
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006088 WindowProcessController getProcessController(IApplicationThread thread) {
6089 if (thread == null) {
6090 return null;
6091 }
6092
6093 final IBinder threadBinder = thread.asBinder();
6094 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6095 for (int i = pmap.size()-1; i >= 0; i--) {
6096 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6097 for (int j = procs.size() - 1; j >= 0; j--) {
6098 final WindowProcessController proc = procs.valueAt(j);
6099 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6100 return proc;
6101 }
6102 }
6103 }
6104
6105 return null;
6106 }
6107
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006108 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006109 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006110 if (proc == null) return null;
6111 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6112 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006113 }
6114 return null;
6115 }
6116
Riddle Hsua0536432019-02-16 00:38:59 +08006117 int getUidState(int uid) {
6118 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006119 }
6120
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006121 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006122 // A uid is considered to be foreground if it has a visible non-toast window.
6123 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006124 }
6125
Ricky Wai96f5c352019-04-10 18:40:17 +01006126 boolean isDeviceOwner(int uid) {
6127 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006128 }
6129
Ricky Wai96f5c352019-04-10 18:40:17 +01006130 void setDeviceOwnerUid(int uid) {
6131 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006132 }
6133
Wale Ogunwale9de19442018-10-18 19:05:03 -07006134 /**
6135 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6136 * the whitelist
6137 */
6138 String getPendingTempWhitelistTagForUidLocked(int uid) {
6139 return mPendingTempWhitelist.get(uid);
6140 }
6141
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006142 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6143 if (true || Build.IS_USER) {
6144 return;
6145 }
6146
6147 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6148 StrictMode.allowThreadDiskWrites();
6149 try {
6150 File tracesDir = new File("/data/anr");
6151 File tracesFile = null;
6152 try {
6153 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6154
6155 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006156 String timeString =
6157 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6158 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006159 sb.append(": ");
6160 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6161 sb.append(" since ");
6162 sb.append(msg);
6163 FileOutputStream fos = new FileOutputStream(tracesFile);
6164 fos.write(sb.toString().getBytes());
6165 if (app == null) {
6166 fos.write("\n*** No application process!".getBytes());
6167 }
6168 fos.close();
6169 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6170 } catch (IOException e) {
6171 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6172 return;
6173 }
6174
6175 if (app != null && app.getPid() > 0) {
6176 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6177 firstPids.add(app.getPid());
6178 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6179 }
6180
6181 File lastTracesFile = null;
6182 File curTracesFile = null;
6183 for (int i=9; i>=0; i--) {
6184 String name = String.format(Locale.US, "slow%02d.txt", i);
6185 curTracesFile = new File(tracesDir, name);
6186 if (curTracesFile.exists()) {
6187 if (lastTracesFile != null) {
6188 curTracesFile.renameTo(lastTracesFile);
6189 } else {
6190 curTracesFile.delete();
6191 }
6192 }
6193 lastTracesFile = curTracesFile;
6194 }
6195 tracesFile.renameTo(curTracesFile);
6196 } finally {
6197 StrictMode.setThreadPolicy(oldPolicy);
6198 }
6199 }
6200
Michal Karpinskida34cd42019-04-02 19:46:52 +01006201 boolean isAssociatedCompanionApp(int userId, int uid) {
6202 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6203 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006204 return false;
6205 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006206 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006207 }
6208
Issei Suzuki734bc942019-06-05 13:59:52 +02006209 void notifySingleTaskDisplayEmpty(int displayId) {
6210 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6211 }
6212
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006213 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006214 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006215
6216
Wale Ogunwale98875612018-10-12 07:53:02 -07006217 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6218 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006219
Riddle Hsud93a6c42018-11-29 21:50:06 +08006220 H(Looper looper) {
6221 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006222 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006223
6224 @Override
6225 public void handleMessage(Message msg) {
6226 switch (msg.what) {
6227 case REPORT_TIME_TRACKER_MSG: {
6228 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6229 tracker.deliverResult(mContext);
6230 } break;
6231 }
6232 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006233 }
6234
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006235 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006236 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006237
6238 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006239 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006240 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006241
6242 @Override
6243 public void handleMessage(Message msg) {
6244 switch (msg.what) {
6245 case DISMISS_DIALOG_UI_MSG: {
6246 final Dialog d = (Dialog) msg.obj;
6247 d.dismiss();
6248 break;
6249 }
6250 }
6251 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006252 }
6253
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 final class LocalService extends ActivityTaskManagerInternal {
6255 @Override
6256 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006257 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006258 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 }
6260
6261 @Override
6262 public ComponentName getHomeActivityForUser(int userId) {
6263 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006264 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006265 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006266 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 }
6268 }
6269
6270 @Override
6271 public void onLocalVoiceInteractionStarted(IBinder activity,
6272 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6273 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006274 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 }
6276 }
6277
6278 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006279 public void notifySingleTaskDisplayDrawn(int displayId) {
6280 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6281 }
6282
6283 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 public void notifyAppTransitionFinished() {
6285 synchronized (mGlobalLock) {
6286 mStackSupervisor.notifyAppTransitionDone();
6287 }
6288 }
6289
6290 @Override
6291 public void notifyAppTransitionCancelled() {
6292 synchronized (mGlobalLock) {
6293 mStackSupervisor.notifyAppTransitionDone();
6294 }
6295 }
6296
6297 @Override
6298 public List<IBinder> getTopVisibleActivities() {
6299 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006300 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
6302 }
6303
6304 @Override
6305 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6306 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006307 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 }
6309 }
6310
6311 @Override
6312 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6313 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006314 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 final String[] resolvedTypes = new String[intents.length];
6316
6317 // UID of the package on user userId.
6318 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6319 // packageUid may not be initialized.
6320 int packageUid = 0;
6321 final long ident = Binder.clearCallingIdentity();
6322
6323 try {
6324 for (int i = 0; i < intents.length; i++) {
6325 resolvedTypes[i] =
6326 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6327 }
6328
6329 packageUid = AppGlobals.getPackageManager().getPackageUid(
6330 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6331 } catch (RemoteException e) {
6332 // Shouldn't happen.
6333 } finally {
6334 Binder.restoreCallingIdentity(ident);
6335 }
6336
Riddle Hsu591bf612019-02-14 17:55:31 +08006337 return getActivityStartController().startActivitiesInPackage(
6338 packageUid, packageName,
6339 intents, resolvedTypes, null /* resultTo */,
6340 SafeActivityOptions.fromBundle(bOptions), userId,
6341 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6342 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006343 }
6344
6345 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006346 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6347 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6348 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6349 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006350 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006351 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006352 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006353 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6354 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6355 userId, validateIncomingUser, originatingPendingIntent,
6356 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006357 }
6358 }
6359
6360 @Override
6361 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6362 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6363 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006364 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006365 PendingIntentRecord originatingPendingIntent,
6366 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006367 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006368 synchronized (mGlobalLock) {
6369 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6370 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6371 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006372 validateIncomingUser, originatingPendingIntent,
6373 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006374 }
6375 }
6376
6377 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006378 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6379 Intent intent, Bundle options, int userId) {
6380 return ActivityTaskManagerService.this.startActivityAsUser(
6381 caller, callerPacakge, intent,
6382 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6383 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6384 false /*validateIncomingUser*/);
6385 }
6386
6387 @Override
lumark588a3e82018-07-20 18:53:54 +08006388 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006389 synchronized (mGlobalLock) {
6390
6391 // We might change the visibilities here, so prepare an empty app transition which
6392 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006393 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006394 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006395 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006396 return;
6397 }
Louis Chang677921f2019-12-06 16:44:24 +08006398 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006399 final boolean wasTransitionSet =
6400 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006401 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006402 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006403 }
Louis Chang149d5c82019-12-30 09:47:39 +08006404 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006405
6406 // If there was a transition set already we don't want to interfere with it as we
6407 // might be starting it too early.
6408 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006409 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006410 }
6411 }
6412 if (callback != null) {
6413 callback.run();
6414 }
6415 }
6416
6417 @Override
6418 public void notifyKeyguardTrustedChanged() {
6419 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006420 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006421 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006422 }
6423 }
6424 }
6425
6426 /**
6427 * Called after virtual display Id is updated by
6428 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6429 * {@param vrVr2dDisplayId}.
6430 */
6431 @Override
6432 public void setVr2dDisplayId(int vr2dDisplayId) {
6433 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6434 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006435 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006436 }
6437 }
6438
6439 @Override
6440 public void setFocusedActivity(IBinder token) {
6441 synchronized (mGlobalLock) {
6442 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6443 if (r == null) {
6444 throw new IllegalArgumentException(
6445 "setFocusedActivity: No activity record matching token=" + token);
6446 }
Louis Chang19443452018-10-09 12:10:21 +08006447 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006448 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006449 }
6450 }
6451 }
6452
6453 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006454 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006455 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006456 }
6457
6458 @Override
6459 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006460 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006461 }
6462
6463 @Override
6464 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006465 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006466 }
6467
6468 @Override
6469 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6470 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6471 }
6472
6473 @Override
6474 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006475 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006476 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006477
6478 @Override
6479 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6480 synchronized (mGlobalLock) {
6481 mActiveVoiceInteractionServiceComponent = component;
6482 }
6483 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006484
6485 @Override
6486 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6487 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6488 return;
6489 }
6490 synchronized (mGlobalLock) {
6491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6492 if (types == null) {
6493 if (uid < 0) {
6494 return;
6495 }
6496 types = new ArrayMap<>();
6497 mAllowAppSwitchUids.put(userId, types);
6498 }
6499 if (uid < 0) {
6500 types.remove(type);
6501 } else {
6502 types.put(type, uid);
6503 }
6504 }
6505 }
6506
6507 @Override
6508 public void onUserStopped(int userId) {
6509 synchronized (mGlobalLock) {
6510 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6511 mAllowAppSwitchUids.remove(userId);
6512 }
6513 }
6514
6515 @Override
6516 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6517 synchronized (mGlobalLock) {
6518 return ActivityTaskManagerService.this.isGetTasksAllowed(
6519 caller, callingPid, callingUid);
6520 }
6521 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006522
Riddle Hsua0536432019-02-16 00:38:59 +08006523 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006524 @Override
6525 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006526 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006527 mProcessNames.put(proc.mName, proc.mUid, proc);
6528 }
6529 }
6530
Riddle Hsua0536432019-02-16 00:38:59 +08006531 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006532 @Override
6533 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006534 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006535 mProcessNames.remove(name, uid);
6536 }
6537 }
6538
Riddle Hsua0536432019-02-16 00:38:59 +08006539 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006540 @Override
6541 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006542 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006543 if (proc == mHomeProcess) {
6544 mHomeProcess = null;
6545 }
6546 if (proc == mPreviousProcess) {
6547 mPreviousProcess = null;
6548 }
6549 }
6550 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006551
Riddle Hsua0536432019-02-16 00:38:59 +08006552 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006553 @Override
6554 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006555 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006556 return mTopProcessState;
6557 }
6558 }
6559
Riddle Hsua0536432019-02-16 00:38:59 +08006560 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006561 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006562 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006563 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006564 return proc == mHeavyWeightProcess;
6565 }
6566 }
6567
Riddle Hsua0536432019-02-16 00:38:59 +08006568 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006569 @Override
6570 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006571 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006572 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6573 }
6574 }
6575
6576 @Override
6577 public void finishHeavyWeightApp() {
6578 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006579 if (mHeavyWeightProcess != null) {
6580 mHeavyWeightProcess.finishActivities();
6581 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006582 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6583 mHeavyWeightProcess);
6584 }
6585 }
6586
Riddle Hsua0536432019-02-16 00:38:59 +08006587 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006588 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006589 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006590 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006591 return isSleepingLocked();
6592 }
6593 }
6594
6595 @Override
6596 public boolean isShuttingDown() {
6597 synchronized (mGlobalLock) {
6598 return mShuttingDown;
6599 }
6600 }
6601
6602 @Override
6603 public boolean shuttingDown(boolean booted, int timeout) {
6604 synchronized (mGlobalLock) {
6605 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006606 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006607 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006608 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006609 return mStackSupervisor.shutdownLocked(timeout);
6610 }
6611 }
6612
6613 @Override
6614 public void enableScreenAfterBoot(boolean booted) {
6615 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006616 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006617 mWindowManager.enableScreenAfterBoot();
6618 updateEventDispatchingLocked(booted);
6619 }
6620 }
6621
6622 @Override
6623 public boolean showStrictModeViolationDialog() {
6624 synchronized (mGlobalLock) {
6625 return mShowDialogs && !mSleeping && !mShuttingDown;
6626 }
6627 }
6628
6629 @Override
6630 public void showSystemReadyErrorDialogsIfNeeded() {
6631 synchronized (mGlobalLock) {
6632 try {
6633 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6634 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6635 + " data partition or your device will be unstable.");
6636 mUiHandler.post(() -> {
6637 if (mShowDialogs) {
6638 AlertDialog d = new BaseErrorDialog(mUiContext);
6639 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6640 d.setCancelable(false);
6641 d.setTitle(mUiContext.getText(R.string.android_system_label));
6642 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6643 d.setButton(DialogInterface.BUTTON_POSITIVE,
6644 mUiContext.getText(R.string.ok),
6645 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6646 d.show();
6647 }
6648 });
6649 }
6650 } catch (RemoteException e) {
6651 }
6652
6653 if (!Build.isBuildConsistent()) {
6654 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6655 mUiHandler.post(() -> {
6656 if (mShowDialogs) {
6657 AlertDialog d = new BaseErrorDialog(mUiContext);
6658 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6659 d.setCancelable(false);
6660 d.setTitle(mUiContext.getText(R.string.android_system_label));
6661 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6662 d.setButton(DialogInterface.BUTTON_POSITIVE,
6663 mUiContext.getText(R.string.ok),
6664 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6665 d.show();
6666 }
6667 });
6668 }
6669 }
6670 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006671
6672 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006673 public void onProcessMapped(int pid, WindowProcessController proc) {
6674 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006675 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006676 }
6677 }
6678
6679 @Override
6680 public void onProcessUnMapped(int pid) {
6681 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006682 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006683 }
6684 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006685
6686 @Override
6687 public void onPackageDataCleared(String name) {
6688 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006689 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006690 mAppWarnings.onPackageDataCleared(name);
6691 }
6692 }
6693
6694 @Override
6695 public void onPackageUninstalled(String name) {
6696 synchronized (mGlobalLock) {
6697 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006698 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006699 }
6700 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006701
6702 @Override
6703 public void onPackageAdded(String name, boolean replacing) {
6704 synchronized (mGlobalLock) {
6705 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6706 }
6707 }
6708
6709 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006710 public void onPackageReplaced(ApplicationInfo aInfo) {
6711 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006712 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 }
6714 }
6715
6716 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006717 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6718 synchronized (mGlobalLock) {
6719 return compatibilityInfoForPackageLocked(ai);
6720 }
6721 }
6722
Yunfan Chen75157d72018-07-27 14:47:21 +09006723 /**
6724 * Set the corresponding display information for the process global configuration. To be
6725 * called when we need to show IME on a different display.
6726 *
6727 * @param pid The process id associated with the IME window.
6728 * @param displayId The ID of the display showing the IME.
6729 */
6730 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006731 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006732 // Don't update process-level configuration for Multi-Client IME process since other
6733 // IMEs on other displays will also receive this configuration change due to IME
6734 // services use the same application config/context.
6735 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006736
Yunfan Chen75157d72018-07-27 14:47:21 +09006737 if (pid == MY_PID || pid < 0) {
6738 if (DEBUG_CONFIGURATION) {
6739 Slog.w(TAG,
6740 "Trying to update display configuration for system/invalid process.");
6741 }
6742 return;
6743 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006744 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006745 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006746 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006747 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006748 // Call might come when display is not yet added or has been removed.
6749 if (DEBUG_CONFIGURATION) {
6750 Slog.w(TAG, "Trying to update display configuration for non-existing "
6751 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006752 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006753 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006754 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006755 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006756 if (process == null) {
6757 if (DEBUG_CONFIGURATION) {
6758 Slog.w(TAG, "Trying to update display configuration for invalid "
6759 + "process, pid=" + pid);
6760 }
6761 return;
6762 }
lumarkddc77fb2019-06-27 22:22:23 +08006763 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006764 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006765 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006766 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006767
6768 @Override
6769 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006770 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006771 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006772 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006773 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006774 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006775 }
6776 }
6777 }
6778
6779 @Override
6780 public void clearPendingResultForActivity(IBinder activityToken,
6781 WeakReference<PendingIntentRecord> pir) {
6782 synchronized (mGlobalLock) {
6783 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6784 if (r != null && r.pendingResults != null) {
6785 r.pendingResults.remove(pir);
6786 }
6787 }
6788 }
6789
6790 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006791 public ActivityTokens getTopActivityForTask(int taskId) {
6792 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006793 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006794 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006795 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6796 + " Requested task not found");
6797 return null;
6798 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006799 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006800 if (activity == null) {
6801 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6802 + " Requested activity not found");
6803 return null;
6804 }
6805 if (!activity.attachedToProcess()) {
6806 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6807 + activity);
6808 return null;
6809 }
6810 return new ActivityTokens(activity.appToken, activity.assistToken,
6811 activity.app.getThread());
6812 }
6813 }
6814
6815 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006816 public IIntentSender getIntentSender(int type, String packageName,
6817 int callingUid, int userId, IBinder token, String resultWho,
6818 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6819 Bundle bOptions) {
6820 synchronized (mGlobalLock) {
6821 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6822 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6823 }
6824 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006825
6826 @Override
6827 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6828 synchronized (mGlobalLock) {
6829 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6830 if (r == null) {
6831 return null;
6832 }
6833 if (r.mServiceConnectionsHolder == null) {
6834 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6835 ActivityTaskManagerService.this, r);
6836 }
6837
6838 return r.mServiceConnectionsHolder;
6839 }
6840 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006841
6842 @Override
6843 public Intent getHomeIntent() {
6844 synchronized (mGlobalLock) {
6845 return ActivityTaskManagerService.this.getHomeIntent();
6846 }
6847 }
6848
6849 @Override
6850 public boolean startHomeActivity(int userId, String reason) {
6851 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006852 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006853 }
6854 }
6855
6856 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006857 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006858 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006859 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006860 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006861 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006862 }
Chilun8b1f1be2019-03-13 17:14:36 +08006863 }
6864
6865 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006866 public boolean startHomeOnAllDisplays(int userId, String reason) {
6867 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006868 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006869 }
6870 }
6871
Riddle Hsua0536432019-02-16 00:38:59 +08006872 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006873 @Override
6874 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006875 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006876 if (mFactoryTest == FACTORY_TEST_OFF) {
6877 return false;
6878 }
6879 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6880 && wpc.mName.equals(mTopComponent.getPackageName())) {
6881 return true;
6882 }
6883 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6884 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6885 }
6886 }
6887
6888 @Override
6889 public void updateTopComponentForFactoryTest() {
6890 synchronized (mGlobalLock) {
6891 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6892 return;
6893 }
6894 final ResolveInfo ri = mContext.getPackageManager()
6895 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6896 final CharSequence errorMsg;
6897 if (ri != null) {
6898 final ActivityInfo ai = ri.activityInfo;
6899 final ApplicationInfo app = ai.applicationInfo;
6900 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6901 mTopAction = Intent.ACTION_FACTORY_TEST;
6902 mTopData = null;
6903 mTopComponent = new ComponentName(app.packageName, ai.name);
6904 errorMsg = null;
6905 } else {
6906 errorMsg = mContext.getResources().getText(
6907 com.android.internal.R.string.factorytest_not_system);
6908 }
6909 } else {
6910 errorMsg = mContext.getResources().getText(
6911 com.android.internal.R.string.factorytest_no_action);
6912 }
6913 if (errorMsg == null) {
6914 return;
6915 }
6916
6917 mTopAction = null;
6918 mTopData = null;
6919 mTopComponent = null;
6920 mUiHandler.post(() -> {
6921 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6922 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006923 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006924 });
6925 }
6926 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927
Riddle Hsua0536432019-02-16 00:38:59 +08006928 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 @Override
6930 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6931 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006932 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006933 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006934 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006935
6936 wpc.clearRecentTasks();
6937 wpc.clearActivities();
6938
6939 if (wpc.isInstrumenting()) {
6940 finishInstrumentationCallback.run();
6941 }
6942
Jorim Jaggid0752812018-10-16 16:07:20 +02006943 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006944 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006945 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006946 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006947 // If there was nothing to resume, and we are not already restarting
6948 // this process, but there is a visible activity that is hosted by the
6949 // process...then make sure all visible activities are running, taking
6950 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006951 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006952 !PRESERVE_WINDOWS);
6953 }
6954 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006955 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006957 }
6958 }
6959 }
6960
6961 @Override
6962 public void closeSystemDialogs(String reason) {
6963 enforceNotIsolatedCaller("closeSystemDialogs");
6964
6965 final int pid = Binder.getCallingPid();
6966 final int uid = Binder.getCallingUid();
6967 final long origId = Binder.clearCallingIdentity();
6968 try {
6969 synchronized (mGlobalLock) {
6970 // Only allow this from foreground processes, so that background
6971 // applications can't abuse it to prevent system UI from being shown.
6972 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006973 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006974 if (!proc.isPerceptible()) {
6975 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6976 + " from background process " + proc);
6977 return;
6978 }
6979 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006980 mWindowManager.closeSystemDialogs(reason);
6981
Louis Chang149d5c82019-12-30 09:47:39 +08006982 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006983 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006984 // Call into AM outside the synchronized block.
6985 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 } finally {
6987 Binder.restoreCallingIdentity(origId);
6988 }
6989 }
6990
6991 @Override
6992 public void cleanupDisabledPackageComponents(
6993 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6994 synchronized (mGlobalLock) {
6995 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006996 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006997 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006998 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006999 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007000 }
7001
7002 // Clean-up disabled tasks
7003 getRecentTasks().cleanupDisabledPackageTasksLocked(
7004 packageName, disabledClasses, userId);
7005 }
7006 }
7007
7008 @Override
7009 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
7010 int userId) {
7011 synchronized (mGlobalLock) {
7012
7013 boolean didSomething =
7014 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08007015 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07007016 null, doit, evenPersistent, userId);
7017 return didSomething;
7018 }
7019 }
7020
7021 @Override
7022 public void resumeTopActivities(boolean scheduleIdle) {
7023 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007024 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08007026 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 }
7028 }
7029 }
7030
Riddle Hsua0536432019-02-16 00:38:59 +08007031 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007032 @Override
7033 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08007034 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007035 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
7036 }
7037 }
7038
Riddle Hsua0536432019-02-16 00:38:59 +08007039 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 @Override
7041 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08007042 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007043 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
7044 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
7045 }
7046 try {
Louis Chang149d5c82019-12-30 09:47:39 +08007047 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007048 } finally {
7049 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
7050 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07007051 }
7052 }
7053
7054 @Override
7055 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
7056 try {
7057 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
7058 throw new SecurityException("Only privileged app can call notifyLockedProfile");
7059 }
7060 } catch (RemoteException ex) {
7061 throw new SecurityException("Fail to check is caller a privileged app", ex);
7062 }
7063
7064 synchronized (mGlobalLock) {
7065 final long ident = Binder.clearCallingIdentity();
7066 try {
7067 if (mAmInternal.shouldConfirmCredentials(userId)) {
7068 if (mKeyguardController.isKeyguardLocked()) {
7069 // Showing launcher to avoid user entering credential twice.
7070 startHomeActivity(currentUserId, "notifyLockedProfile");
7071 }
Louis Chang149d5c82019-12-30 09:47:39 +08007072 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 }
7074 } finally {
7075 Binder.restoreCallingIdentity(ident);
7076 }
7077 }
7078 }
7079
7080 @Override
7081 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7082 mAmInternal.enforceCallingPermission(
7083 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7084
7085 synchronized (mGlobalLock) {
7086 final long ident = Binder.clearCallingIdentity();
7087 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007088 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7089 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007091 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7092 UserHandle.CURRENT);
7093 } finally {
7094 Binder.restoreCallingIdentity(ident);
7095 }
7096 }
7097 }
7098
7099 @Override
7100 public void writeActivitiesToProto(ProtoOutputStream proto) {
7101 synchronized (mGlobalLock) {
7102 // The output proto of "activity --proto activities"
7103 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007104 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007105 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7106 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 }
7108 }
7109
7110 @Override
7111 public void saveANRState(String reason) {
7112 synchronized (mGlobalLock) {
7113 final StringWriter sw = new StringWriter();
7114 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7115 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7116 if (reason != null) {
7117 pw.println(" Reason: " + reason);
7118 }
7119 pw.println();
7120 getActivityStartController().dump(pw, " ", null);
7121 pw.println();
7122 pw.println("-------------------------------------------------------------------------------");
7123 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7124 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7125 "" /* header */);
7126 pw.println();
7127 pw.close();
7128
7129 mLastANRState = sw.toString();
7130 }
7131 }
7132
7133 @Override
7134 public void clearSavedANRState() {
7135 synchronized (mGlobalLock) {
7136 mLastANRState = null;
7137 }
7138 }
7139
7140 @Override
7141 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7142 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7143 synchronized (mGlobalLock) {
7144 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7145 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7146 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7147 dumpLastANRLocked(pw);
7148 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7149 dumpLastANRTracesLocked(pw);
7150 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7151 dumpActivityStarterLocked(pw, dumpPackage);
7152 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7153 dumpActivityContainersLocked(pw);
7154 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7155 if (getRecentTasks() != null) {
7156 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7157 }
7158 }
7159 }
7160 }
7161
7162 @Override
7163 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7164 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7165 int wakefulness) {
7166 synchronized (mGlobalLock) {
7167 if (mHomeProcess != null && (dumpPackage == null
7168 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7169 if (needSep) {
7170 pw.println();
7171 needSep = false;
7172 }
7173 pw.println(" mHomeProcess: " + mHomeProcess);
7174 }
7175 if (mPreviousProcess != null && (dumpPackage == null
7176 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7177 if (needSep) {
7178 pw.println();
7179 needSep = false;
7180 }
7181 pw.println(" mPreviousProcess: " + mPreviousProcess);
7182 }
7183 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7184 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7185 StringBuilder sb = new StringBuilder(128);
7186 sb.append(" mPreviousProcessVisibleTime: ");
7187 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7188 pw.println(sb);
7189 }
7190 if (mHeavyWeightProcess != null && (dumpPackage == null
7191 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7192 if (needSep) {
7193 pw.println();
7194 needSep = false;
7195 }
7196 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7197 }
7198 if (dumpPackage == null) {
7199 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007200 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007201 }
7202 if (dumpAll) {
7203 if (dumpPackage == null) {
7204 pw.println(" mConfigWillChange: "
7205 + getTopDisplayFocusedStack().mConfigWillChange);
7206 }
7207 if (mCompatModePackages.getPackages().size() > 0) {
7208 boolean printed = false;
7209 for (Map.Entry<String, Integer> entry
7210 : mCompatModePackages.getPackages().entrySet()) {
7211 String pkg = entry.getKey();
7212 int mode = entry.getValue();
7213 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7214 continue;
7215 }
7216 if (!printed) {
7217 pw.println(" mScreenCompatPackages:");
7218 printed = true;
7219 }
7220 pw.println(" " + pkg + ": " + mode);
7221 }
7222 }
7223 }
7224
7225 if (dumpPackage == null) {
7226 pw.println(" mWakefulness="
7227 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007228 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 if (mRunningVoice != null) {
7230 pw.println(" mRunningVoice=" + mRunningVoice);
7231 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7232 }
7233 pw.println(" mSleeping=" + mSleeping);
7234 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7235 pw.println(" mVrController=" + mVrController);
7236 }
7237 if (mCurAppTimeTracker != null) {
7238 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7239 }
7240 if (mAllowAppSwitchUids.size() > 0) {
7241 boolean printed = false;
7242 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7243 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7244 for (int j = 0; j < types.size(); j++) {
7245 if (dumpPackage == null ||
7246 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7247 if (needSep) {
7248 pw.println();
7249 needSep = false;
7250 }
7251 if (!printed) {
7252 pw.println(" mAllowAppSwitchUids:");
7253 printed = true;
7254 }
7255 pw.print(" User ");
7256 pw.print(mAllowAppSwitchUids.keyAt(i));
7257 pw.print(": Type ");
7258 pw.print(types.keyAt(j));
7259 pw.print(" = ");
7260 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7261 pw.println();
7262 }
7263 }
7264 }
7265 }
7266 if (dumpPackage == null) {
7267 if (mController != null) {
7268 pw.println(" mController=" + mController
7269 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7270 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007271 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7272 pw.println(" mLaunchingActivityWakeLock="
7273 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007274 }
7275
7276 return needSep;
7277 }
7278 }
7279
7280 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007281 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7282 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007283 synchronized (mGlobalLock) {
7284 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007285 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007286 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007287 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7288 if (mRunningVoice != null) {
7289 final long vrToken = proto.start(
7290 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7291 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7292 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007293 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007294 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7295 proto.end(vrToken);
7296 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007297 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007298 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007299 if (mController != null) {
7300 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007301 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7302 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007303 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7304 proto.end(token);
7305 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007306 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7307 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007308 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007309 }
7310
7311 if (mHomeProcess != null && (dumpPackage == null
7312 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007313 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007314 }
7315
7316 if (mPreviousProcess != null && (dumpPackage == null
7317 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007318 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007319 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7320 }
7321
7322 if (mHeavyWeightProcess != null && (dumpPackage == null
7323 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007324 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007325 }
7326
7327 for (Map.Entry<String, Integer> entry
7328 : mCompatModePackages.getPackages().entrySet()) {
7329 String pkg = entry.getKey();
7330 int mode = entry.getValue();
7331 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7332 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7333 proto.write(PACKAGE, pkg);
7334 proto.write(MODE, mode);
7335 proto.end(compatToken);
7336 }
7337 }
7338
7339 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007340 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007341 }
7342
7343 }
7344 }
7345
7346 @Override
7347 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7348 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7349 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007350 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7351 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007352 }
7353
7354 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007355 public void dumpForOom(PrintWriter pw) {
7356 synchronized (mGlobalLock) {
7357 pw.println(" mHomeProcess: " + mHomeProcess);
7358 pw.println(" mPreviousProcess: " + mPreviousProcess);
7359 if (mHeavyWeightProcess != null) {
7360 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7361 }
7362 }
7363 }
7364
7365 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007366 public boolean canGcNow() {
7367 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007368 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007369 }
7370 }
7371
Riddle Hsua0536432019-02-16 00:38:59 +08007372 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007373 @Override
7374 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007375 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007376 if (mRootWindowContainer == null) {
7377 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007378 // oomadj after AMS created.
7379 return null;
7380 }
Louis Chang149d5c82019-12-30 09:47:39 +08007381 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007382 return top != null ? top.app : null;
7383 }
7384 }
7385
Riddle Hsua0536432019-02-16 00:38:59 +08007386 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007387 @Override
7388 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007389 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007390 if (mRootWindowContainer != null) {
7391 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007392 }
7393 }
7394 }
7395
7396 @Override
7397 public void scheduleDestroyAllActivities(String reason) {
7398 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007399 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007400 }
7401 }
7402
7403 @Override
7404 public void removeUser(int userId) {
7405 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007406 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007407 }
7408 }
7409
7410 @Override
7411 public boolean switchUser(int userId, UserState userState) {
7412 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007413 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007414 }
7415 }
7416
7417 @Override
7418 public void onHandleAppCrash(WindowProcessController wpc) {
7419 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007420 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007421 }
7422 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007423
7424 @Override
7425 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7426 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007427 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007428 }
7429 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007430
Riddle Hsua0536432019-02-16 00:38:59 +08007431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007432 @Override
7433 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007434 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007435 }
7436
Riddle Hsua0536432019-02-16 00:38:59 +08007437 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007438 @Override
7439 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007440 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007441 }
7442
Riddle Hsua0536432019-02-16 00:38:59 +08007443 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007444 @Override
7445 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007446 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007447 }
7448
Riddle Hsua0536432019-02-16 00:38:59 +08007449 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007450 @Override
7451 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007452 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007453 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007454
7455 @Override
7456 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007457 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007458 mPendingTempWhitelist.put(uid, tag);
7459 }
7460 }
7461
7462 @Override
7463 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007464 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007465 mPendingTempWhitelist.remove(uid);
7466 }
7467 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007468
7469 @Override
7470 public boolean handleAppCrashInActivityController(String processName, int pid,
7471 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7472 Runnable killCrashingAppCallback) {
7473 synchronized (mGlobalLock) {
7474 if (mController == null) {
7475 return false;
7476 }
7477
7478 try {
7479 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7480 stackTrace)) {
7481 killCrashingAppCallback.run();
7482 return true;
7483 }
7484 } catch (RemoteException e) {
7485 mController = null;
7486 Watchdog.getInstance().setActivityController(null);
7487 }
7488 return false;
7489 }
7490 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007491
7492 @Override
7493 public void removeRecentTasksByPackageName(String packageName, int userId) {
7494 synchronized (mGlobalLock) {
7495 mRecentTasks.removeTasksByPackageName(packageName, userId);
7496 }
7497 }
7498
7499 @Override
7500 public void cleanupRecentTasksForUser(int userId) {
7501 synchronized (mGlobalLock) {
7502 mRecentTasks.cleanupLocked(userId);
7503 }
7504 }
7505
7506 @Override
7507 public void loadRecentTasksForUser(int userId) {
7508 synchronized (mGlobalLock) {
7509 mRecentTasks.loadUserRecentsLocked(userId);
7510 }
7511 }
7512
7513 @Override
7514 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7515 synchronized (mGlobalLock) {
7516 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7517 }
7518 }
7519
7520 @Override
7521 public void flushRecentTasks() {
7522 mRecentTasks.flush();
7523 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007524
7525 @Override
7526 public WindowProcessController getHomeProcess() {
7527 synchronized (mGlobalLock) {
7528 return mHomeProcess;
7529 }
7530 }
7531
7532 @Override
7533 public WindowProcessController getPreviousProcess() {
7534 synchronized (mGlobalLock) {
7535 return mPreviousProcess;
7536 }
7537 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007538
7539 @Override
7540 public void clearLockedTasks(String reason) {
7541 synchronized (mGlobalLock) {
7542 getLockTaskController().clearLockedTasks(reason);
7543 }
7544 }
7545
7546 @Override
7547 public void updateUserConfiguration() {
7548 synchronized (mGlobalLock) {
7549 final Configuration configuration = new Configuration(getGlobalConfiguration());
7550 final int currentUserId = mAmInternal.getCurrentUserId();
7551 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7552 configuration, currentUserId, Settings.System.canWrite(mContext));
7553 updateConfigurationLocked(configuration, null /* starting */,
7554 false /* initLocale */, false /* persistent */, currentUserId,
7555 false /* deferResume */);
7556 }
7557 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007558
7559 @Override
7560 public boolean canShowErrorDialogs() {
7561 synchronized (mGlobalLock) {
7562 return mShowDialogs && !mSleeping && !mShuttingDown
7563 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7564 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7565 mAmInternal.getCurrentUserId())
7566 && !(UserManager.isDeviceInDemoMode(mContext)
7567 && mAmInternal.getCurrentUser().isDemo());
7568 }
7569 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007570
7571 @Override
7572 public void setProfileApp(String profileApp) {
7573 synchronized (mGlobalLock) {
7574 mProfileApp = profileApp;
7575 }
7576 }
7577
7578 @Override
7579 public void setProfileProc(WindowProcessController wpc) {
7580 synchronized (mGlobalLock) {
7581 mProfileProc = wpc;
7582 }
7583 }
7584
7585 @Override
7586 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7587 synchronized (mGlobalLock) {
7588 mProfilerInfo = profilerInfo;
7589 }
7590 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007591
7592 @Override
7593 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7594 synchronized (mGlobalLock) {
7595 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7596 }
7597 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007598
7599 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007600 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7601 boolean reducedResolution) {
7602 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7603 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007604 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007605
7606 @Override
7607 public boolean isUidForeground(int uid) {
7608 synchronized (mGlobalLock) {
7609 return ActivityTaskManagerService.this.isUidForeground(uid);
7610 }
7611 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007612
7613 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007614 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007615 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007616 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007617 }
7618 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007619
7620 @Override
7621 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007622 // Translate package names into UIDs
7623 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007624 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007625 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7626 if (uid >= 0) {
7627 result.add(uid);
7628 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007629 }
7630 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007631 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007632 }
7633 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007634 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007635}