blob: f019013eedf1a7f503da9598de8c4f8003cf0965 [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 Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
Robert Carr8a2f9132019-11-11 15:03:15 -0800228import android.view.ITaskOrganizer;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800250import com.android.internal.util.FrameworkStatsLog;
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
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 @Override
1835 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1836 synchronized (mGlobalLock) {
1837 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 if (r == null) {
1839 return;
1840 }
1841 final long origId = Binder.clearCallingIdentity();
1842 try {
1843 r.setRequestedOrientation(requestedOrientation);
1844 } finally {
1845 Binder.restoreCallingIdentity(origId);
1846 }
1847 }
1848 }
1849
1850 @Override
1851 public int getRequestedOrientation(IBinder token) {
1852 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001853 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1854 return (r != null)
1855 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858
1859 @Override
1860 public void setImmersive(IBinder token, boolean immersive) {
1861 synchronized (mGlobalLock) {
1862 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1863 if (r == null) {
1864 throw new IllegalArgumentException();
1865 }
1866 r.immersive = immersive;
1867
1868 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001869 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 }
1873 }
1874 }
1875
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 void applyUpdateLockStateLocked(ActivityRecord r) {
1877 // Modifications to the UpdateLock state are done on our handler, outside
1878 // the activity manager's locks. The new state is determined based on the
1879 // state *now* of the relevant activity record. The object is passed to
1880 // the handler solely for logging detail, not to be consulted/modified.
1881 final boolean nextState = r != null && r.immersive;
1882 mH.post(() -> {
1883 if (mUpdateLock.isHeld() != nextState) {
1884 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1885 "Applying new update lock state '" + nextState + "' for " + r);
1886 if (nextState) {
1887 mUpdateLock.acquire();
1888 } else {
1889 mUpdateLock.release();
1890 }
1891 }
1892 });
1893 }
1894
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 @Override
1896 public boolean isImmersive(IBinder token) {
1897 synchronized (mGlobalLock) {
1898 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1899 if (r == null) {
1900 throw new IllegalArgumentException();
1901 }
1902 return r.immersive;
1903 }
1904 }
1905
1906 @Override
1907 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001908 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001910 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 return (r != null) ? r.immersive : false;
1912 }
1913 }
1914
1915 @Override
1916 public void overridePendingTransition(IBinder token, String packageName,
1917 int enterAnim, int exitAnim) {
1918 synchronized (mGlobalLock) {
1919 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1920 if (self == null) {
1921 return;
1922 }
1923
1924 final long origId = Binder.clearCallingIdentity();
1925
1926 if (self.isState(
1927 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001928 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001929 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 }
1931
1932 Binder.restoreCallingIdentity(origId);
1933 }
1934 }
1935
1936 @Override
1937 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001938 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001940 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001941 if (r == null) {
1942 return ActivityManager.COMPAT_MODE_UNKNOWN;
1943 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001950 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001954 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001955 if (r == null) {
1956 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1957 return;
1958 }
1959 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001960 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 }
1962 }
1963
1964 @Override
1965 public int getLaunchedFromUid(IBinder activityToken) {
1966 ActivityRecord srec;
1967 synchronized (mGlobalLock) {
1968 srec = ActivityRecord.forTokenLocked(activityToken);
1969 }
1970 if (srec == null) {
1971 return -1;
1972 }
1973 return srec.launchedFromUid;
1974 }
1975
1976 @Override
1977 public String getLaunchedFromPackage(IBinder activityToken) {
1978 ActivityRecord srec;
1979 synchronized (mGlobalLock) {
1980 srec = ActivityRecord.forTokenLocked(activityToken);
1981 }
1982 if (srec == null) {
1983 return null;
1984 }
1985 return srec.launchedFromPackage;
1986 }
1987
1988 @Override
1989 public boolean convertFromTranslucent(IBinder token) {
1990 final long origId = Binder.clearCallingIdentity();
1991 try {
1992 synchronized (mGlobalLock) {
1993 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1994 if (r == null) {
1995 return false;
1996 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001997 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 }
1999 } finally {
2000 Binder.restoreCallingIdentity(origId);
2001 }
2002 }
2003
2004 @Override
2005 public boolean convertToTranslucent(IBinder token, Bundle options) {
2006 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2007 final long origId = Binder.clearCallingIdentity();
2008 try {
2009 synchronized (mGlobalLock) {
2010 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2011 if (r == null) {
2012 return false;
2013 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002014 final ActivityRecord under = r.getTask().getActivityBelow(r);
2015 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2017 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002018 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002019 }
2020 } finally {
2021 Binder.restoreCallingIdentity(origId);
2022 }
2023 }
2024
2025 @Override
2026 public void notifyActivityDrawn(IBinder token) {
2027 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2028 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002029 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002031 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 }
2033 }
2034 }
2035
2036 @Override
2037 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2038 synchronized (mGlobalLock) {
2039 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2040 if (r == null) {
2041 return;
2042 }
2043 r.reportFullyDrawnLocked(restoredFromBundle);
2044 }
2045 }
2046
2047 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002048 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 synchronized (mGlobalLock) {
2050 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002051 if (stack != null) {
2052 final int displayId = stack.getDisplayId();
2053 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 return DEFAULT_DISPLAY;
2056 }
2057 }
2058
2059 @Override
2060 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002061 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 long ident = Binder.clearCallingIdentity();
2063 try {
2064 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002065 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002067 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 }
2069 return null;
2070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(ident);
2073 }
2074 }
2075
2076 @Override
2077 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002078 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2080 final long callingId = Binder.clearCallingIdentity();
2081 try {
2082 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002083 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 if (stack == null) {
2085 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2086 return;
2087 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002088 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002089 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002090 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 }
2092 }
2093 } finally {
2094 Binder.restoreCallingIdentity(callingId);
2095 }
2096 }
2097
2098 @Override
2099 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002100 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2102 final long callingId = Binder.clearCallingIdentity();
2103 try {
2104 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002105 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002106 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 if (task == null) {
2108 return;
2109 }
2110 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002111 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002112 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 }
2114 }
2115 } finally {
2116 Binder.restoreCallingIdentity(callingId);
2117 }
2118 }
2119
2120 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002121 public void restartActivityProcessIfVisible(IBinder activityToken) {
2122 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2123 final long callingId = Binder.clearCallingIdentity();
2124 try {
2125 synchronized (mGlobalLock) {
2126 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2127 if (r == null) {
2128 return;
2129 }
2130 r.restartProcessIfVisible();
2131 }
2132 } finally {
2133 Binder.restoreCallingIdentity(callingId);
2134 }
2135 }
2136
2137 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002139 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 synchronized (mGlobalLock) {
2141 final long ident = Binder.clearCallingIdentity();
2142 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002143 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 "remove-task");
2145 } finally {
2146 Binder.restoreCallingIdentity(ident);
2147 }
2148 }
2149 }
2150
2151 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002152 public void removeAllVisibleRecentTasks() {
2153 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2154 synchronized (mGlobalLock) {
2155 final long ident = Binder.clearCallingIdentity();
2156 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002157 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002158 } finally {
2159 Binder.restoreCallingIdentity(ident);
2160 }
2161 }
2162 }
2163
2164 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2166 synchronized (mGlobalLock) {
2167 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2168 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002169 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172 return false;
2173 }
2174
2175 @Override
2176 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2177 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002178
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002179 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002180 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2181 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002182 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002183 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002184 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002185 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 }
2187 }
2188
2189 /**
2190 * Attempts to move a task backwards in z-order (the order of activities within the task is
2191 * unchanged).
2192 *
2193 * There are several possible results of this call:
2194 * - if the task is locked, then we will show the lock toast
2195 * - if there is a task behind the provided task, then that task is made visible and resumed as
2196 * this task is moved to the back
2197 * - otherwise, if there are no other tasks in the stack:
2198 * - if this task is in the pinned stack, then we remove the stack completely, which will
2199 * have the effect of moving the task to the top or bottom of the fullscreen stack
2200 * (depending on whether it is visible)
2201 * - otherwise, we simply return home and hide this task
2202 *
2203 * @param token A reference to the activity we wish to move
2204 * @param nonRoot If false then this only works if the activity is the root
2205 * of a task; if true it will work for any activity in a task.
2206 * @return Returns true if the move completed, false if not.
2207 */
2208 @Override
2209 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 synchronized (mGlobalLock) {
2212 final long origId = Binder.clearCallingIdentity();
2213 try {
2214 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002215 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002216 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002217 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 }
2219 } finally {
2220 Binder.restoreCallingIdentity(origId);
2221 }
2222 }
2223 return false;
2224 }
2225
2226 @Override
2227 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 long ident = Binder.clearCallingIdentity();
2230 Rect rect = new Rect();
2231 try {
2232 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002233 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002234 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2235 if (task == null) {
2236 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2237 return rect;
2238 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002239 if (task.getParent() != null) {
2240 rect.set(task.getBounds());
2241 } else if (task.mLastNonFullscreenBounds != null) {
2242 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 }
2244 }
2245 } finally {
2246 Binder.restoreCallingIdentity(ident);
2247 }
2248 return rect;
2249 }
2250
2251 @Override
2252 public ActivityManager.TaskDescription getTaskDescription(int id) {
2253 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002254 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002256 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2258 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002259 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 }
2261 }
2262 return null;
2263 }
2264
2265 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2267 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2268 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2269 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2270 return;
2271 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002273 synchronized (mGlobalLock) {
2274 final long ident = Binder.clearCallingIdentity();
2275 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002276 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002277 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002278 if (task == null) {
2279 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2280 return;
2281 }
2282
2283 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2284 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2285
2286 if (!task.isActivityTypeStandardOrUndefined()) {
2287 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2288 + " non-standard task " + taskId + " to windowing mode="
2289 + windowingMode);
2290 }
2291
2292 final ActivityStack stack = task.getStack();
2293 if (toTop) {
2294 stack.moveToFront("setTaskWindowingMode", task);
2295 }
2296 stack.setWindowingMode(windowingMode);
2297 } finally {
2298 Binder.restoreCallingIdentity(ident);
2299 }
2300 }
2301 }
2302
2303 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 ActivityRecord r = getCallingRecordLocked(token);
2307 return r != null ? r.info.packageName : null;
2308 }
2309 }
2310
2311 @Override
2312 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314 ActivityRecord r = getCallingRecordLocked(token);
2315 return r != null ? r.intent.getComponent() : null;
2316 }
2317 }
2318
2319 private ActivityRecord getCallingRecordLocked(IBinder token) {
2320 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2321 if (r == null) {
2322 return null;
2323 }
2324 return r.resultTo;
2325 }
2326
2327 @Override
2328 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002329 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330
2331 synchronized (mGlobalLock) {
2332 final long origId = Binder.clearCallingIdentity();
2333 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002334 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 } finally {
2336 Binder.restoreCallingIdentity(origId);
2337 }
2338 }
2339 }
2340
Mark Renouf446251d2019-04-26 10:22:41 -04002341 @Override
2342 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2343 synchronized (mGlobalLock) {
2344 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2345 if (r == null) {
2346 return;
2347 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002348 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002349 if (stack != null && stack.isSingleTaskInstance()) {
2350 // Single-task stacks are used for activities which are presented in floating
2351 // windows above full screen activities. Instead of directly finishing the
2352 // task, a task change listener is used to notify SystemUI so the action can be
2353 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002354 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002355 mTaskChangeNotificationController
2356 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2357 } else {
2358 try {
2359 callback.requestFinish();
2360 } catch (RemoteException e) {
2361 Slog.e(TAG, "Failed to invoke request finish callback", e);
2362 }
2363 }
2364 }
2365 }
2366
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 /**
2368 * TODO: Add mController hook
2369 */
2370 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2372 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002373 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374
2375 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2376 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2378 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 }
2380 }
2381
Ricky Waiaca8a772019-04-04 16:01:06 +01002382 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2383 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002385 final int callingPid = Binder.getCallingPid();
2386 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002387 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 SafeActivityOptions.abort(options);
2390 return;
2391 }
2392 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002393 WindowProcessController callerApp = null;
2394 if (appThread != null) {
2395 callerApp = getProcessController(appThread);
2396 }
2397 final ActivityStarter starter = getActivityStartController().obtainStarter(
2398 null /* intent */, "moveTaskToFront");
2399 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2400 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002401 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002402 return;
2403 }
2404 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002406 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 if (task == null) {
2408 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002409 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 return;
2411 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002412 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002414 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415 return;
2416 }
2417 ActivityOptions realOptions = options != null
2418 ? options.getOptions(mStackSupervisor)
2419 : null;
2420 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2421 false /* forceNonResizable */);
2422
Wale Ogunwale21e06482019-11-18 05:14:15 -08002423 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 if (topActivity != null) {
2425
2426 // We are reshowing a task, use a starting window to hide the initial draw delay
2427 // so the transition can start earlier.
2428 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2429 true /* taskSwitch */, fromRecents);
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(origId);
2433 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 }
2435
Ricky Waiaca8a772019-04-04 16:01:06 +01002436 /**
2437 * Return true if callingUid is system, or packageName belongs to that callingUid.
2438 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002439 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 try {
2441 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2442 if (packageName == null) {
2443 return false;
2444 }
2445 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2446 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2447 UserHandle.getUserId(callingUid));
2448 return UserHandle.isSameApp(callingUid, uid);
2449 }
2450 } catch (RemoteException e) {
2451 // Should not happen
2452 }
2453 return true;
2454 }
2455
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002456 /**
2457 * Checks that the provided package name matches the current calling UID, throws a security
2458 * exception if it doesn't.
2459 */
2460 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2461 final int callingUid = Binder.getCallingUid();
2462 if (isSameApp(callingUid, packageName)) {
2463 return;
2464 }
2465 final String msg = "Permission Denial: package=" + packageName
2466 + " does not belong to uid=" + callingUid;
2467 Slog.w(TAG, msg);
2468 throw new SecurityException(msg);
2469 }
2470
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002471 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2472 int callingPid, int callingUid, String name) {
2473 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2474 return true;
2475 }
2476
2477 if (getRecentTasks().isCallerRecents(sourceUid)) {
2478 return true;
2479 }
2480
2481 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2482 if (perm == PackageManager.PERMISSION_GRANTED) {
2483 return true;
2484 }
2485 if (checkAllowAppSwitchUid(sourceUid)) {
2486 return true;
2487 }
2488
2489 // If the actual IPC caller is different from the logical source, then
2490 // also see if they are allowed to control app switches.
2491 if (callingUid != -1 && callingUid != sourceUid) {
2492 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2493 if (perm == PackageManager.PERMISSION_GRANTED) {
2494 return true;
2495 }
2496 if (checkAllowAppSwitchUid(callingUid)) {
2497 return true;
2498 }
2499 }
2500
2501 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2502 return false;
2503 }
2504
2505 private boolean checkAllowAppSwitchUid(int uid) {
2506 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2507 if (types != null) {
2508 for (int i = types.size() - 1; i >= 0; i--) {
2509 if (types.valueAt(i).intValue() == uid) {
2510 return true;
2511 }
2512 }
2513 }
2514 return false;
2515 }
2516
2517 @Override
2518 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2519 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2520 "setActivityController()");
2521 synchronized (mGlobalLock) {
2522 mController = controller;
2523 mControllerIsAMonkey = imAMonkey;
2524 Watchdog.getInstance().setActivityController(controller);
2525 }
2526 }
2527
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002528 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 synchronized (mGlobalLock) {
2530 return mController != null && mControllerIsAMonkey;
2531 }
2532 }
2533
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 @Override
2535 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2536 synchronized (mGlobalLock) {
2537 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2538 }
2539 }
2540
2541 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2543 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2544 }
2545
2546 @Override
2547 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2548 @WindowConfiguration.ActivityType int ignoreActivityType,
2549 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2550 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002551 final int callingPid = Binder.getCallingPid();
2552 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002553 final int[] profileIds = getUserManager().getProfileIds(
2554 UserHandle.getUserId(callingUid), true);
2555 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2556 for (int i = 0; i < profileIds.length; i++) {
2557 callingProfileIds.add(profileIds[i]);
2558 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2560
2561 synchronized (mGlobalLock) {
2562 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2563
Nicholas Sauer0259e532019-08-30 08:24:55 -07002564 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002565 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002566 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 }
2568
2569 return list;
2570 }
2571
2572 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002573 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2574 synchronized (mGlobalLock) {
2575 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002576 try {
2577 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2578 if (r == null) return;
2579
2580 final PooledConsumer c = PooledLambda.obtainConsumer(
2581 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2582 r, resultWho, requestCode);
2583 // TODO: This should probably only loop over the task since you need to be in the
2584 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002585 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002586 c.recycle();
2587
2588 updateOomAdj();
2589 } finally {
2590 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002592 }
2593 }
2594
2595 @Override
2596 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 ActivityStack stack = ActivityRecord.getStackLocked(token);
2599 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002600 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002601 }
2602 return false;
2603 }
2604 }
2605
2606 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002608 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 synchronized (mGlobalLock) {
2610 final long ident = Binder.clearCallingIdentity();
2611 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002612 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 if (task == null) {
2614 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2615 return;
2616 }
2617
2618 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2619 + " to stackId=" + stackId + " toTop=" + toTop);
2620
Louis Chang149d5c82019-12-30 09:47:39 +08002621 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 if (stack == null) {
2623 throw new IllegalStateException(
2624 "moveTaskToStack: No stack for stackId=" + stackId);
2625 }
2626 if (!stack.isActivityTypeStandardOrUndefined()) {
2627 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2628 + taskId + " to stack " + stackId);
2629 }
2630 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002631 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002632 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2633 }
2634 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2635 "moveTaskToStack");
2636 } finally {
2637 Binder.restoreCallingIdentity(ident);
2638 }
2639 }
2640 }
2641
2642 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2644 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645
2646 final long ident = Binder.clearCallingIdentity();
2647 try {
2648 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002649 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002650 if (stack == null) {
2651 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2652 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002653 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002654 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2655 throw new IllegalArgumentException("Stack: " + stackId
2656 + " doesn't support animated resize.");
2657 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002658 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002659 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002660 }
2661 } finally {
2662 Binder.restoreCallingIdentity(ident);
2663 }
2664 }
2665
wilsonshih5c4cf522019-01-25 09:03:47 +08002666 @Override
2667 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2668 int animationDuration) {
2669 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2670
2671 final long ident = Binder.clearCallingIdentity();
2672 try {
2673 synchronized (mGlobalLock) {
2674 if (xOffset == 0 && yOffset == 0) {
2675 return;
2676 }
Louis Chang149d5c82019-12-30 09:47:39 +08002677 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 if (stack == null) {
2679 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2680 return;
2681 }
2682 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2683 throw new IllegalArgumentException("Stack: " + stackId
2684 + " doesn't support animated resize.");
2685 }
2686 final Rect destBounds = new Rect();
2687 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002688 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002689 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2690 return;
2691 }
2692 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002693 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002694 animationDuration, false /* fromFullscreen */);
2695 }
2696 } finally {
2697 Binder.restoreCallingIdentity(ident);
2698 }
2699 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 /**
2701 * Moves the specified task to the primary-split-screen stack.
2702 *
2703 * @param taskId Id of task to move.
2704 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2705 * exist already. See
2706 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2707 * and
2708 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2709 * @param toTop If the task and stack should be moved to the top.
2710 * @param animate Whether we should play an animation for the moving the task.
2711 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2712 * stack. Pass {@code null} to use default bounds.
2713 * @param showRecents If the recents activity should be shown on the other side of the task
2714 * going into split-screen mode.
2715 */
2716 @Override
2717 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2718 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002719 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 "setTaskWindowingModeSplitScreenPrimary()");
2721 synchronized (mGlobalLock) {
2722 final long ident = Binder.clearCallingIdentity();
2723 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002724 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002725 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 if (task == null) {
2727 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2728 return false;
2729 }
2730 if (DEBUG_STACK) Slog.d(TAG_STACK,
2731 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2732 + " to createMode=" + createMode + " toTop=" + toTop);
2733 if (!task.isActivityTypeStandardOrUndefined()) {
2734 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2735 + " non-standard task " + taskId + " to split-screen windowing mode");
2736 }
2737
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002738 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 final int windowingMode = task.getWindowingMode();
2740 final ActivityStack stack = task.getStack();
2741 if (toTop) {
2742 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2743 }
2744 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002745 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2746 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002747 return windowingMode != task.getWindowingMode();
2748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752 }
2753
2754 /**
2755 * Removes stacks in the input windowing modes from the system if they are of activity type
2756 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2757 */
2758 @Override
2759 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002761 "removeStacksInWindowingModes()");
2762
2763 synchronized (mGlobalLock) {
2764 final long ident = Binder.clearCallingIdentity();
2765 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002766 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
2770 }
2771 }
2772
2773 @Override
2774 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002776 "removeStacksWithActivityTypes()");
2777
2778 synchronized (mGlobalLock) {
2779 final long ident = Binder.clearCallingIdentity();
2780 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002781 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002782 } finally {
2783 Binder.restoreCallingIdentity(ident);
2784 }
2785 }
2786 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787
2788 @Override
2789 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2790 int userId) {
2791 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2793 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002795 final boolean detailed = checkGetTasksPermission(
2796 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2797 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 == PackageManager.PERMISSION_GRANTED;
2799
2800 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002801 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 callingUid);
2803 }
2804 }
2805
2806 @Override
2807 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002808 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 long ident = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002812 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 }
2814 } finally {
2815 Binder.restoreCallingIdentity(ident);
2816 }
2817 }
2818
2819 @Override
2820 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002821 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 long ident = Binder.clearCallingIdentity();
2823 try {
2824 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002825 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 } finally {
2828 Binder.restoreCallingIdentity(ident);
2829 }
2830 }
2831
2832 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002833 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2834 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2835 long ident = Binder.clearCallingIdentity();
2836 try {
2837 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002838 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002839 }
2840 } finally {
2841 Binder.restoreCallingIdentity(ident);
2842 }
2843 }
2844
2845 @Override
2846 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2847 int displayId) {
2848 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002852 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(ident);
2856 }
2857 }
2858
2859 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002861 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 final long callingUid = Binder.getCallingUid();
2863 final long origId = Binder.clearCallingIdentity();
2864 try {
2865 synchronized (mGlobalLock) {
2866 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002867 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2869 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(origId);
2873 }
2874 }
2875
2876 @Override
2877 public void startLockTaskModeByToken(IBinder token) {
2878 synchronized (mGlobalLock) {
2879 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2880 if (r == null) {
2881 return;
2882 }
Louis Changcdec0802019-11-11 11:45:07 +08002883 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 }
2886
2887 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002888 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 // This makes inner call to look as if it was initiated by system.
2891 long ident = Binder.clearCallingIdentity();
2892 try {
2893 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002894 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002895 MATCH_TASK_IN_STACKS_ONLY);
2896 if (task == null) {
2897 return;
2898 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899
2900 // When starting lock task mode the stack must be in front and focused
2901 task.getStack().moveToFront("startSystemLockTaskMode");
2902 startLockTaskModeLocked(task, true /* isSystemCaller */);
2903 }
2904 } finally {
2905 Binder.restoreCallingIdentity(ident);
2906 }
2907 }
2908
2909 @Override
2910 public void stopLockTaskModeByToken(IBinder token) {
2911 synchronized (mGlobalLock) {
2912 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2913 if (r == null) {
2914 return;
2915 }
Louis Changcdec0802019-11-11 11:45:07 +08002916 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 }
2918 }
2919
2920 /**
2921 * This API should be called by SystemUI only when user perform certain action to dismiss
2922 * lock task mode. We should only dismiss pinned lock task mode in this case.
2923 */
2924 @Override
2925 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002926 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2928 }
2929
Louis Changcdec0802019-11-11 11:45:07 +08002930 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2932 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2933 return;
2934 }
2935
Louis Chang149d5c82019-12-30 09:47:39 +08002936 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002937 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 throw new IllegalArgumentException("Invalid task, not in foreground");
2939 }
2940
2941 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2942 // system or a specific app.
2943 // * System-initiated requests will only start the pinned mode (screen pinning)
2944 // * App-initiated requests
2945 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2946 // - will start the pinned mode, otherwise
2947 final int callingUid = Binder.getCallingUid();
2948 long ident = Binder.clearCallingIdentity();
2949 try {
2950 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002951 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002953 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 } finally {
2955 Binder.restoreCallingIdentity(ident);
2956 }
2957 }
2958
Louis Changcdec0802019-11-11 11:45:07 +08002959 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 final int callingUid = Binder.getCallingUid();
2961 long ident = Binder.clearCallingIdentity();
2962 try {
2963 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002964 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 }
2966 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2967 // task and jumping straight into a call in the case of emergency call back.
2968 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2969 if (tm != null) {
2970 tm.showInCallScreen(false);
2971 }
2972 } finally {
2973 Binder.restoreCallingIdentity(ident);
2974 }
2975 }
2976
2977 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002978 public void updateLockTaskPackages(int userId, String[] packages) {
2979 final int callingUid = Binder.getCallingUid();
2980 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2981 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2982 "updateLockTaskPackages()");
2983 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002984 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002985 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2986 + Arrays.toString(packages));
2987 getLockTaskController().updateLockTaskPackages(userId, packages);
2988 }
2989 }
2990
2991 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 public boolean isInLockTaskMode() {
2993 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2994 }
2995
2996 @Override
2997 public int getLockTaskModeState() {
2998 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002999 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 }
3001 }
3002
3003 @Override
3004 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3007 if (r != null) {
3008 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003009 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 }
3012 }
3013 }
3014
3015 @Override
3016 public Bundle getActivityOptions(IBinder token) {
3017 final long origId = Binder.clearCallingIdentity();
3018 try {
3019 synchronized (mGlobalLock) {
3020 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3021 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003022 final ActivityOptions activityOptions = r.takeOptionsLocked(
3023 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 return activityOptions == null ? null : activityOptions.toBundle();
3025 }
3026 return null;
3027 }
3028 } finally {
3029 Binder.restoreCallingIdentity(origId);
3030 }
3031 }
3032
3033 @Override
3034 public List<IBinder> getAppTasks(String callingPackage) {
3035 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003036 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 long ident = Binder.clearCallingIdentity();
3038 try {
3039 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003040 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 }
3042 } finally {
3043 Binder.restoreCallingIdentity(ident);
3044 }
3045 }
3046
3047 @Override
3048 public void finishVoiceTask(IVoiceInteractionSession session) {
3049 synchronized (mGlobalLock) {
3050 final long origId = Binder.clearCallingIdentity();
3051 try {
3052 // TODO: VI Consider treating local voice interactions and voice tasks
3053 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003054 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 } finally {
3056 Binder.restoreCallingIdentity(origId);
3057 }
3058 }
3059
3060 }
3061
3062 @Override
3063 public boolean isTopOfTask(IBinder token) {
3064 synchronized (mGlobalLock) {
3065 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003066 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 }
3068 }
3069
3070 @Override
3071 public void notifyLaunchTaskBehindComplete(IBinder token) {
3072 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3073 }
3074
3075 @Override
3076 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003077 mH.post(() -> {
3078 synchronized (mGlobalLock) {
3079 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003080 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003081 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003082 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003083 } catch (RemoteException e) {
3084 }
3085 }
3086 }
3087
3088 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 }
3090
3091 /** Called from an app when assist data is ready. */
3092 @Override
3093 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3094 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 synchronized (pae) {
3097 pae.result = extras;
3098 pae.structure = structure;
3099 pae.content = content;
3100 if (referrer != null) {
3101 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3102 }
3103 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003104 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003105 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003106 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 structure.setHomeActivity(pae.isHome);
3108 }
3109 pae.haveResult = true;
3110 pae.notifyAll();
3111 if (pae.intent == null && pae.receiver == null) {
3112 // Caller is just waiting for the result.
3113 return;
3114 }
3115 }
3116 // We are now ready to launch the assist activity.
3117 IAssistDataReceiver sendReceiver = null;
3118 Bundle sendBundle = null;
3119 synchronized (mGlobalLock) {
3120 buildAssistBundleLocked(pae, extras);
3121 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 if (!exists) {
3124 // Timed out.
3125 return;
3126 }
3127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003128 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003129 // Caller wants result sent back to them.
3130 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003131 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003132 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003133 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3134 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3136 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3137 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3138 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3139 }
3140 }
3141 if (sendReceiver != null) {
3142 try {
3143 sendReceiver.onHandleAssistData(sendBundle);
3144 } catch (RemoteException e) {
3145 }
3146 return;
3147 }
3148
3149 final long ident = Binder.clearCallingIdentity();
3150 try {
3151 if (TextUtils.equals(pae.intent.getAction(),
3152 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003153 // Start voice interaction through VoiceInteractionManagerService.
3154 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3155 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 } else {
3157 pae.intent.replaceExtras(pae.extras);
3158 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3159 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3160 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003161 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162
3163 try {
3164 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3165 } catch (ActivityNotFoundException e) {
3166 Slog.w(TAG, "No activity to handle assist action.", e);
3167 }
3168 }
3169 } finally {
3170 Binder.restoreCallingIdentity(ident);
3171 }
3172 }
3173
3174 @Override
3175 public int addAppTask(IBinder activityToken, Intent intent,
3176 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3177 final int callingUid = Binder.getCallingUid();
3178 final long callingIdent = Binder.clearCallingIdentity();
3179
3180 try {
3181 synchronized (mGlobalLock) {
3182 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3183 if (r == null) {
3184 throw new IllegalArgumentException("Activity does not exist; token="
3185 + activityToken);
3186 }
3187 ComponentName comp = intent.getComponent();
3188 if (comp == null) {
3189 throw new IllegalArgumentException("Intent " + intent
3190 + " must specify explicit component");
3191 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003192 if (thumbnail.getWidth() != mThumbnailWidth
3193 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 throw new IllegalArgumentException("Bad thumbnail size: got "
3195 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003196 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 }
3198 if (intent.getSelector() != null) {
3199 intent.setSelector(null);
3200 }
3201 if (intent.getSourceBounds() != null) {
3202 intent.setSourceBounds(null);
3203 }
3204 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3205 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3206 // The caller has added this as an auto-remove task... that makes no
3207 // sense, so turn off auto-remove.
3208 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3209 }
3210 }
3211 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3212 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3213 if (ainfo.applicationInfo.uid != callingUid) {
3214 throw new SecurityException(
3215 "Can't add task for another application: target uid="
3216 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3217 }
3218
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003219 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003220 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003221 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003222 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003224 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 return INVALID_TASK_ID;
3226 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003227 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003228
3229 // TODO: Send the thumbnail to WM to store it.
3230
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003231 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232 }
3233 } finally {
3234 Binder.restoreCallingIdentity(callingIdent);
3235 }
3236 }
3237
3238 @Override
3239 public Point getAppTaskThumbnailSize() {
3240 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243 }
3244
3245 @Override
3246 public void setTaskResizeable(int taskId, int resizeableMode) {
3247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003248 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3250 if (task == null) {
3251 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3252 return;
3253 }
3254 task.setResizeMode(resizeableMode);
3255 }
3256 }
3257
3258 @Override
3259 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003260 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 long ident = Binder.clearCallingIdentity();
3262 try {
3263 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003264 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003265 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 if (task == null) {
3267 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3268 return;
3269 }
3270 // Place the task in the right stack if it isn't there already based on
3271 // the requested bounds.
3272 // The stack transition logic is:
3273 // - a null bounds on a freeform task moves that task to fullscreen
3274 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3275 // that task to freeform
3276 // - otherwise the task is not moved
3277 ActivityStack stack = task.getStack();
3278 if (!task.getWindowConfiguration().canResizeTask()) {
3279 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3280 }
3281 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3282 stack = stack.getDisplay().getOrCreateStack(
3283 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3284 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3285 stack = stack.getDisplay().getOrCreateStack(
3286 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3287 }
3288
3289 // Reparent the task to the right stack if necessary
3290 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3291 if (stack != task.getStack()) {
3292 // Defer resume until the task is resized below
3293 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3294 DEFER_RESUME, "resizeTask");
3295 preserveWindow = false;
3296 }
3297
3298 // After reparenting (which only resizes the task to the stack bounds), resize the
3299 // task to the actual bounds provided
3300 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3301 }
3302 } finally {
3303 Binder.restoreCallingIdentity(ident);
3304 }
3305 }
3306
Evan Roskya80f11c2020-01-23 19:17:10 -08003307 private int sanitizeAndApplyChange(WindowContainer container,
Evan Roskyddedfd42019-10-04 13:38:38 -07003308 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003309 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003310 throw new RuntimeException("Invalid token in task transaction");
3311 }
3312 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3313 // masks here.
3314 int configMask = change.getConfigSetMask();
3315 int windowMask = change.getWindowSetMask();
3316 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3317 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3318 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
Evan Rosky226de132020-01-03 18:00:29 -08003319 int effects = 0;
3320 if (configMask != 0) {
3321 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3322 c.setTo(change.getConfiguration(), configMask, windowMask);
3323 container.onRequestedOverrideConfigurationChanged(c);
3324 // TODO(b/145675353): remove the following once we could apply new bounds to the
3325 // pinned stack together with its children.
3326 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3327 effects |= TRANSACT_EFFECTS_CLIENT_CONFIG;
3328 }
3329 if ((change.getChangeMask() & WindowContainerTransaction.Change.CHANGE_FOCUSABLE) != 0) {
3330 if (container.setFocusable(change.getFocusable())) {
3331 effects |= TRANSACT_EFFECTS_LIFECYCLE;
3332 }
3333 }
3334 return effects;
Hongwei Wangebf18082019-09-26 14:25:11 -07003335 }
3336
3337 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3338 int windowMask, Configuration config) {
3339 if ((container instanceof ActivityStack)
3340 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3341 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3342 final ActivityStack stack = (ActivityStack) container;
3343 if (stack.inPinnedWindowingMode()) {
3344 stack.resize(config.windowConfiguration.getBounds(),
3345 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3346 PRESERVE_WINDOWS, true /* deferResume */);
3347 }
3348 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003349 }
3350
Evan Roskya80f11c2020-01-23 19:17:10 -08003351 private int applyWindowContainerChange(WindowContainer wc,
Robert Carr8a2f9132019-11-11 15:03:15 -08003352 WindowContainerTransaction.Change c) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003353 int effects = sanitizeAndApplyChange(wc, c);
Robert Carr8a2f9132019-11-11 15:03:15 -08003354
3355 Rect enterPipBounds = c.getEnterPipBounds();
3356 if (enterPipBounds != null) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003357 Task tr = (Task) wc;
Robert Carr8a2f9132019-11-11 15:03:15 -08003358 mStackSupervisor.updatePictureInPictureMode(tr,
3359 enterPipBounds, true);
3360 }
Evan Rosky226de132020-01-03 18:00:29 -08003361 return effects;
Robert Carr8a2f9132019-11-11 15:03:15 -08003362 }
3363
Evan Roskyddedfd42019-10-04 13:38:38 -07003364 @Override
3365 public void applyContainerTransaction(WindowContainerTransaction t) {
3366 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
Evan Rosky226de132020-01-03 18:00:29 -08003367 if (t == null) {
3368 return;
3369 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003370 long ident = Binder.clearCallingIdentity();
3371 try {
Evan Roskyddedfd42019-10-04 13:38:38 -07003372 synchronized (mGlobalLock) {
Evan Rosky226de132020-01-03 18:00:29 -08003373 int effects = 0;
3374 deferWindowLayout();
3375 try {
3376 ArraySet<WindowContainer> haveConfigChanges = new ArraySet<>();
3377 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3378 t.getChanges().entrySet().iterator();
3379 while (entries.hasNext()) {
3380 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3381 entries.next();
Evan Roskya80f11c2020-01-23 19:17:10 -08003382 final WindowContainer wc = WindowContainer.RemoteToken.fromBinder(
3383 entry.getKey()).getContainer();
3384 int containerEffect = applyWindowContainerChange(wc, entry.getValue());
Evan Rosky226de132020-01-03 18:00:29 -08003385 effects |= containerEffect;
3386 // Lifecycle changes will trigger ensureConfig for everything.
3387 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) == 0
3388 && (containerEffect & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003389 haveConfigChanges.add(wc);
Evan Rosky226de132020-01-03 18:00:29 -08003390 }
3391 }
3392 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) != 0) {
3393 // Already calls ensureActivityConfig
3394 mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
3395 } else if ((effects & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3396 final PooledConsumer f = PooledLambda.obtainConsumer(
3397 ActivityRecord::ensureActivityConfiguration,
3398 PooledLambda.__(ActivityRecord.class), 0,
3399 false /* preserveWindow */);
3400 try {
3401 for (int i = haveConfigChanges.size() - 1; i >= 0; --i) {
3402 haveConfigChanges.valueAt(i).forAllActivities(f);
3403 }
3404 } finally {
3405 f.recycle();
3406 }
3407 }
3408 } finally {
3409 continueWindowLayout();
Evan Roskyddedfd42019-10-04 13:38:38 -07003410 }
3411 }
3412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
3415 }
3416
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 @Override
3418 public boolean releaseActivityInstance(IBinder token) {
3419 synchronized (mGlobalLock) {
3420 final long origId = Binder.clearCallingIdentity();
3421 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003422 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3423 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 return false;
3425 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003426 r.destroyImmediately(true /* removeFromApp */, "app-req");
3427 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 } finally {
3429 Binder.restoreCallingIdentity(origId);
3430 }
3431 }
3432 }
3433
3434 @Override
3435 public void releaseSomeActivities(IApplicationThread appInt) {
3436 synchronized (mGlobalLock) {
3437 final long origId = Binder.clearCallingIdentity();
3438 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003439 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003440 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003441 } finally {
3442 Binder.restoreCallingIdentity(origId);
3443 }
3444 }
3445 }
3446
3447 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003448 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003449 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 != PackageManager.PERMISSION_GRANTED) {
3451 throw new SecurityException("Requires permission "
3452 + android.Manifest.permission.DEVICE_POWER);
3453 }
3454
3455 synchronized (mGlobalLock) {
3456 long ident = Binder.clearCallingIdentity();
3457 if (mKeyguardShown != keyguardShowing) {
3458 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003459 final Message msg = PooledLambda.obtainMessage(
3460 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3461 keyguardShowing);
3462 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 }
3464 try {
wilsonshih177261f2019-02-22 12:02:18 +08003465 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 } finally {
3467 Binder.restoreCallingIdentity(ident);
3468 }
3469 }
3470
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003471 mH.post(() -> {
3472 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3473 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3474 }
3475 });
3476 }
3477
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003478 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003479 mH.post(() -> {
3480 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3481 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3482 }
3483 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
3486 @Override
3487 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003488 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3489 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490
3491 final File passedIconFile = new File(filePath);
3492 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3493 passedIconFile.getName());
3494 if (!legitIconFile.getPath().equals(filePath)
3495 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3496 throw new IllegalArgumentException("Bad file path: " + filePath
3497 + " passed for userId " + userId);
3498 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003499 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003500 }
3501
3502 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003504 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 synchronized (mGlobalLock) {
3506 final long ident = Binder.clearCallingIdentity();
3507 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003508 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 if (stack == null) {
3510 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3511 return;
3512 }
3513 if (!stack.isActivityTypeStandardOrUndefined()) {
3514 throw new IllegalArgumentException(
3515 "Removing non-standard stack is not allowed.");
3516 }
3517 mStackSupervisor.removeStack(stack);
3518 } finally {
3519 Binder.restoreCallingIdentity(ident);
3520 }
3521 }
3522 }
3523
3524 @Override
3525 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527
3528 synchronized (mGlobalLock) {
3529 final long ident = Binder.clearCallingIdentity();
3530 try {
3531 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3532 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003533 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003534 } finally {
3535 Binder.restoreCallingIdentity(ident);
3536 }
3537 }
3538 }
3539
3540 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003541 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 synchronized (mGlobalLock) {
3543 long ident = Binder.clearCallingIdentity();
3544 try {
3545 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3546 if (r == null) {
3547 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003548 "toggleFreeformWindowingMode: No activity record matching token="
3549 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 }
3551
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003552 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003553 if (stack == null) {
3554 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3555 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 }
3557
Yunfan Chend967af82019-01-17 18:30:18 +09003558 if (!stack.inFreeformWindowingMode()
3559 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3560 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3561 + "toggle between fullscreen and freeform.");
3562 }
3563
3564 if (stack.inFreeformWindowingMode()) {
3565 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003566 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003567 throw new IllegalStateException("Size-compat windows are currently not"
3568 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003569 } else if (stack.getParent().inFreeformWindowingMode()) {
3570 // If the window is on a freeform display, set it to undefined. It will be
3571 // resolved to freeform and it can adjust windowing mode when the display mode
3572 // changes in runtime.
3573 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003574 } else {
3575 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3576 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577 } finally {
3578 Binder.restoreCallingIdentity(ident);
3579 }
3580 }
3581 }
3582
3583 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3584 @Override
3585 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003586 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003587 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003588 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589 }
3590
3591 /** Unregister a task stack listener so that it stops receiving callbacks. */
3592 @Override
3593 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003594 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003596 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003597 }
3598
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 @Override
3600 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3601 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3602 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3603 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3604 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3605 }
3606
3607 @Override
3608 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3609 IBinder activityToken, int flags) {
3610 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3611 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3612 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3613 }
3614
3615 @Override
3616 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3617 Bundle args) {
3618 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3619 true /* focused */, true /* newSessionId */, userHandle, args,
3620 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3621 }
3622
3623 @Override
3624 public Bundle getAssistContextExtras(int requestType) {
3625 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3626 null, null, true /* focused */, true /* newSessionId */,
3627 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3628 if (pae == null) {
3629 return null;
3630 }
3631 synchronized (pae) {
3632 while (!pae.haveResult) {
3633 try {
3634 pae.wait();
3635 } catch (InterruptedException e) {
3636 }
3637 }
3638 }
3639 synchronized (mGlobalLock) {
3640 buildAssistBundleLocked(pae, pae.result);
3641 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003642 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 }
3644 return pae.extras;
3645 }
3646
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003647 /**
3648 * Binder IPC calls go through the public entry point.
3649 * This can be called with or without the global lock held.
3650 */
3651 private static int checkCallingPermission(String permission) {
3652 return checkPermission(
3653 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3654 }
3655
3656 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003657 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003658 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3659 mAmInternal.enforceCallingPermission(permission, func);
3660 }
3661 }
3662
3663 @VisibleForTesting
3664 int checkGetTasksPermission(String permission, int pid, int uid) {
3665 return checkPermission(permission, pid, uid);
3666 }
3667
3668 static int checkPermission(String permission, int pid, int uid) {
3669 if (permission == null) {
3670 return PackageManager.PERMISSION_DENIED;
3671 }
3672 return checkComponentPermission(permission, pid, uid, -1, true);
3673 }
3674
Wale Ogunwale214f3482018-10-04 11:00:47 -07003675 public static int checkComponentPermission(String permission, int pid, int uid,
3676 int owningUid, boolean exported) {
3677 return ActivityManagerService.checkComponentPermission(
3678 permission, pid, uid, owningUid, exported);
3679 }
3680
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003681 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3682 if (getRecentTasks().isCallerRecents(callingUid)) {
3683 // Always allow the recents component to get tasks
3684 return true;
3685 }
3686
3687 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3688 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3689 if (!allowed) {
3690 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3691 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3692 // Temporary compatibility: some existing apps on the system image may
3693 // still be requesting the old permission and not switched to the new
3694 // one; if so, we'll still allow them full access. This means we need
3695 // to see if they are holding the old permission and are a system app.
3696 try {
3697 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3698 allowed = true;
3699 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3700 + " is using old GET_TASKS but privileged; allowing");
3701 }
3702 } catch (RemoteException e) {
3703 }
3704 }
3705 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3706 + " does not hold REAL_GET_TASKS; limiting output");
3707 }
3708 return allowed;
3709 }
3710
Nicholas Sauer0259e532019-08-30 08:24:55 -07003711 boolean isCrossUserAllowed(int pid, int uid) {
3712 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3713 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3714 }
3715
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3717 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3718 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3719 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003720 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 "enqueueAssistContext()");
3722
3723 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003724 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003725 if (activity == null) {
3726 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3727 return null;
3728 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003729 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3731 return null;
3732 }
3733 if (focused) {
3734 if (activityToken != null) {
3735 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3736 if (activity != caller) {
3737 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3738 + " is not current top " + activity);
3739 return null;
3740 }
3741 }
3742 } else {
3743 activity = ActivityRecord.forTokenLocked(activityToken);
3744 if (activity == null) {
3745 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3746 + " couldn't be found");
3747 return null;
3748 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003749 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003750 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3751 return null;
3752 }
3753 }
3754
3755 PendingAssistExtras pae;
3756 Bundle extras = new Bundle();
3757 if (args != null) {
3758 extras.putAll(args);
3759 }
3760 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003761 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762
3763 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3764 userHandle);
3765 pae.isHome = activity.isActivityTypeHome();
3766
3767 // Increment the sessionId if necessary
3768 if (newSessionId) {
3769 mViSessionId++;
3770 }
3771 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003772 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3773 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003774 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003775 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776 } catch (RemoteException e) {
3777 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3778 return null;
3779 }
3780 return pae;
3781 }
3782 }
3783
3784 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3785 if (result != null) {
3786 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3787 }
3788 if (pae.hint != null) {
3789 pae.extras.putBoolean(pae.hint, true);
3790 }
3791 }
3792
3793 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3794 IAssistDataReceiver receiver;
3795 synchronized (mGlobalLock) {
3796 mPendingAssistExtras.remove(pae);
3797 receiver = pae.receiver;
3798 }
3799 if (receiver != null) {
3800 // Caller wants result sent back to them.
3801 Bundle sendBundle = new Bundle();
3802 // At least return the receiver extras
3803 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3804 try {
3805 pae.receiver.onHandleAssistData(sendBundle);
3806 } catch (RemoteException e) {
3807 }
3808 }
3809 }
3810
3811 public class PendingAssistExtras extends Binder implements Runnable {
3812 public final ActivityRecord activity;
3813 public boolean isHome;
3814 public final Bundle extras;
3815 public final Intent intent;
3816 public final String hint;
3817 public final IAssistDataReceiver receiver;
3818 public final int userHandle;
3819 public boolean haveResult = false;
3820 public Bundle result = null;
3821 public AssistStructure structure = null;
3822 public AssistContent content = null;
3823 public Bundle receiverExtras;
3824
3825 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3826 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3827 int _userHandle) {
3828 activity = _activity;
3829 extras = _extras;
3830 intent = _intent;
3831 hint = _hint;
3832 receiver = _receiver;
3833 receiverExtras = _receiverExtras;
3834 userHandle = _userHandle;
3835 }
3836
3837 @Override
3838 public void run() {
3839 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3840 synchronized (this) {
3841 haveResult = true;
3842 notifyAll();
3843 }
3844 pendingAssistExtrasTimedOut(this);
3845 }
3846 }
3847
3848 @Override
3849 public boolean isAssistDataAllowedOnCurrentActivity() {
3850 int userId;
3851 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003852 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3854 return false;
3855 }
3856
Wale Ogunwale21e06482019-11-18 05:14:15 -08003857 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 if (activity == null) {
3859 return false;
3860 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003861 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 }
3863 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3864 }
3865
3866 @Override
3867 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3868 long ident = Binder.clearCallingIdentity();
3869 try {
3870 synchronized (mGlobalLock) {
3871 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003872 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003873 if (top != caller) {
3874 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3875 + " is not current top " + top);
3876 return false;
3877 }
3878 if (!top.nowVisible) {
3879 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3880 + " is not visible");
3881 return false;
3882 }
3883 }
3884 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3885 token);
3886 } finally {
3887 Binder.restoreCallingIdentity(ident);
3888 }
3889 }
3890
3891 @Override
3892 public boolean isRootVoiceInteraction(IBinder token) {
3893 synchronized (mGlobalLock) {
3894 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3895 if (r == null) {
3896 return false;
3897 }
3898 return r.rootVoiceInteraction;
3899 }
3900 }
3901
Wale Ogunwalef6733932018-06-27 05:14:34 -07003902 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3903 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3904 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3905 if (activityToCallback == null) return;
3906 activityToCallback.setVoiceSessionLocked(voiceSession);
3907
3908 // Inform the activity
3909 try {
3910 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3911 voiceInteractor);
3912 long token = Binder.clearCallingIdentity();
3913 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003914 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003915 } finally {
3916 Binder.restoreCallingIdentity(token);
3917 }
3918 // TODO: VI Should we cache the activity so that it's easier to find later
3919 // rather than scan through all the stacks and activities?
3920 } catch (RemoteException re) {
3921 activityToCallback.clearVoiceSessionLocked();
3922 // TODO: VI Should this terminate the voice session?
3923 }
3924 }
3925
3926 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3927 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3928 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3929 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3930 boolean wasRunningVoice = mRunningVoice != null;
3931 mRunningVoice = session;
3932 if (!wasRunningVoice) {
3933 mVoiceWakeLock.acquire();
3934 updateSleepIfNeededLocked();
3935 }
3936 }
3937 }
3938
3939 void finishRunningVoiceLocked() {
3940 if (mRunningVoice != null) {
3941 mRunningVoice = null;
3942 mVoiceWakeLock.release();
3943 updateSleepIfNeededLocked();
3944 }
3945 }
3946
3947 @Override
3948 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3949 synchronized (mGlobalLock) {
3950 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3951 if (keepAwake) {
3952 mVoiceWakeLock.acquire();
3953 } else {
3954 mVoiceWakeLock.release();
3955 }
3956 }
3957 }
3958 }
3959
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 @Override
3961 public ComponentName getActivityClassForToken(IBinder token) {
3962 synchronized (mGlobalLock) {
3963 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3964 if (r == null) {
3965 return null;
3966 }
3967 return r.intent.getComponent();
3968 }
3969 }
3970
3971 @Override
3972 public String getPackageForToken(IBinder token) {
3973 synchronized (mGlobalLock) {
3974 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3975 if (r == null) {
3976 return null;
3977 }
3978 return r.packageName;
3979 }
3980 }
3981
3982 @Override
3983 public void showLockTaskEscapeMessage(IBinder token) {
3984 synchronized (mGlobalLock) {
3985 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3986 if (r == null) {
3987 return;
3988 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003989 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 }
3991 }
3992
3993 @Override
3994 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 final long token = Binder.clearCallingIdentity();
3997 try {
3998 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003999 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 }
4001 } finally {
4002 Binder.restoreCallingIdentity(token);
4003 }
4004 }
4005
4006 /**
4007 * Try to place task to provided position. The final position might be different depending on
4008 * current user and stacks state. The task will be moved to target stack if it's currently in
4009 * different stack.
4010 */
4011 @Override
4012 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004013 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 synchronized (mGlobalLock) {
4015 long ident = Binder.clearCallingIdentity();
4016 try {
4017 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
4018 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08004019 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 if (task == null) {
4021 throw new IllegalArgumentException("positionTaskInStack: no task for id="
4022 + taskId);
4023 }
4024
Louis Chang149d5c82019-12-30 09:47:39 +08004025 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026
4027 if (stack == null) {
4028 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
4029 + stackId);
4030 }
4031 if (!stack.isActivityTypeStandardOrUndefined()) {
4032 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
4033 + " the position of task " + taskId + " in/to non-standard stack");
4034 }
4035
4036 // TODO: Have the callers of this API call a separate reparent method if that is
4037 // what they intended to do vs. having this method also do reparenting.
4038 if (task.getStack() == stack) {
4039 // Change position in current stack.
4040 stack.positionChildAt(task, position);
4041 } else {
4042 // Reparent to new stack.
4043 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4044 !DEFER_RESUME, "positionTaskInStack");
4045 }
4046 } finally {
4047 Binder.restoreCallingIdentity(ident);
4048 }
4049 }
4050 }
4051
4052 @Override
4053 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4054 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4055 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004056 + Arrays.toString(horizontalSizeConfiguration) + " "
4057 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 synchronized (mGlobalLock) {
4059 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4060 if (record == null) {
4061 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4062 + "found for: " + token);
4063 }
4064 record.setSizeConfigurations(horizontalSizeConfiguration,
4065 verticalSizeConfigurations, smallestSizeConfigurations);
4066 }
4067 }
4068
4069 /**
4070 * Dismisses split-screen multi-window mode.
4071 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4072 */
4073 @Override
4074 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004075 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4077 final long ident = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004081 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 if (stack == null) {
4083 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4084 return;
4085 }
4086
4087 if (toTop) {
4088 // Caller wants the current split-screen primary stack to be the top stack after
4089 // it goes fullscreen, so move it to the front.
4090 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004091 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004093 // stack after it goes fullscreen, so we move the focus to the top-most
4094 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4096 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4097 if (otherStack != null) {
4098 otherStack.moveToFront("dismissSplitScreenMode_other");
4099 }
4100 }
4101
Evan Rosky10475742018-09-05 19:02:48 -07004102 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 }
4104 } finally {
4105 Binder.restoreCallingIdentity(ident);
4106 }
4107 }
4108
4109 /**
4110 * Dismisses Pip
4111 * @param animate True if the dismissal should be animated.
4112 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4113 * default animation duration should be used.
4114 */
4115 @Override
4116 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 final long ident = Binder.clearCallingIdentity();
4119 try {
4120 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004121 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004122 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 if (stack == null) {
4124 Slog.w(TAG, "dismissPip: pinned stack not found.");
4125 return;
4126 }
4127 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4128 throw new IllegalArgumentException("Stack: " + stack
4129 + " doesn't support animated resize.");
4130 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004131 /**
4132 * TODO(b/146594635): Remove all PIP animation code from WM
4133 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4134 */
4135 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004136 stack.animateResizePinnedStack(null /* destBounds */,
4137 null /* sourceHintBounds */, animationDuration,
4138 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004140 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 }
4142 }
4143 } finally {
4144 Binder.restoreCallingIdentity(ident);
4145 }
4146 }
4147
4148 @Override
4149 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 synchronized (mGlobalLock) {
4152 mSuppressResizeConfigChanges = suppress;
4153 }
4154 }
4155
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 @Override
4157 // TODO: API should just be about changing windowing modes...
4158 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 "moveTasksToFullscreenStack()");
4161 synchronized (mGlobalLock) {
4162 final long origId = Binder.clearCallingIdentity();
4163 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004164 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 if (stack != null){
4166 if (!stack.isActivityTypeStandardOrUndefined()) {
4167 throw new IllegalArgumentException(
4168 "You can't move tasks from non-standard stacks.");
4169 }
4170 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4171 }
4172 } finally {
4173 Binder.restoreCallingIdentity(origId);
4174 }
4175 }
4176 }
4177
4178 /**
4179 * Moves the top activity in the input stackId to the pinned stack.
4180 *
4181 * @param stackId Id of stack to move the top activity to pinned stack.
4182 * @param bounds Bounds to use for pinned stack.
4183 *
4184 * @return True if the top activity of the input stack was successfully moved to the pinned
4185 * stack.
4186 */
4187 @Override
4188 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004189 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004190 "moveTopActivityToPinnedStack()");
4191 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4194 + "Device doesn't support picture-in-picture mode");
4195 }
4196
4197 long ident = Binder.clearCallingIdentity();
4198 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004199 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 } finally {
4201 Binder.restoreCallingIdentity(ident);
4202 }
4203 }
4204 }
4205
4206 @Override
4207 public boolean isInMultiWindowMode(IBinder token) {
4208 final long origId = Binder.clearCallingIdentity();
4209 try {
4210 synchronized (mGlobalLock) {
4211 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4212 if (r == null) {
4213 return false;
4214 }
4215 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4216 return r.inMultiWindowMode();
4217 }
4218 } finally {
4219 Binder.restoreCallingIdentity(origId);
4220 }
4221 }
4222
4223 @Override
4224 public boolean isInPictureInPictureMode(IBinder token) {
4225 final long origId = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
4228 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4229 }
4230 } finally {
4231 Binder.restoreCallingIdentity(origId);
4232 }
4233 }
4234
4235 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004236 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4237 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 return false;
4239 }
4240
4241 // If we are animating to fullscreen then we have already dispatched the PIP mode
4242 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004243 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004244 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 }
4246
4247 @Override
4248 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4249 final long origId = Binder.clearCallingIdentity();
4250 try {
4251 synchronized (mGlobalLock) {
4252 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4253 "enterPictureInPictureMode", token, params);
4254
4255 // If the activity is already in picture in picture mode, then just return early
4256 if (isInPictureInPictureMode(r)) {
4257 return true;
4258 }
4259
4260 // Activity supports picture-in-picture, now check that we can enter PiP at this
4261 // point, if it is
4262 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4263 false /* beforeStopping */)) {
4264 return false;
4265 }
4266
4267 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004268 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004269 if (r.getParent() == null) {
4270 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4271 return;
4272 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004273 // Only update the saved args from the args that are set
4274 r.pictureInPictureArgs.copyOnlySet(params);
4275 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4276 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4277 // Adjust the source bounds by the insets for the transition down
4278 final Rect sourceBounds = new Rect(
4279 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004280 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004281 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004282 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004283 stack.setPictureInPictureAspectRatio(aspectRatio);
4284 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004285 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4286 r.info.applicationInfo.uid, r.shortComponentName,
4287 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004288 logPictureInPictureArgs(params);
4289 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290 };
4291
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004292 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 // If the keyguard is showing or occluded, then try and dismiss it before
4294 // entering picture-in-picture (this will prompt the user to authenticate if the
4295 // device is currently locked).
4296 dismissKeyguard(token, new KeyguardDismissCallback() {
4297 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 public void onDismissSucceeded() {
4299 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 }
4301 }, null /* message */);
4302 } else {
4303 // Enter picture in picture immediately otherwise
4304 enterPipRunnable.run();
4305 }
4306 return true;
4307 }
4308 } finally {
4309 Binder.restoreCallingIdentity(origId);
4310 }
4311 }
4312
4313 @Override
4314 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4315 final long origId = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4319 "setPictureInPictureParams", token, params);
4320
4321 // Only update the saved args from the args that are set
4322 r.pictureInPictureArgs.copyOnlySet(params);
4323 if (r.inPinnedWindowingMode()) {
4324 // If the activity is already in picture-in-picture, update the pinned stack now
4325 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4326 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004327 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 if (!stack.isAnimatingBoundsToFullscreen()) {
4329 stack.setPictureInPictureAspectRatio(
4330 r.pictureInPictureArgs.getAspectRatio());
4331 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4332 }
4333 }
4334 logPictureInPictureArgs(params);
4335 }
4336 } finally {
4337 Binder.restoreCallingIdentity(origId);
4338 }
4339 }
4340
4341 @Override
4342 public int getMaxNumPictureInPictureActions(IBinder token) {
4343 // Currently, this is a static constant, but later, we may change this to be dependent on
4344 // the context of the activity
4345 return 3;
4346 }
4347
4348 private void logPictureInPictureArgs(PictureInPictureParams params) {
4349 if (params.hasSetActions()) {
4350 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4351 params.getActions().size());
4352 }
4353 if (params.hasSetAspectRatio()) {
4354 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4355 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4356 MetricsLogger.action(lm);
4357 }
4358 }
4359
4360 /**
4361 * Checks the state of the system and the activity associated with the given {@param token} to
4362 * verify that picture-in-picture is supported for that activity.
4363 *
4364 * @return the activity record for the given {@param token} if all the checks pass.
4365 */
4366 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4367 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 throw new IllegalStateException(caller
4370 + ": Device doesn't support picture-in-picture mode.");
4371 }
4372
4373 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4374 if (r == null) {
4375 throw new IllegalStateException(caller
4376 + ": Can't find activity for token=" + token);
4377 }
4378
4379 if (!r.supportsPictureInPicture()) {
4380 throw new IllegalStateException(caller
4381 + ": Current activity does not support picture-in-picture.");
4382 }
4383
4384 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004385 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004386 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 final float minAspectRatio = mContext.getResources().getFloat(
4388 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4389 final float maxAspectRatio = mContext.getResources().getFloat(
4390 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4391 throw new IllegalArgumentException(String.format(caller
4392 + ": Aspect ratio is too extreme (must be between %f and %f).",
4393 minAspectRatio, maxAspectRatio));
4394 }
4395
4396 // Truncate the number of actions if necessary
4397 params.truncateActions(getMaxNumPictureInPictureActions(token));
4398
4399 return r;
4400 }
4401
4402 @Override
4403 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004404 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004405 synchronized (mGlobalLock) {
4406 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4407 if (r == null) {
4408 throw new IllegalArgumentException("Activity does not exist; token="
4409 + activityToken);
4410 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004411 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 }
4413 }
4414
4415 @Override
4416 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4417 Rect tempDockedTaskInsetBounds,
4418 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 long ident = Binder.clearCallingIdentity();
4421 try {
4422 synchronized (mGlobalLock) {
4423 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4424 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4425 PRESERVE_WINDOWS);
4426 }
4427 } finally {
4428 Binder.restoreCallingIdentity(ident);
4429 }
4430 }
4431
4432 @Override
4433 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 final long ident = Binder.clearCallingIdentity();
4436 try {
4437 synchronized (mGlobalLock) {
4438 mStackSupervisor.setSplitScreenResizing(resizing);
4439 }
4440 } finally {
4441 Binder.restoreCallingIdentity(ident);
4442 }
4443 }
4444
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 /**
4446 * Check that we have the features required for VR-related API calls, and throw an exception if
4447 * not.
4448 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004449 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 if (!mContext.getPackageManager().hasSystemFeature(
4451 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4452 throw new UnsupportedOperationException("VR mode not supported on this device!");
4453 }
4454 }
4455
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 @Override
4457 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459
4460 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4461
4462 ActivityRecord r;
4463 synchronized (mGlobalLock) {
4464 r = ActivityRecord.isInStackLocked(token);
4465 }
4466
4467 if (r == null) {
4468 throw new IllegalArgumentException();
4469 }
4470
4471 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004472 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 VrManagerInternal.NO_ERROR) {
4474 return err;
4475 }
4476
4477 // Clear the binder calling uid since this path may call moveToTask().
4478 final long callingId = Binder.clearCallingIdentity();
4479 try {
4480 synchronized (mGlobalLock) {
4481 r.requestedVrComponent = (enabled) ? packageName : null;
4482
4483 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004484 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 return 0;
4488 }
4489 } finally {
4490 Binder.restoreCallingIdentity(callingId);
4491 }
4492 }
4493
4494 @Override
4495 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4496 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4497 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004498 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4500 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4501 }
Louis Changcdec0802019-11-11 11:45:07 +08004502 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 || activity.voiceSession != null) {
4504 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4505 return;
4506 }
4507 if (activity.pendingVoiceInteractionStart) {
4508 Slog.w(TAG, "Pending start of voice interaction already.");
4509 return;
4510 }
4511 activity.pendingVoiceInteractionStart = true;
4512 }
4513 LocalServices.getService(VoiceInteractionManagerInternal.class)
4514 .startLocalVoiceInteraction(callingActivity, options);
4515 }
4516
4517 @Override
4518 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4519 LocalServices.getService(VoiceInteractionManagerInternal.class)
4520 .stopLocalVoiceInteraction(callingActivity);
4521 }
4522
4523 @Override
4524 public boolean supportsLocalVoiceInteraction() {
4525 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4526 .supportsLocalVoiceInteraction();
4527 }
4528
4529 /** Notifies all listeners when the pinned stack animation starts. */
4530 @Override
4531 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004532 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004533 }
4534
4535 /** Notifies all listeners when the pinned stack animation ends. */
4536 @Override
4537 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004538 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004539 }
4540
4541 @Override
4542 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004543 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 final long ident = Binder.clearCallingIdentity();
4545 try {
4546 synchronized (mGlobalLock) {
4547 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4548 }
4549 } finally {
4550 Binder.restoreCallingIdentity(ident);
4551 }
4552 }
4553
4554 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004555 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557
4558 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004559 if (mWindowManager == null) {
4560 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4561 return false;
4562 }
4563
4564 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004566 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568
Riddle Hsua0022cd2019-09-09 21:12:41 +08004569 mH.sendMessage(PooledLambda.obtainMessage(
4570 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4571 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572
4573 final long origId = Binder.clearCallingIdentity();
4574 try {
4575 if (values != null) {
4576 Settings.System.clearConfiguration(values);
4577 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004578 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 UserHandle.USER_NULL, false /* deferResume */,
4580 mTmpUpdateConfigurationResult);
4581 return mTmpUpdateConfigurationResult.changes != 0;
4582 } finally {
4583 Binder.restoreCallingIdentity(origId);
4584 }
4585 }
4586 }
4587
4588 @Override
4589 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4590 CharSequence message) {
4591 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004592 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004593 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4594 }
4595 final long callingId = Binder.clearCallingIdentity();
4596 try {
4597 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004598 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004599 }
4600 } finally {
4601 Binder.restoreCallingIdentity(callingId);
4602 }
4603 }
4604
4605 @Override
4606 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004607 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 "cancelTaskWindowTransition()");
4609 final long ident = Binder.clearCallingIdentity();
4610 try {
4611 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004612 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 MATCH_TASK_IN_STACKS_ONLY);
4614 if (task == null) {
4615 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4616 return;
4617 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004618 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004619 }
4620 } finally {
4621 Binder.restoreCallingIdentity(ident);
4622 }
4623 }
4624
4625 @Override
4626 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 final long ident = Binder.clearCallingIdentity();
4629 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004630 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 } finally {
4632 Binder.restoreCallingIdentity(ident);
4633 }
4634 }
4635
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004636 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4637 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004638 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004639 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004640 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004641 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4642 if (task == null) {
4643 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4644 return null;
4645 }
4646 }
4647 // Don't call this while holding the lock as this operation might hit the disk.
4648 return task.getSnapshot(reducedResolution, restoreFromDisk);
4649 }
4650
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004651 @Override
4652 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4653 synchronized (mGlobalLock) {
4654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4655 if (r == null) {
4656 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4657 + token);
4658 return;
4659 }
4660 final long origId = Binder.clearCallingIdentity();
4661 try {
4662 r.setDisablePreviewScreenshots(disable);
4663 } finally {
4664 Binder.restoreCallingIdentity(origId);
4665 }
4666 }
4667 }
4668
Riddle Hsu440f88b2019-11-06 22:17:35 +08004669 @Override
4670 public void invalidateHomeTaskSnapshot(IBinder token) {
4671 synchronized (mGlobalLock) {
4672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4673 if (r == null || !r.isActivityTypeHome()) {
4674 return;
4675 }
4676 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4677 }
4678 }
4679
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004680 /** Return the user id of the last resumed activity. */
4681 @Override
4682 public @UserIdInt
4683 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004684 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004685 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4686 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004687 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004688 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004690 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004691 }
4692 }
4693
4694 @Override
4695 public void updateLockTaskFeatures(int userId, int flags) {
4696 final int callingUid = Binder.getCallingUid();
4697 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004698 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004699 "updateLockTaskFeatures()");
4700 }
4701 synchronized (mGlobalLock) {
4702 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4703 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004704 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004705 }
4706 }
4707
4708 @Override
4709 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4710 synchronized (mGlobalLock) {
4711 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4712 if (r == null) {
4713 return;
4714 }
4715 final long origId = Binder.clearCallingIdentity();
4716 try {
4717 r.setShowWhenLocked(showWhenLocked);
4718 } finally {
4719 Binder.restoreCallingIdentity(origId);
4720 }
4721 }
4722 }
4723
4724 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004725 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4726 synchronized (mGlobalLock) {
4727 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4728 if (r == null) {
4729 return;
4730 }
4731 final long origId = Binder.clearCallingIdentity();
4732 try {
4733 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4734 } finally {
4735 Binder.restoreCallingIdentity(origId);
4736 }
4737 }
4738 }
4739
4740 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004741 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4742 synchronized (mGlobalLock) {
4743 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4744 if (r == null) {
4745 return;
4746 }
4747 final long origId = Binder.clearCallingIdentity();
4748 try {
4749 r.setTurnScreenOn(turnScreenOn);
4750 } finally {
4751 Binder.restoreCallingIdentity(origId);
4752 }
4753 }
4754 }
4755
4756 @Override
4757 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004758 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004759 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004760 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004761 synchronized (mGlobalLock) {
4762 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4763 if (r == null) {
4764 return;
4765 }
4766 final long origId = Binder.clearCallingIdentity();
4767 try {
4768 r.registerRemoteAnimations(definition);
4769 } finally {
4770 Binder.restoreCallingIdentity(origId);
4771 }
4772 }
4773 }
4774
4775 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004776 public void unregisterRemoteAnimations(IBinder token) {
4777 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4778 "unregisterRemoteAnimations");
4779 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.unregisterRemoteAnimations();
4787 } finally {
4788 Binder.restoreCallingIdentity(origId);
4789 }
4790 }
4791 }
4792
4793 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004794 public void registerRemoteAnimationForNextActivityStart(String packageName,
4795 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004796 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004797 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004798 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004799 synchronized (mGlobalLock) {
4800 final long origId = Binder.clearCallingIdentity();
4801 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004802 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004803 packageName, adapter);
4804 } finally {
4805 Binder.restoreCallingIdentity(origId);
4806 }
4807 }
4808 }
4809
Evan Rosky966759f2019-01-15 10:33:58 -08004810 @Override
4811 public void registerRemoteAnimationsForDisplay(int displayId,
4812 RemoteAnimationDefinition definition) {
4813 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4814 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004815 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004816 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004817 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004818 if (display == null) {
4819 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4820 return;
4821 }
4822 final long origId = Binder.clearCallingIdentity();
4823 try {
4824 display.mDisplayContent.registerRemoteAnimations(definition);
4825 } finally {
4826 Binder.restoreCallingIdentity(origId);
4827 }
4828 }
4829 }
4830
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004831 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4832 @Override
4833 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4834 synchronized (mGlobalLock) {
4835 final long origId = Binder.clearCallingIdentity();
4836 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004837 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004838 } finally {
4839 Binder.restoreCallingIdentity(origId);
4840 }
4841 }
4842 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004843
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004844 @Override
4845 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004846 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004847 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004848 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004849 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004850 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004851 }
4852 }
4853
4854 @Override
4855 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004856 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004857 != PERMISSION_GRANTED) {
4858 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4859 + Binder.getCallingPid()
4860 + ", uid=" + Binder.getCallingUid()
4861 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4862 Slog.w(TAG, msg);
4863 throw new SecurityException(msg);
4864 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004865 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004866 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004867 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004868 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004869 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004870 }
4871 }
4872
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004873 @Override
4874 public void stopAppSwitches() {
4875 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4876 synchronized (mGlobalLock) {
4877 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004878 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004879 mDidAppSwitch = false;
4880 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4881 }
4882 }
4883
4884 @Override
4885 public void resumeAppSwitches() {
4886 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4887 synchronized (mGlobalLock) {
4888 // Note that we don't execute any pending app switches... we will
4889 // let those wait until either the timeout, or the next start
4890 // activity request.
4891 mAppSwitchesAllowedTime = 0;
4892 }
4893 }
4894
Ricky Wai906af482019-06-03 17:25:28 +01004895 long getLastStopAppSwitchesTime() {
4896 return mLastStopAppSwitchesTime;
4897 }
4898
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004899 void onStartActivitySetDidAppSwitch() {
4900 if (mDidAppSwitch) {
4901 // This is the second allowed switch since we stopped switches, so now just generally
4902 // allow switches. Use case:
4903 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4904 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4905 // anyone to switch again).
4906 mAppSwitchesAllowedTime = 0;
4907 } else {
4908 mDidAppSwitch = true;
4909 }
4910 }
4911
4912 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004913 boolean shouldDisableNonVrUiLocked() {
4914 return mVrController.shouldDisableNonVrUiLocked();
4915 }
4916
Wale Ogunwale53783742018-09-16 10:21:51 -07004917 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004918 // 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 +00004919 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004920 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004921 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4922 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004923 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004924 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004925 }
4926 mH.post(() -> {
4927 if (!mVrController.onVrModeChanged(r)) {
4928 return;
4929 }
4930 synchronized (mGlobalLock) {
4931 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4932 mWindowManager.disableNonVrUi(disableNonVrUi);
4933 if (disableNonVrUi) {
4934 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4935 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004936 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004937 }
4938 }
4939 });
4940 }
4941
Wale Ogunwale53783742018-09-16 10:21:51 -07004942 @Override
4943 public int getPackageScreenCompatMode(String packageName) {
4944 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4945 synchronized (mGlobalLock) {
4946 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4947 }
4948 }
4949
4950 @Override
4951 public void setPackageScreenCompatMode(String packageName, int mode) {
4952 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4953 "setPackageScreenCompatMode");
4954 synchronized (mGlobalLock) {
4955 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4956 }
4957 }
4958
4959 @Override
4960 public boolean getPackageAskScreenCompat(String packageName) {
4961 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4962 synchronized (mGlobalLock) {
4963 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4964 }
4965 }
4966
4967 @Override
4968 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4969 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4970 "setPackageAskScreenCompat");
4971 synchronized (mGlobalLock) {
4972 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4973 }
4974 }
4975
Wale Ogunwale64258362018-10-16 15:13:37 -07004976 public static String relaunchReasonToString(int relaunchReason) {
4977 switch (relaunchReason) {
4978 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4979 return "window_resize";
4980 case RELAUNCH_REASON_FREE_RESIZE:
4981 return "free_resize";
4982 default:
4983 return null;
4984 }
4985 }
4986
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004987 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004988 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989 }
4990
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004991 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004992 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004993 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4994 }
4995
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004996 boolean isKeyguardLocked() {
4997 return mKeyguardController.isKeyguardLocked();
4998 }
4999
Garfield Tan01548632018-11-27 10:15:48 -08005000 /**
5001 * Clears launch params for the given package.
5002 * @param packageNames the names of the packages of which the launch params are to be cleared
5003 */
5004 @Override
5005 public void clearLaunchParamsForPackages(List<String> packageNames) {
5006 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5007 "clearLaunchParamsForPackages");
5008 synchronized (mGlobalLock) {
5009 for (int i = 0; i < packageNames.size(); ++i) {
5010 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
5011 }
5012 }
5013 }
5014
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005015 /**
5016 * Makes the display with the given id a single task instance display. I.e the display can only
5017 * contain one task.
5018 */
5019 @Override
5020 public void setDisplayToSingleTaskInstance(int displayId) {
5021 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5022 "setDisplayToSingleTaskInstance");
5023 final long origId = Binder.clearCallingIdentity();
5024 try {
Louis Chang677921f2019-12-06 16:44:24 +08005025 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08005026 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005027 if (display != null) {
5028 display.setDisplayToSingleTaskInstance();
5029 }
5030 } finally {
5031 Binder.restoreCallingIdentity(origId);
5032 }
5033 }
5034
jorgegil@google.com06bc3232019-10-31 14:51:22 -07005035 /**
5036 * Requests that an activity should enter picture-in-picture mode if possible.
5037 */
5038 @Override
5039 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
5040 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5041 "requestPictureInPictureMode");
5042 final long origId = Binder.clearCallingIdentity();
5043 try {
5044 synchronized (mGlobalLock) {
5045 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5046 if (activity == null) {
5047 return;
5048 }
5049
5050 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5051 "requestPictureInPictureMode", /* beforeStopping */ false);
5052 if (!canEnterPictureInPicture) {
5053 throw new IllegalStateException(
5054 "Requested PIP on an activity that doesn't support it");
5055 }
5056
5057 try {
5058 final ClientTransaction transaction = ClientTransaction.obtain(
5059 activity.app.getThread(),
5060 activity.token);
5061 transaction.addCallback(EnterPipRequestedItem.obtain());
5062 getLifecycleManager().scheduleTransaction(transaction);
5063 } catch (Exception e) {
5064 Slog.w(TAG, "Failed to send enter pip requested item: "
5065 + activity.intent.getComponent(), e);
5066 }
5067 }
5068 } finally {
5069 Binder.restoreCallingIdentity(origId);
5070 }
5071 }
5072
Wale Ogunwale31913b52018-10-13 08:29:31 -07005073 void dumpLastANRLocked(PrintWriter pw) {
5074 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5075 if (mLastANRState == null) {
5076 pw.println(" <no ANR has occurred since boot>");
5077 } else {
5078 pw.println(mLastANRState);
5079 }
5080 }
5081
5082 void dumpLastANRTracesLocked(PrintWriter pw) {
5083 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5084
5085 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5086 if (ArrayUtils.isEmpty(files)) {
5087 pw.println(" <no ANR has occurred since boot>");
5088 return;
5089 }
5090 // Find the latest file.
5091 File latest = null;
5092 for (File f : files) {
5093 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5094 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005095 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005096 }
5097 pw.print("File: ");
5098 pw.print(latest.getName());
5099 pw.println();
5100 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5101 String line;
5102 while ((line = in.readLine()) != null) {
5103 pw.println(line);
5104 }
5105 } catch (IOException e) {
5106 pw.print("Unable to read: ");
5107 pw.print(e);
5108 pw.println();
5109 }
5110 }
5111
5112 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5113 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5114 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5115 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5116 }
5117
5118 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5119 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5120 pw.println(header);
5121
Louis Chang149d5c82019-12-30 09:47:39 +08005122 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005123 dumpPackage);
5124 boolean needSep = printedAnything;
5125
5126 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005127 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005128 " ResumedActivity: ");
5129 if (printed) {
5130 printedAnything = true;
5131 needSep = false;
5132 }
5133
5134 if (dumpPackage == null) {
5135 if (needSep) {
5136 pw.println();
5137 }
5138 printedAnything = true;
5139 mStackSupervisor.dump(pw, " ");
5140 }
5141
5142 if (!printedAnything) {
5143 pw.println(" (nothing)");
5144 }
5145 }
5146
5147 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005148 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005149 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005150 pw.println(" ");
5151 }
5152
5153 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5154 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5155 getActivityStartController().dump(pw, "", dumpPackage);
5156 }
5157
5158 /**
5159 * There are three things that cmd can be:
5160 * - a flattened component name that matches an existing activity
5161 * - the cmd arg isn't the flattened component name of an existing activity:
5162 * dump all activity whose component contains the cmd as a substring
5163 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005164 * <p>
5165 * The caller should not hold lock when calling this method because it will wait for the
5166 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005167 *
5168 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5169 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5170 */
5171 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5172 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5173 ArrayList<ActivityRecord> activities;
5174
5175 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005176 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005177 dumpFocusedStackOnly);
5178 }
5179
5180 if (activities.size() <= 0) {
5181 return false;
5182 }
5183
5184 String[] newArgs = new String[args.length - opti];
5185 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5186
Louis Changcdec0802019-11-11 11:45:07 +08005187 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005188 boolean needSep = false;
5189 for (int i = activities.size() - 1; i >= 0; i--) {
5190 ActivityRecord r = activities.get(i);
5191 if (needSep) {
5192 pw.println();
5193 }
5194 needSep = true;
5195 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005196 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005197 if (lastTask != task) {
5198 lastTask = task;
5199 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005200 pw.print(" id="); pw.print(lastTask.mTaskId);
5201 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005202 if (dumpAll) {
5203 lastTask.dump(pw, " ");
5204 }
5205 }
5206 }
5207 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5208 }
5209 return true;
5210 }
5211
5212 /**
5213 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5214 * there is a thread associated with the activity.
5215 */
5216 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5217 final ActivityRecord r, String[] args, boolean dumpAll) {
5218 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005219 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005220 synchronized (mGlobalLock) {
5221 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5222 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5223 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005224 if (r.hasProcess()) {
5225 pw.println(r.app.getPid());
5226 appThread = r.app.getThread();
5227 } else {
5228 pw.println("(not running)");
5229 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005230 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005231 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005232 }
5233 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005234 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005235 // flush anything that is already in the PrintWriter since the thread is going
5236 // to write to the file descriptor directly
5237 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005238 try (TransferPipe tp = new TransferPipe()) {
5239 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5240 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005241 } catch (IOException e) {
5242 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5243 } catch (RemoteException e) {
5244 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5245 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005246 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005247 }
5248
sanryhuang498e77e2018-12-06 14:57:01 +08005249 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5250 boolean testPssMode) {
5251 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5252 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5253 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005254 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005255 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5256 st.toString());
5257 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005258 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5259 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5260 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005261 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5262 testPssMode);
5263 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005264 }
5265
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 int getCurrentUserId() {
5267 return mAmInternal.getCurrentUserId();
5268 }
5269
5270 private void enforceNotIsolatedCaller(String caller) {
5271 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5272 throw new SecurityException("Isolated process not allowed to call " + caller);
5273 }
5274 }
5275
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276 public Configuration getConfiguration() {
5277 Configuration ci;
5278 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005279 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005280 ci.userSetLocale = false;
5281 }
5282 return ci;
5283 }
5284
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285 /**
5286 * Current global configuration information. Contains general settings for the entire system,
5287 * also corresponds to the merged configuration of the default display.
5288 */
5289 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005290 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005291 // while initializing process record for system, see {@link
5292 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005293 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005294 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295 }
5296
5297 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5298 boolean initLocale) {
5299 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5300 }
5301
5302 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5303 boolean initLocale, boolean deferResume) {
5304 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5305 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5306 UserHandle.USER_NULL, deferResume);
5307 }
5308
Wale Ogunwale59507092018-10-29 09:00:30 -07005309 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005310 final long origId = Binder.clearCallingIdentity();
5311 try {
5312 synchronized (mGlobalLock) {
5313 updateConfigurationLocked(values, null, false, true, userId,
5314 false /* deferResume */);
5315 }
5316 } finally {
5317 Binder.restoreCallingIdentity(origId);
5318 }
5319 }
5320
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005321 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5322 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5323 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5324 deferResume, null /* result */);
5325 }
5326
5327 /**
5328 * Do either or both things: (1) change the current configuration, and (2)
5329 * make sure the given activity is running with the (now) current
5330 * configuration. Returns true if the activity has been left running, or
5331 * false if <var>starting</var> is being destroyed to match the new
5332 * configuration.
5333 *
5334 * @param userId is only used when persistent parameter is set to true to persist configuration
5335 * for that particular user
5336 */
5337 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5338 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5339 ActivityTaskManagerService.UpdateConfigurationResult result) {
5340 int changes = 0;
5341 boolean kept = true;
5342
Riddle Hsua0022cd2019-09-09 21:12:41 +08005343 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344 try {
5345 if (values != null) {
5346 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5347 deferResume);
5348 }
5349
5350 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5351 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005352 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 }
5354
5355 if (result != null) {
5356 result.changes = changes;
5357 result.activityRelaunched = !kept;
5358 }
5359 return kept;
5360 }
5361
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005363 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005365
Louis Chang677921f2019-12-06 16:44:24 +08005366 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005367 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005368
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369 mTempConfig.setTo(getGlobalConfiguration());
5370 final int changes = mTempConfig.updateFrom(values);
5371 if (changes == 0) {
5372 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5373 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5374 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5375 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005376 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005377 return 0;
5378 }
5379
5380 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5381 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005382 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005383 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005384 values.colorMode,
5385 values.densityDpi,
5386 values.fontScale,
5387 values.hardKeyboardHidden,
5388 values.keyboard,
5389 values.keyboardHidden,
5390 values.mcc,
5391 values.mnc,
5392 values.navigation,
5393 values.navigationHidden,
5394 values.orientation,
5395 values.screenHeightDp,
5396 values.screenLayout,
5397 values.screenWidthDp,
5398 values.smallestScreenWidthDp,
5399 values.touchscreen,
5400 values.uiMode);
5401
5402
5403 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5404 final LocaleList locales = values.getLocales();
5405 int bestLocaleIndex = 0;
5406 if (locales.size() > 1) {
5407 if (mSupportedSystemLocales == null) {
5408 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5409 }
5410 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5411 }
5412 SystemProperties.set("persist.sys.locale",
5413 locales.get(bestLocaleIndex).toLanguageTag());
5414 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005415
5416 final Message m = PooledLambda.obtainMessage(
5417 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5418 locales.get(bestLocaleIndex));
5419 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005420 }
5421
Yunfan Chen75157d72018-07-27 14:47:21 +09005422 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005423
5424 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005425 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005426
5427 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5428 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005429 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005430
5431 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005433
5434 AttributeCache ac = AttributeCache.instance();
5435 if (ac != null) {
5436 ac.updateConfiguration(mTempConfig);
5437 }
5438
5439 // Make sure all resources in our process are updated right now, so that anyone who is going
5440 // to retrieve resource values after we return will be sure to get the new ones. This is
5441 // especially important during boot, where the first config change needs to guarantee all
5442 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005443 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005444
5445 // We need another copy of global config because we're scheduling some calls instead of
5446 // running them in place. We need to be sure that object we send will be handled unchanged.
5447 final Configuration configCopy = new Configuration(mTempConfig);
5448 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005449 final Message msg = PooledLambda.obtainMessage(
5450 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5451 this, userId, configCopy);
5452 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005453 }
5454
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005455 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5456 for (int i = pidMap.size() - 1; i >= 0; i--) {
5457 final int pid = pidMap.keyAt(i);
5458 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005459 if (DEBUG_CONFIGURATION) {
5460 Slog.v(TAG_CONFIGURATION, "Update process config of "
5461 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005462 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005463 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005464 }
5465
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005466 final Message msg = PooledLambda.obtainMessage(
5467 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5468 mAmInternal, changes, initLocale);
5469 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005470
5471 // Override configuration of the default display duplicates global config, so we need to
5472 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005473 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005474 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005475
5476 return changes;
5477 }
5478
Riddle Hsua0022cd2019-09-09 21:12:41 +08005479 /** @see WindowSurfacePlacer#deferLayout */
5480 void deferWindowLayout() {
5481 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5482 // Reset the reasons at the first entrance because we only care about the changes in the
5483 // deferred scope.
5484 mLayoutReasons = 0;
5485 }
5486
5487 mWindowManager.mWindowPlacerLocked.deferLayout();
5488 }
5489
5490 /** @see WindowSurfacePlacer#continueLayout */
5491 void continueWindowLayout() {
5492 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5493 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5494 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5495 }
5496 }
5497
5498 /**
5499 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5500 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5501 * defer count is gone.
5502 */
5503 void addWindowLayoutReasons(@LayoutReason int reasons) {
5504 mLayoutReasons |= reasons;
5505 }
5506
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 private void updateEventDispatchingLocked(boolean booted) {
5508 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5509 }
5510
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005511 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5512 final ContentResolver resolver = mContext.getContentResolver();
5513 Settings.System.putConfigurationForUser(resolver, config, userId);
5514 }
5515
5516 private void sendLocaleToMountDaemonMsg(Locale l) {
5517 try {
5518 IBinder service = ServiceManager.getService("mount");
5519 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5520 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5521 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5522 } catch (RemoteException e) {
5523 Log.e(TAG, "Error storing locale for decryption UI", e);
5524 }
5525 }
5526
Alison Cichowlas3e340502018-08-07 17:15:01 -04005527 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5528 mStartActivitySources.remove(permissionToken);
5529 mExpiredStartAsCallerTokens.add(permissionToken);
5530 }
5531
5532 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5533 mExpiredStartAsCallerTokens.remove(permissionToken);
5534 }
5535
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005536 boolean isActivityStartsLoggingEnabled() {
5537 return mAmInternal.isActivityStartsLoggingEnabled();
5538 }
5539
Michal Karpinski8596ded2018-11-14 14:43:48 +00005540 boolean isBackgroundActivityStartsEnabled() {
5541 return mAmInternal.isBackgroundActivityStartsEnabled();
5542 }
5543
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005545 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 mWindowManager.enableScreenAfterBoot();
5547
5548 synchronized (mGlobalLock) {
5549 updateEventDispatchingLocked(booted);
5550 }
5551 }
5552
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005553 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5554 if (r == null || !r.hasProcess()) {
5555 return KEY_DISPATCHING_TIMEOUT_MS;
5556 }
5557 return getInputDispatchingTimeoutLocked(r.app);
5558 }
5559
5560 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005561 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005562 }
5563
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 /**
5565 * Decide based on the configuration whether we should show the ANR,
5566 * crash, etc dialogs. The idea is that if there is no affordance to
5567 * press the on-screen buttons, or the user experience would be more
5568 * greatly impacted than the crash itself, we shouldn't show the dialog.
5569 *
5570 * A thought: SystemUI might also want to get told about this, the Power
5571 * dialog / global actions also might want different behaviors.
5572 */
5573 private void updateShouldShowDialogsLocked(Configuration config) {
5574 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5575 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5576 && config.navigation == Configuration.NAVIGATION_NONAV);
5577 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5578 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5579 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5580 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5581 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5582 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5583 HIDE_ERROR_DIALOGS, 0) != 0;
5584 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5585 }
5586
5587 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5588 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5589 FONT_SCALE, 1.0f, userId);
5590
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005591 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 if (getGlobalConfiguration().fontScale == scaleFactor) {
5593 return;
5594 }
5595
5596 final Configuration configuration
5597 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5598 configuration.fontScale = scaleFactor;
5599 updatePersistentConfiguration(configuration, userId);
5600 }
5601 }
5602
5603 // Actually is sleeping or shutting down or whatever else in the future
5604 // is an inactive state.
5605 boolean isSleepingOrShuttingDownLocked() {
5606 return isSleepingLocked() || mShuttingDown;
5607 }
5608
5609 boolean isSleepingLocked() {
5610 return mSleeping;
5611 }
5612
Riddle Hsu16567132018-08-16 21:37:47 +08005613 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005614 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005615 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005616 if (task.isActivityTypeStandard()) {
5617 if (mCurAppTimeTracker != r.appTimeTracker) {
5618 // We are switching app tracking. Complete the current one.
5619 if (mCurAppTimeTracker != null) {
5620 mCurAppTimeTracker.stop();
5621 mH.obtainMessage(
5622 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005623 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624 mCurAppTimeTracker = null;
5625 }
5626 if (r.appTimeTracker != null) {
5627 mCurAppTimeTracker = r.appTimeTracker;
5628 startTimeTrackingFocusedActivityLocked();
5629 }
5630 } else {
5631 startTimeTrackingFocusedActivityLocked();
5632 }
5633 } else {
5634 r.appTimeTracker = null;
5635 }
5636 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5637 // TODO: Probably not, because we don't want to resume voice on switching
5638 // back to this activity
5639 if (task.voiceInteractor != null) {
5640 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5641 } else {
5642 finishRunningVoiceLocked();
5643
5644 if (mLastResumedActivity != null) {
5645 final IVoiceInteractionSession session;
5646
Louis Changcdec0802019-11-11 11:45:07 +08005647 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005648 if (lastResumedActivityTask != null
5649 && lastResumedActivityTask.voiceSession != null) {
5650 session = lastResumedActivityTask.voiceSession;
5651 } else {
5652 session = mLastResumedActivity.voiceSession;
5653 }
5654
5655 if (session != null) {
5656 // We had been in a voice interaction session, but now focused has
5657 // move to something different. Just finish the session, we can't
5658 // return to it and retain the proper state and synchronization with
5659 // the voice interaction service.
5660 finishVoiceTask(session);
5661 }
5662 }
5663 }
5664
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005665 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5666 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005667 }
5668 updateResumedAppTrace(r);
5669 mLastResumedActivity = r;
5670
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005671 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005672
5673 applyUpdateLockStateLocked(r);
5674 applyUpdateVrModeLocked(r);
5675
Jeff Changd136e772019-11-05 20:33:52 +08005676 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005677 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005678 r == null ? "NULL" : r.shortComponentName,
5679 reason);
5680 }
5681
5682 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5683 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005684 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005685 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005686 updateSleepIfNeededLocked();
5687 return token;
5688 }
5689 }
5690
5691 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005692 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005693 final boolean wasSleeping = mSleeping;
5694 boolean updateOomAdj = false;
5695
5696 if (!shouldSleep) {
5697 // If wasSleeping is true, we need to wake up activity manager state from when
5698 // we started sleeping. In either case, we need to apply the sleep tokens, which
5699 // will wake up stacks or put them to sleep as appropriate.
5700 if (wasSleeping) {
5701 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005702 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5703 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005704 startTimeTrackingFocusedActivityLocked();
5705 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005706 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005707 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5708 }
Louis Chang149d5c82019-12-30 09:47:39 +08005709 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005710 if (wasSleeping) {
5711 updateOomAdj = true;
5712 }
5713 } else if (!mSleeping && shouldSleep) {
5714 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005715 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5716 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005717 if (mCurAppTimeTracker != null) {
5718 mCurAppTimeTracker.stop();
5719 }
5720 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005721 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005722 mStackSupervisor.goingToSleepLocked();
5723 updateResumedAppTrace(null /* resumed */);
5724 updateOomAdj = true;
5725 }
5726 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005727 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005728 }
5729 }
5730
5731 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005732 mH.removeCallbacks(mUpdateOomAdjRunnable);
5733 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005734 }
5735
Wale Ogunwale53783742018-09-16 10:21:51 -07005736 void updateCpuStats() {
5737 mH.post(mAmInternal::updateCpuStats);
5738 }
5739
Hui Yu03d12402018-12-06 18:00:37 -08005740 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5741 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005742 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5743 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005744 mH.sendMessage(m);
5745 }
5746
Hui Yu03d12402018-12-06 18:00:37 -08005747 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005748 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005749 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005750 if (task != null) {
5751 final ActivityRecord rootActivity = task.getRootActivity();
5752 if (rootActivity != null) {
5753 taskRoot = rootActivity.mActivityComponent;
5754 }
5755 }
5756
Hui Yu03d12402018-12-06 18:00:37 -08005757 final Message m = PooledLambda.obtainMessage(
5758 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005759 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005760 mH.sendMessage(m);
5761 }
5762
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005763 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5764 String hostingType) {
5765 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005766 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5767 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005768 + activity.processName);
5769 }
5770 // Post message to start process to avoid possible deadlock of calling into AMS with the
5771 // ATMS lock held.
5772 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5773 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5774 isTop, hostingType, activity.intent.getComponent());
5775 mH.sendMessage(m);
5776 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005777 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005778 }
5779 }
5780
Wale Ogunwale53783742018-09-16 10:21:51 -07005781 void setBooting(boolean booting) {
5782 mAmInternal.setBooting(booting);
5783 }
5784
5785 boolean isBooting() {
5786 return mAmInternal.isBooting();
5787 }
5788
5789 void setBooted(boolean booted) {
5790 mAmInternal.setBooted(booted);
5791 }
5792
5793 boolean isBooted() {
5794 return mAmInternal.isBooted();
5795 }
5796
5797 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5798 mH.post(() -> {
5799 if (finishBooting) {
5800 mAmInternal.finishBooting();
5801 }
5802 if (enableScreen) {
5803 mInternal.enableScreenAfterBoot(isBooted());
5804 }
5805 });
5806 }
5807
5808 void setHeavyWeightProcess(ActivityRecord root) {
5809 mHeavyWeightProcess = root.app;
5810 final Message m = PooledLambda.obtainMessage(
5811 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005812 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005813 mH.sendMessage(m);
5814 }
5815
5816 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5817 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5818 return;
5819 }
5820
5821 mHeavyWeightProcess = null;
5822 final Message m = PooledLambda.obtainMessage(
5823 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5824 proc.mUserId);
5825 mH.sendMessage(m);
5826 }
5827
5828 private void cancelHeavyWeightProcessNotification(int userId) {
5829 final INotificationManager inm = NotificationManager.getService();
5830 if (inm == null) {
5831 return;
5832 }
5833 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005834 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005835 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5836 } catch (RuntimeException e) {
5837 Slog.w(TAG, "Error canceling notification for service", e);
5838 } catch (RemoteException e) {
5839 }
5840
5841 }
5842
5843 private void postHeavyWeightProcessNotification(
5844 WindowProcessController proc, Intent intent, int userId) {
5845 if (proc == null) {
5846 return;
5847 }
5848
5849 final INotificationManager inm = NotificationManager.getService();
5850 if (inm == null) {
5851 return;
5852 }
5853
5854 try {
5855 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5856 String text = mContext.getString(R.string.heavy_weight_notification,
5857 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5858 Notification notification =
5859 new Notification.Builder(context,
5860 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5861 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5862 .setWhen(0)
5863 .setOngoing(true)
5864 .setTicker(text)
5865 .setColor(mContext.getColor(
5866 com.android.internal.R.color.system_notification_accent_color))
5867 .setContentTitle(text)
5868 .setContentText(
5869 mContext.getText(R.string.heavy_weight_notification_detail))
5870 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5871 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5872 new UserHandle(userId)))
5873 .build();
5874 try {
5875 inm.enqueueNotificationWithTag("android", "android", null,
5876 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5877 } catch (RuntimeException e) {
5878 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5879 } catch (RemoteException e) {
5880 }
5881 } catch (PackageManager.NameNotFoundException e) {
5882 Slog.w(TAG, "Unable to create context for heavy notification", e);
5883 }
5884
5885 }
5886
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005887 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5888 IBinder token, String resultWho, int requestCode, Intent[] intents,
5889 String[] resolvedTypes, int flags, Bundle bOptions) {
5890
5891 ActivityRecord activity = null;
5892 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5893 activity = ActivityRecord.isInStackLocked(token);
5894 if (activity == null) {
5895 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5896 return null;
5897 }
5898 if (activity.finishing) {
5899 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5900 return null;
5901 }
5902 }
5903
5904 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5905 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5906 bOptions);
5907 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5908 if (noCreate) {
5909 return rec;
5910 }
5911 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5912 if (activity.pendingResults == null) {
5913 activity.pendingResults = new HashSet<>();
5914 }
5915 activity.pendingResults.add(rec.ref);
5916 }
5917 return rec;
5918 }
5919
Andrii Kulian52d255c2018-07-13 11:32:19 -07005920 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005921 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005922 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005923 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5924 mCurAppTimeTracker.start(resumedActivity.packageName);
5925 }
5926 }
5927
5928 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5929 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005930 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005931 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5932 }
5933 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005934 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005935 constructResumedTraceName(resumed.packageName), 0);
5936 }
5937 mTracedResumedActivity = resumed;
5938 }
5939
5940 private String constructResumedTraceName(String packageName) {
5941 return "focused app: " + packageName;
5942 }
5943
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005944 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005945 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005946 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005947 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948 // mainStack is null during startup.
5949 if (mainStack != null) {
5950 if (changes != 0 && starting == null) {
5951 // If the configuration changed, and the caller is not already
5952 // in the process of starting an activity, then find the top
5953 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005954 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005955 }
5956
5957 if (starting != null) {
5958 kept = starting.ensureActivityConfiguration(changes,
5959 false /* preserveWindow */);
5960 // And we need to make sure at this point that all other activities
5961 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005962 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005963 !PRESERVE_WINDOWS);
5964 }
5965 }
5966
5967 return kept;
5968 }
5969
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005970 void scheduleAppGcsLocked() {
5971 mH.post(() -> mAmInternal.scheduleAppGcs());
5972 }
5973
Wale Ogunwale53783742018-09-16 10:21:51 -07005974 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5975 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5976 }
5977
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005978 /**
5979 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5980 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5981 * on demand.
5982 */
5983 IPackageManager getPackageManager() {
5984 return AppGlobals.getPackageManager();
5985 }
5986
5987 PackageManagerInternal getPackageManagerInternalLocked() {
5988 if (mPmInternal == null) {
5989 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5990 }
5991 return mPmInternal;
5992 }
5993
Hai Zhangf4da9be2019-05-01 13:46:06 +08005994 PermissionPolicyInternal getPermissionPolicyInternal() {
5995 if (mPermissionPolicyInternal == null) {
5996 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5997 }
5998 return mPermissionPolicyInternal;
5999 }
6000
Wale Ogunwale008163e2018-07-23 23:11:08 -07006001 AppWarnings getAppWarningsLocked() {
6002 return mAppWarnings;
6003 }
6004
Wale Ogunwale214f3482018-10-04 11:00:47 -07006005 Intent getHomeIntent() {
6006 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
6007 intent.setComponent(mTopComponent);
6008 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6009 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6010 intent.addCategory(Intent.CATEGORY_HOME);
6011 }
6012 return intent;
6013 }
6014
Chilun2ef71f72018-11-16 17:57:15 +08006015 /**
6016 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
6017 * activities.
6018 *
6019 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
6020 * component defined in config_secondaryHomeComponent.
6021 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
6022 */
6023 Intent getSecondaryHomeIntent(String preferredPackage) {
6024 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07006025 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
6026 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
6027 if (preferredPackage == null || useSystemProvidedLauncher) {
6028 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08006029 final String secondaryHomeComponent = mContext.getResources().getString(
6030 com.android.internal.R.string.config_secondaryHomeComponent);
6031 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
6032 } else {
6033 intent.setPackage(preferredPackage);
6034 }
6035 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6036 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6037 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
6038 }
6039 return intent;
6040 }
6041
Wale Ogunwale214f3482018-10-04 11:00:47 -07006042 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
6043 if (info == null) return null;
6044 ApplicationInfo newInfo = new ApplicationInfo(info);
6045 newInfo.initForUser(userId);
6046 return newInfo;
6047 }
6048
Wale Ogunwale9c103022018-10-18 07:44:54 -07006049 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006050 if (uid == SYSTEM_UID) {
6051 // The system gets to run in any process. If there are multiple processes with the same
6052 // uid, just pick the first (this should never happen).
6053 final SparseArray<WindowProcessController> procs =
6054 mProcessNames.getMap().get(processName);
6055 if (procs == null) return null;
6056 final int procCount = procs.size();
6057 for (int i = 0; i < procCount; i++) {
6058 final int procUid = procs.keyAt(i);
6059 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6060 // Don't use an app process or different user process for system component.
6061 continue;
6062 }
6063 return procs.valueAt(i);
6064 }
6065 }
6066
6067 return mProcessNames.get(processName, uid);
6068 }
6069
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006070 WindowProcessController getProcessController(IApplicationThread thread) {
6071 if (thread == null) {
6072 return null;
6073 }
6074
6075 final IBinder threadBinder = thread.asBinder();
6076 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6077 for (int i = pmap.size()-1; i >= 0; i--) {
6078 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6079 for (int j = procs.size() - 1; j >= 0; j--) {
6080 final WindowProcessController proc = procs.valueAt(j);
6081 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6082 return proc;
6083 }
6084 }
6085 }
6086
6087 return null;
6088 }
6089
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006090 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006091 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006092 if (proc == null) return null;
6093 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6094 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006095 }
6096 return null;
6097 }
6098
Riddle Hsua0536432019-02-16 00:38:59 +08006099 int getUidState(int uid) {
6100 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006101 }
6102
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006103 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006104 // A uid is considered to be foreground if it has a visible non-toast window.
6105 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006106 }
6107
Ricky Wai96f5c352019-04-10 18:40:17 +01006108 boolean isDeviceOwner(int uid) {
6109 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006110 }
6111
Ricky Wai96f5c352019-04-10 18:40:17 +01006112 void setDeviceOwnerUid(int uid) {
6113 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006114 }
6115
Wale Ogunwale9de19442018-10-18 19:05:03 -07006116 /**
6117 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6118 * the whitelist
6119 */
6120 String getPendingTempWhitelistTagForUidLocked(int uid) {
6121 return mPendingTempWhitelist.get(uid);
6122 }
6123
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006124 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6125 if (true || Build.IS_USER) {
6126 return;
6127 }
6128
6129 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6130 StrictMode.allowThreadDiskWrites();
6131 try {
6132 File tracesDir = new File("/data/anr");
6133 File tracesFile = null;
6134 try {
6135 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6136
6137 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006138 String timeString =
6139 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6140 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006141 sb.append(": ");
6142 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6143 sb.append(" since ");
6144 sb.append(msg);
6145 FileOutputStream fos = new FileOutputStream(tracesFile);
6146 fos.write(sb.toString().getBytes());
6147 if (app == null) {
6148 fos.write("\n*** No application process!".getBytes());
6149 }
6150 fos.close();
6151 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6152 } catch (IOException e) {
6153 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6154 return;
6155 }
6156
6157 if (app != null && app.getPid() > 0) {
6158 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6159 firstPids.add(app.getPid());
6160 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6161 }
6162
6163 File lastTracesFile = null;
6164 File curTracesFile = null;
6165 for (int i=9; i>=0; i--) {
6166 String name = String.format(Locale.US, "slow%02d.txt", i);
6167 curTracesFile = new File(tracesDir, name);
6168 if (curTracesFile.exists()) {
6169 if (lastTracesFile != null) {
6170 curTracesFile.renameTo(lastTracesFile);
6171 } else {
6172 curTracesFile.delete();
6173 }
6174 }
6175 lastTracesFile = curTracesFile;
6176 }
6177 tracesFile.renameTo(curTracesFile);
6178 } finally {
6179 StrictMode.setThreadPolicy(oldPolicy);
6180 }
6181 }
6182
Michal Karpinskida34cd42019-04-02 19:46:52 +01006183 boolean isAssociatedCompanionApp(int userId, int uid) {
6184 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6185 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006186 return false;
6187 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006188 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006189 }
6190
Issei Suzuki734bc942019-06-05 13:59:52 +02006191 void notifySingleTaskDisplayEmpty(int displayId) {
6192 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6193 }
6194
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006195 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006196 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006197
6198
Wale Ogunwale98875612018-10-12 07:53:02 -07006199 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6200 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006201
Riddle Hsud93a6c42018-11-29 21:50:06 +08006202 H(Looper looper) {
6203 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006204 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006205
6206 @Override
6207 public void handleMessage(Message msg) {
6208 switch (msg.what) {
6209 case REPORT_TIME_TRACKER_MSG: {
6210 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6211 tracker.deliverResult(mContext);
6212 } break;
6213 }
6214 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006215 }
6216
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006217 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006218 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006219
6220 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006221 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006222 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006223
6224 @Override
6225 public void handleMessage(Message msg) {
6226 switch (msg.what) {
6227 case DISMISS_DIALOG_UI_MSG: {
6228 final Dialog d = (Dialog) msg.obj;
6229 d.dismiss();
6230 break;
6231 }
6232 }
6233 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006234 }
6235
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 final class LocalService extends ActivityTaskManagerInternal {
6237 @Override
6238 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006239 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006240 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 }
6242
6243 @Override
6244 public ComponentName getHomeActivityForUser(int userId) {
6245 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006246 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006247 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006248 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250 }
6251
6252 @Override
6253 public void onLocalVoiceInteractionStarted(IBinder activity,
6254 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6255 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006256 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006257 }
6258 }
6259
6260 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006261 public void notifySingleTaskDisplayDrawn(int displayId) {
6262 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6263 }
6264
6265 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 public void notifyAppTransitionFinished() {
6267 synchronized (mGlobalLock) {
6268 mStackSupervisor.notifyAppTransitionDone();
6269 }
6270 }
6271
6272 @Override
6273 public void notifyAppTransitionCancelled() {
6274 synchronized (mGlobalLock) {
6275 mStackSupervisor.notifyAppTransitionDone();
6276 }
6277 }
6278
6279 @Override
6280 public List<IBinder> getTopVisibleActivities() {
6281 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006282 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
6284 }
6285
6286 @Override
6287 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6288 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006289 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006290 }
6291 }
6292
6293 @Override
6294 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6295 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006296 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006297 final String[] resolvedTypes = new String[intents.length];
6298
6299 // UID of the package on user userId.
6300 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6301 // packageUid may not be initialized.
6302 int packageUid = 0;
6303 final long ident = Binder.clearCallingIdentity();
6304
6305 try {
6306 for (int i = 0; i < intents.length; i++) {
6307 resolvedTypes[i] =
6308 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6309 }
6310
6311 packageUid = AppGlobals.getPackageManager().getPackageUid(
6312 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6313 } catch (RemoteException e) {
6314 // Shouldn't happen.
6315 } finally {
6316 Binder.restoreCallingIdentity(ident);
6317 }
6318
Riddle Hsu591bf612019-02-14 17:55:31 +08006319 return getActivityStartController().startActivitiesInPackage(
6320 packageUid, packageName,
6321 intents, resolvedTypes, null /* resultTo */,
6322 SafeActivityOptions.fromBundle(bOptions), userId,
6323 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6324 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 }
6326
6327 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006328 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6329 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6330 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6331 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006332 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006333 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006334 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006335 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6336 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6337 userId, validateIncomingUser, originatingPendingIntent,
6338 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006339 }
6340 }
6341
6342 @Override
6343 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6344 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6345 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006346 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006347 PendingIntentRecord originatingPendingIntent,
6348 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006349 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006350 synchronized (mGlobalLock) {
6351 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6352 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6353 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006354 validateIncomingUser, originatingPendingIntent,
6355 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006356 }
6357 }
6358
6359 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006360 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6361 Intent intent, Bundle options, int userId) {
6362 return ActivityTaskManagerService.this.startActivityAsUser(
6363 caller, callerPacakge, intent,
6364 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6365 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6366 false /*validateIncomingUser*/);
6367 }
6368
6369 @Override
lumark588a3e82018-07-20 18:53:54 +08006370 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 synchronized (mGlobalLock) {
6372
6373 // We might change the visibilities here, so prepare an empty app transition which
6374 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006375 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006376 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006377 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006378 return;
6379 }
Louis Chang677921f2019-12-06 16:44:24 +08006380 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006381 final boolean wasTransitionSet =
6382 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006383 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006384 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006385 }
Louis Chang149d5c82019-12-30 09:47:39 +08006386 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006387
6388 // If there was a transition set already we don't want to interfere with it as we
6389 // might be starting it too early.
6390 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006391 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006392 }
6393 }
6394 if (callback != null) {
6395 callback.run();
6396 }
6397 }
6398
6399 @Override
6400 public void notifyKeyguardTrustedChanged() {
6401 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006402 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006403 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006404 }
6405 }
6406 }
6407
6408 /**
6409 * Called after virtual display Id is updated by
6410 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6411 * {@param vrVr2dDisplayId}.
6412 */
6413 @Override
6414 public void setVr2dDisplayId(int vr2dDisplayId) {
6415 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6416 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006417 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006418 }
6419 }
6420
6421 @Override
6422 public void setFocusedActivity(IBinder token) {
6423 synchronized (mGlobalLock) {
6424 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6425 if (r == null) {
6426 throw new IllegalArgumentException(
6427 "setFocusedActivity: No activity record matching token=" + token);
6428 }
Louis Chang19443452018-10-09 12:10:21 +08006429 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006430 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006431 }
6432 }
6433 }
6434
6435 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006436 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006437 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006438 }
6439
6440 @Override
6441 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006442 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006443 }
6444
6445 @Override
6446 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006447 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006448 }
6449
6450 @Override
6451 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6452 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6453 }
6454
6455 @Override
6456 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006457 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006458 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006459
6460 @Override
6461 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6462 synchronized (mGlobalLock) {
6463 mActiveVoiceInteractionServiceComponent = component;
6464 }
6465 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006466
6467 @Override
6468 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6469 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6470 return;
6471 }
6472 synchronized (mGlobalLock) {
6473 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6474 if (types == null) {
6475 if (uid < 0) {
6476 return;
6477 }
6478 types = new ArrayMap<>();
6479 mAllowAppSwitchUids.put(userId, types);
6480 }
6481 if (uid < 0) {
6482 types.remove(type);
6483 } else {
6484 types.put(type, uid);
6485 }
6486 }
6487 }
6488
6489 @Override
6490 public void onUserStopped(int userId) {
6491 synchronized (mGlobalLock) {
6492 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6493 mAllowAppSwitchUids.remove(userId);
6494 }
6495 }
6496
6497 @Override
6498 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6499 synchronized (mGlobalLock) {
6500 return ActivityTaskManagerService.this.isGetTasksAllowed(
6501 caller, callingPid, callingUid);
6502 }
6503 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006504
Riddle Hsua0536432019-02-16 00:38:59 +08006505 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006506 @Override
6507 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006508 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006509 mProcessNames.put(proc.mName, proc.mUid, proc);
6510 }
6511 }
6512
Riddle Hsua0536432019-02-16 00:38:59 +08006513 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006514 @Override
6515 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006516 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006517 mProcessNames.remove(name, uid);
6518 }
6519 }
6520
Riddle Hsua0536432019-02-16 00:38:59 +08006521 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006522 @Override
6523 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006524 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006525 if (proc == mHomeProcess) {
6526 mHomeProcess = null;
6527 }
6528 if (proc == mPreviousProcess) {
6529 mPreviousProcess = null;
6530 }
6531 }
6532 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006533
Riddle Hsua0536432019-02-16 00:38:59 +08006534 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006535 @Override
6536 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006537 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006538 return mTopProcessState;
6539 }
6540 }
6541
Riddle Hsua0536432019-02-16 00:38:59 +08006542 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006543 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006544 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006545 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006546 return proc == mHeavyWeightProcess;
6547 }
6548 }
6549
Riddle Hsua0536432019-02-16 00:38:59 +08006550 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 @Override
6552 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006553 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006554 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6555 }
6556 }
6557
6558 @Override
6559 public void finishHeavyWeightApp() {
6560 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006561 if (mHeavyWeightProcess != null) {
6562 mHeavyWeightProcess.finishActivities();
6563 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006564 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6565 mHeavyWeightProcess);
6566 }
6567 }
6568
Riddle Hsua0536432019-02-16 00:38:59 +08006569 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006570 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006571 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006572 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006573 return isSleepingLocked();
6574 }
6575 }
6576
6577 @Override
6578 public boolean isShuttingDown() {
6579 synchronized (mGlobalLock) {
6580 return mShuttingDown;
6581 }
6582 }
6583
6584 @Override
6585 public boolean shuttingDown(boolean booted, int timeout) {
6586 synchronized (mGlobalLock) {
6587 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006588 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006589 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006590 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006591 return mStackSupervisor.shutdownLocked(timeout);
6592 }
6593 }
6594
6595 @Override
6596 public void enableScreenAfterBoot(boolean booted) {
6597 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006598 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006599 mWindowManager.enableScreenAfterBoot();
6600 updateEventDispatchingLocked(booted);
6601 }
6602 }
6603
6604 @Override
6605 public boolean showStrictModeViolationDialog() {
6606 synchronized (mGlobalLock) {
6607 return mShowDialogs && !mSleeping && !mShuttingDown;
6608 }
6609 }
6610
6611 @Override
6612 public void showSystemReadyErrorDialogsIfNeeded() {
6613 synchronized (mGlobalLock) {
6614 try {
6615 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6616 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6617 + " data partition or your device will be unstable.");
6618 mUiHandler.post(() -> {
6619 if (mShowDialogs) {
6620 AlertDialog d = new BaseErrorDialog(mUiContext);
6621 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6622 d.setCancelable(false);
6623 d.setTitle(mUiContext.getText(R.string.android_system_label));
6624 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6625 d.setButton(DialogInterface.BUTTON_POSITIVE,
6626 mUiContext.getText(R.string.ok),
6627 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6628 d.show();
6629 }
6630 });
6631 }
6632 } catch (RemoteException e) {
6633 }
6634
6635 if (!Build.isBuildConsistent()) {
6636 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6637 mUiHandler.post(() -> {
6638 if (mShowDialogs) {
6639 AlertDialog d = new BaseErrorDialog(mUiContext);
6640 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6641 d.setCancelable(false);
6642 d.setTitle(mUiContext.getText(R.string.android_system_label));
6643 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6644 d.setButton(DialogInterface.BUTTON_POSITIVE,
6645 mUiContext.getText(R.string.ok),
6646 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6647 d.show();
6648 }
6649 });
6650 }
6651 }
6652 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006653
6654 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006655 public void onProcessMapped(int pid, WindowProcessController proc) {
6656 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006657 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006658 }
6659 }
6660
6661 @Override
6662 public void onProcessUnMapped(int pid) {
6663 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006664 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006665 }
6666 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006667
6668 @Override
6669 public void onPackageDataCleared(String name) {
6670 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006671 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006672 mAppWarnings.onPackageDataCleared(name);
6673 }
6674 }
6675
6676 @Override
6677 public void onPackageUninstalled(String name) {
6678 synchronized (mGlobalLock) {
6679 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006680 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006681 }
6682 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006683
6684 @Override
6685 public void onPackageAdded(String name, boolean replacing) {
6686 synchronized (mGlobalLock) {
6687 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6688 }
6689 }
6690
6691 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 public void onPackageReplaced(ApplicationInfo aInfo) {
6693 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006694 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 }
6696 }
6697
6698 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006699 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6700 synchronized (mGlobalLock) {
6701 return compatibilityInfoForPackageLocked(ai);
6702 }
6703 }
6704
Yunfan Chen75157d72018-07-27 14:47:21 +09006705 /**
6706 * Set the corresponding display information for the process global configuration. To be
6707 * called when we need to show IME on a different display.
6708 *
6709 * @param pid The process id associated with the IME window.
6710 * @param displayId The ID of the display showing the IME.
6711 */
6712 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006713 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006714 // Don't update process-level configuration for Multi-Client IME process since other
6715 // IMEs on other displays will also receive this configuration change due to IME
6716 // services use the same application config/context.
6717 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006718
Yunfan Chen75157d72018-07-27 14:47:21 +09006719 if (pid == MY_PID || pid < 0) {
6720 if (DEBUG_CONFIGURATION) {
6721 Slog.w(TAG,
6722 "Trying to update display configuration for system/invalid process.");
6723 }
6724 return;
6725 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006726 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006727 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006728 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006729 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006730 // Call might come when display is not yet added or has been removed.
6731 if (DEBUG_CONFIGURATION) {
6732 Slog.w(TAG, "Trying to update display configuration for non-existing "
6733 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006734 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006735 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006736 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006737 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006738 if (process == null) {
6739 if (DEBUG_CONFIGURATION) {
6740 Slog.w(TAG, "Trying to update display configuration for invalid "
6741 + "process, pid=" + pid);
6742 }
6743 return;
6744 }
lumarkddc77fb2019-06-27 22:22:23 +08006745 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006746 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006747 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006748 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006749
6750 @Override
6751 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006752 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006753 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006754 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006755 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006756 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006757 }
6758 }
6759 }
6760
6761 @Override
6762 public void clearPendingResultForActivity(IBinder activityToken,
6763 WeakReference<PendingIntentRecord> pir) {
6764 synchronized (mGlobalLock) {
6765 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6766 if (r != null && r.pendingResults != null) {
6767 r.pendingResults.remove(pir);
6768 }
6769 }
6770 }
6771
6772 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006773 public ActivityTokens getTopActivityForTask(int taskId) {
6774 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006775 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006776 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006777 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6778 + " Requested task not found");
6779 return null;
6780 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006781 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006782 if (activity == null) {
6783 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6784 + " Requested activity not found");
6785 return null;
6786 }
6787 if (!activity.attachedToProcess()) {
6788 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6789 + activity);
6790 return null;
6791 }
6792 return new ActivityTokens(activity.appToken, activity.assistToken,
6793 activity.app.getThread());
6794 }
6795 }
6796
6797 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006798 public IIntentSender getIntentSender(int type, String packageName,
6799 int callingUid, int userId, IBinder token, String resultWho,
6800 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6801 Bundle bOptions) {
6802 synchronized (mGlobalLock) {
6803 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6804 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6805 }
6806 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006807
6808 @Override
6809 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6810 synchronized (mGlobalLock) {
6811 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6812 if (r == null) {
6813 return null;
6814 }
6815 if (r.mServiceConnectionsHolder == null) {
6816 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6817 ActivityTaskManagerService.this, r);
6818 }
6819
6820 return r.mServiceConnectionsHolder;
6821 }
6822 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006823
6824 @Override
6825 public Intent getHomeIntent() {
6826 synchronized (mGlobalLock) {
6827 return ActivityTaskManagerService.this.getHomeIntent();
6828 }
6829 }
6830
6831 @Override
6832 public boolean startHomeActivity(int userId, String reason) {
6833 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006834 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006835 }
6836 }
6837
6838 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006839 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006840 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006841 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006842 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006843 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006844 }
Chilun8b1f1be2019-03-13 17:14:36 +08006845 }
6846
6847 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006848 public boolean startHomeOnAllDisplays(int userId, String reason) {
6849 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006850 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006851 }
6852 }
6853
Riddle Hsua0536432019-02-16 00:38:59 +08006854 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006855 @Override
6856 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006857 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006858 if (mFactoryTest == FACTORY_TEST_OFF) {
6859 return false;
6860 }
6861 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6862 && wpc.mName.equals(mTopComponent.getPackageName())) {
6863 return true;
6864 }
6865 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6866 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6867 }
6868 }
6869
6870 @Override
6871 public void updateTopComponentForFactoryTest() {
6872 synchronized (mGlobalLock) {
6873 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6874 return;
6875 }
6876 final ResolveInfo ri = mContext.getPackageManager()
6877 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6878 final CharSequence errorMsg;
6879 if (ri != null) {
6880 final ActivityInfo ai = ri.activityInfo;
6881 final ApplicationInfo app = ai.applicationInfo;
6882 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6883 mTopAction = Intent.ACTION_FACTORY_TEST;
6884 mTopData = null;
6885 mTopComponent = new ComponentName(app.packageName, ai.name);
6886 errorMsg = null;
6887 } else {
6888 errorMsg = mContext.getResources().getText(
6889 com.android.internal.R.string.factorytest_not_system);
6890 }
6891 } else {
6892 errorMsg = mContext.getResources().getText(
6893 com.android.internal.R.string.factorytest_no_action);
6894 }
6895 if (errorMsg == null) {
6896 return;
6897 }
6898
6899 mTopAction = null;
6900 mTopData = null;
6901 mTopComponent = null;
6902 mUiHandler.post(() -> {
6903 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6904 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006905 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006906 });
6907 }
6908 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909
Riddle Hsua0536432019-02-16 00:38:59 +08006910 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 @Override
6912 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6913 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006914 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006916 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006917
6918 wpc.clearRecentTasks();
6919 wpc.clearActivities();
6920
6921 if (wpc.isInstrumenting()) {
6922 finishInstrumentationCallback.run();
6923 }
6924
Jorim Jaggid0752812018-10-16 16:07:20 +02006925 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006926 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006927 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006928 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006929 // If there was nothing to resume, and we are not already restarting
6930 // this process, but there is a visible activity that is hosted by the
6931 // process...then make sure all visible activities are running, taking
6932 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006933 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006934 !PRESERVE_WINDOWS);
6935 }
6936 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006937 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006939 }
6940 }
6941 }
6942
6943 @Override
6944 public void closeSystemDialogs(String reason) {
6945 enforceNotIsolatedCaller("closeSystemDialogs");
6946
6947 final int pid = Binder.getCallingPid();
6948 final int uid = Binder.getCallingUid();
6949 final long origId = Binder.clearCallingIdentity();
6950 try {
6951 synchronized (mGlobalLock) {
6952 // Only allow this from foreground processes, so that background
6953 // applications can't abuse it to prevent system UI from being shown.
6954 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006955 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 if (!proc.isPerceptible()) {
6957 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6958 + " from background process " + proc);
6959 return;
6960 }
6961 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 mWindowManager.closeSystemDialogs(reason);
6963
Louis Chang149d5c82019-12-30 09:47:39 +08006964 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006965 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006966 // Call into AM outside the synchronized block.
6967 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 } finally {
6969 Binder.restoreCallingIdentity(origId);
6970 }
6971 }
6972
6973 @Override
6974 public void cleanupDisabledPackageComponents(
6975 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6976 synchronized (mGlobalLock) {
6977 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006978 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006980 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006981 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 }
6983
6984 // Clean-up disabled tasks
6985 getRecentTasks().cleanupDisabledPackageTasksLocked(
6986 packageName, disabledClasses, userId);
6987 }
6988 }
6989
6990 @Override
6991 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6992 int userId) {
6993 synchronized (mGlobalLock) {
6994
6995 boolean didSomething =
6996 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006997 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006998 null, doit, evenPersistent, userId);
6999 return didSomething;
7000 }
7001 }
7002
7003 @Override
7004 public void resumeTopActivities(boolean scheduleIdle) {
7005 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007006 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08007008 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 }
7010 }
7011 }
7012
Riddle Hsua0536432019-02-16 00:38:59 +08007013 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 @Override
7015 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08007016 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
7018 }
7019 }
7020
Riddle Hsua0536432019-02-16 00:38:59 +08007021 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007022 @Override
7023 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08007024 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007025 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
7026 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
7027 }
7028 try {
Louis Chang149d5c82019-12-30 09:47:39 +08007029 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007030 } finally {
7031 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
7032 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034 }
7035
7036 @Override
7037 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
7038 try {
7039 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
7040 throw new SecurityException("Only privileged app can call notifyLockedProfile");
7041 }
7042 } catch (RemoteException ex) {
7043 throw new SecurityException("Fail to check is caller a privileged app", ex);
7044 }
7045
7046 synchronized (mGlobalLock) {
7047 final long ident = Binder.clearCallingIdentity();
7048 try {
7049 if (mAmInternal.shouldConfirmCredentials(userId)) {
7050 if (mKeyguardController.isKeyguardLocked()) {
7051 // Showing launcher to avoid user entering credential twice.
7052 startHomeActivity(currentUserId, "notifyLockedProfile");
7053 }
Louis Chang149d5c82019-12-30 09:47:39 +08007054 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007055 }
7056 } finally {
7057 Binder.restoreCallingIdentity(ident);
7058 }
7059 }
7060 }
7061
7062 @Override
7063 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7064 mAmInternal.enforceCallingPermission(
7065 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7066
7067 synchronized (mGlobalLock) {
7068 final long ident = Binder.clearCallingIdentity();
7069 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007070 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7071 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7074 UserHandle.CURRENT);
7075 } finally {
7076 Binder.restoreCallingIdentity(ident);
7077 }
7078 }
7079 }
7080
7081 @Override
7082 public void writeActivitiesToProto(ProtoOutputStream proto) {
7083 synchronized (mGlobalLock) {
7084 // The output proto of "activity --proto activities"
7085 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007086 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007087 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7088 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 }
7090 }
7091
7092 @Override
7093 public void saveANRState(String reason) {
7094 synchronized (mGlobalLock) {
7095 final StringWriter sw = new StringWriter();
7096 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7097 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7098 if (reason != null) {
7099 pw.println(" Reason: " + reason);
7100 }
7101 pw.println();
7102 getActivityStartController().dump(pw, " ", null);
7103 pw.println();
7104 pw.println("-------------------------------------------------------------------------------");
7105 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7106 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7107 "" /* header */);
7108 pw.println();
7109 pw.close();
7110
7111 mLastANRState = sw.toString();
7112 }
7113 }
7114
7115 @Override
7116 public void clearSavedANRState() {
7117 synchronized (mGlobalLock) {
7118 mLastANRState = null;
7119 }
7120 }
7121
7122 @Override
7123 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7124 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7125 synchronized (mGlobalLock) {
7126 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7127 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7128 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7129 dumpLastANRLocked(pw);
7130 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7131 dumpLastANRTracesLocked(pw);
7132 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7133 dumpActivityStarterLocked(pw, dumpPackage);
7134 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7135 dumpActivityContainersLocked(pw);
7136 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7137 if (getRecentTasks() != null) {
7138 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7139 }
7140 }
7141 }
7142 }
7143
7144 @Override
7145 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7146 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7147 int wakefulness) {
7148 synchronized (mGlobalLock) {
7149 if (mHomeProcess != null && (dumpPackage == null
7150 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7151 if (needSep) {
7152 pw.println();
7153 needSep = false;
7154 }
7155 pw.println(" mHomeProcess: " + mHomeProcess);
7156 }
7157 if (mPreviousProcess != null && (dumpPackage == null
7158 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7159 if (needSep) {
7160 pw.println();
7161 needSep = false;
7162 }
7163 pw.println(" mPreviousProcess: " + mPreviousProcess);
7164 }
7165 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7166 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7167 StringBuilder sb = new StringBuilder(128);
7168 sb.append(" mPreviousProcessVisibleTime: ");
7169 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7170 pw.println(sb);
7171 }
7172 if (mHeavyWeightProcess != null && (dumpPackage == null
7173 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7174 if (needSep) {
7175 pw.println();
7176 needSep = false;
7177 }
7178 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7179 }
7180 if (dumpPackage == null) {
7181 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007182 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184 if (dumpAll) {
7185 if (dumpPackage == null) {
7186 pw.println(" mConfigWillChange: "
7187 + getTopDisplayFocusedStack().mConfigWillChange);
7188 }
7189 if (mCompatModePackages.getPackages().size() > 0) {
7190 boolean printed = false;
7191 for (Map.Entry<String, Integer> entry
7192 : mCompatModePackages.getPackages().entrySet()) {
7193 String pkg = entry.getKey();
7194 int mode = entry.getValue();
7195 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7196 continue;
7197 }
7198 if (!printed) {
7199 pw.println(" mScreenCompatPackages:");
7200 printed = true;
7201 }
7202 pw.println(" " + pkg + ": " + mode);
7203 }
7204 }
7205 }
7206
7207 if (dumpPackage == null) {
7208 pw.println(" mWakefulness="
7209 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007210 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 if (mRunningVoice != null) {
7212 pw.println(" mRunningVoice=" + mRunningVoice);
7213 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7214 }
7215 pw.println(" mSleeping=" + mSleeping);
7216 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7217 pw.println(" mVrController=" + mVrController);
7218 }
7219 if (mCurAppTimeTracker != null) {
7220 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7221 }
7222 if (mAllowAppSwitchUids.size() > 0) {
7223 boolean printed = false;
7224 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7225 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7226 for (int j = 0; j < types.size(); j++) {
7227 if (dumpPackage == null ||
7228 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7229 if (needSep) {
7230 pw.println();
7231 needSep = false;
7232 }
7233 if (!printed) {
7234 pw.println(" mAllowAppSwitchUids:");
7235 printed = true;
7236 }
7237 pw.print(" User ");
7238 pw.print(mAllowAppSwitchUids.keyAt(i));
7239 pw.print(": Type ");
7240 pw.print(types.keyAt(j));
7241 pw.print(" = ");
7242 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7243 pw.println();
7244 }
7245 }
7246 }
7247 }
7248 if (dumpPackage == null) {
7249 if (mController != null) {
7250 pw.println(" mController=" + mController
7251 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7252 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007253 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7254 pw.println(" mLaunchingActivityWakeLock="
7255 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007256 }
7257
7258 return needSep;
7259 }
7260 }
7261
7262 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007263 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7264 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007265 synchronized (mGlobalLock) {
7266 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007267 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007268 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007269 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7270 if (mRunningVoice != null) {
7271 final long vrToken = proto.start(
7272 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7273 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7274 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007275 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007276 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7277 proto.end(vrToken);
7278 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007279 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007280 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007281 if (mController != null) {
7282 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007283 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7284 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7286 proto.end(token);
7287 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007288 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7289 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007290 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292
7293 if (mHomeProcess != null && (dumpPackage == null
7294 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007295 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007296 }
7297
7298 if (mPreviousProcess != null && (dumpPackage == null
7299 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007300 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007301 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7302 }
7303
7304 if (mHeavyWeightProcess != null && (dumpPackage == null
7305 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007306 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007307 }
7308
7309 for (Map.Entry<String, Integer> entry
7310 : mCompatModePackages.getPackages().entrySet()) {
7311 String pkg = entry.getKey();
7312 int mode = entry.getValue();
7313 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7314 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7315 proto.write(PACKAGE, pkg);
7316 proto.write(MODE, mode);
7317 proto.end(compatToken);
7318 }
7319 }
7320
7321 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007322 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007323 }
7324
7325 }
7326 }
7327
7328 @Override
7329 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7330 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7331 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007332 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7333 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007334 }
7335
7336 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007337 public void dumpForOom(PrintWriter pw) {
7338 synchronized (mGlobalLock) {
7339 pw.println(" mHomeProcess: " + mHomeProcess);
7340 pw.println(" mPreviousProcess: " + mPreviousProcess);
7341 if (mHeavyWeightProcess != null) {
7342 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7343 }
7344 }
7345 }
7346
7347 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007348 public boolean canGcNow() {
7349 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007350 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007351 }
7352 }
7353
Riddle Hsua0536432019-02-16 00:38:59 +08007354 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007355 @Override
7356 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007357 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007358 if (mRootWindowContainer == null) {
7359 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007360 // oomadj after AMS created.
7361 return null;
7362 }
Louis Chang149d5c82019-12-30 09:47:39 +08007363 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007364 return top != null ? top.app : null;
7365 }
7366 }
7367
Riddle Hsua0536432019-02-16 00:38:59 +08007368 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007369 @Override
7370 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007371 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007372 if (mRootWindowContainer != null) {
7373 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007374 }
7375 }
7376 }
7377
7378 @Override
7379 public void scheduleDestroyAllActivities(String reason) {
7380 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007381 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007382 }
7383 }
7384
7385 @Override
7386 public void removeUser(int userId) {
7387 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007388 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007389 }
7390 }
7391
7392 @Override
7393 public boolean switchUser(int userId, UserState userState) {
7394 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007395 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007396 }
7397 }
7398
7399 @Override
7400 public void onHandleAppCrash(WindowProcessController wpc) {
7401 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007402 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007403 }
7404 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007405
7406 @Override
7407 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7408 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007409 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007410 }
7411 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007412
Riddle Hsua0536432019-02-16 00:38:59 +08007413 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007414 @Override
7415 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007416 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007417 }
7418
Riddle Hsua0536432019-02-16 00:38:59 +08007419 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007420 @Override
7421 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007422 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007423 }
7424
Riddle Hsua0536432019-02-16 00:38:59 +08007425 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007426 @Override
7427 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007428 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007429 }
7430
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 onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007434 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007435 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007436
7437 @Override
7438 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007439 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007440 mPendingTempWhitelist.put(uid, tag);
7441 }
7442 }
7443
7444 @Override
7445 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007446 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007447 mPendingTempWhitelist.remove(uid);
7448 }
7449 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007450
7451 @Override
7452 public boolean handleAppCrashInActivityController(String processName, int pid,
7453 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7454 Runnable killCrashingAppCallback) {
7455 synchronized (mGlobalLock) {
7456 if (mController == null) {
7457 return false;
7458 }
7459
7460 try {
7461 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7462 stackTrace)) {
7463 killCrashingAppCallback.run();
7464 return true;
7465 }
7466 } catch (RemoteException e) {
7467 mController = null;
7468 Watchdog.getInstance().setActivityController(null);
7469 }
7470 return false;
7471 }
7472 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007473
7474 @Override
7475 public void removeRecentTasksByPackageName(String packageName, int userId) {
7476 synchronized (mGlobalLock) {
7477 mRecentTasks.removeTasksByPackageName(packageName, userId);
7478 }
7479 }
7480
7481 @Override
7482 public void cleanupRecentTasksForUser(int userId) {
7483 synchronized (mGlobalLock) {
7484 mRecentTasks.cleanupLocked(userId);
7485 }
7486 }
7487
7488 @Override
7489 public void loadRecentTasksForUser(int userId) {
7490 synchronized (mGlobalLock) {
7491 mRecentTasks.loadUserRecentsLocked(userId);
7492 }
7493 }
7494
7495 @Override
7496 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7497 synchronized (mGlobalLock) {
7498 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7499 }
7500 }
7501
7502 @Override
7503 public void flushRecentTasks() {
7504 mRecentTasks.flush();
7505 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007506
7507 @Override
7508 public WindowProcessController getHomeProcess() {
7509 synchronized (mGlobalLock) {
7510 return mHomeProcess;
7511 }
7512 }
7513
7514 @Override
7515 public WindowProcessController getPreviousProcess() {
7516 synchronized (mGlobalLock) {
7517 return mPreviousProcess;
7518 }
7519 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007520
7521 @Override
7522 public void clearLockedTasks(String reason) {
7523 synchronized (mGlobalLock) {
7524 getLockTaskController().clearLockedTasks(reason);
7525 }
7526 }
7527
7528 @Override
7529 public void updateUserConfiguration() {
7530 synchronized (mGlobalLock) {
7531 final Configuration configuration = new Configuration(getGlobalConfiguration());
7532 final int currentUserId = mAmInternal.getCurrentUserId();
7533 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7534 configuration, currentUserId, Settings.System.canWrite(mContext));
7535 updateConfigurationLocked(configuration, null /* starting */,
7536 false /* initLocale */, false /* persistent */, currentUserId,
7537 false /* deferResume */);
7538 }
7539 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007540
7541 @Override
7542 public boolean canShowErrorDialogs() {
7543 synchronized (mGlobalLock) {
7544 return mShowDialogs && !mSleeping && !mShuttingDown
7545 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7546 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7547 mAmInternal.getCurrentUserId())
7548 && !(UserManager.isDeviceInDemoMode(mContext)
7549 && mAmInternal.getCurrentUser().isDemo());
7550 }
7551 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007552
7553 @Override
7554 public void setProfileApp(String profileApp) {
7555 synchronized (mGlobalLock) {
7556 mProfileApp = profileApp;
7557 }
7558 }
7559
7560 @Override
7561 public void setProfileProc(WindowProcessController wpc) {
7562 synchronized (mGlobalLock) {
7563 mProfileProc = wpc;
7564 }
7565 }
7566
7567 @Override
7568 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7569 synchronized (mGlobalLock) {
7570 mProfilerInfo = profilerInfo;
7571 }
7572 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007573
7574 @Override
7575 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7576 synchronized (mGlobalLock) {
7577 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7578 }
7579 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007580
7581 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007582 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7583 boolean reducedResolution) {
7584 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7585 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007586 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007587
7588 @Override
7589 public boolean isUidForeground(int uid) {
7590 synchronized (mGlobalLock) {
7591 return ActivityTaskManagerService.this.isUidForeground(uid);
7592 }
7593 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007594
7595 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007596 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007597 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007598 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007599 }
7600 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007601
7602 @Override
7603 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007604 // Translate package names into UIDs
7605 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007606 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007607 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7608 if (uid >= 0) {
7609 result.add(uid);
7610 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007611 }
7612 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007613 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007614 }
7615 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007616 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007617}