blob: 014b682ff8d69686cba150f8144ecc5ec457df9c [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800126import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700218import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.EventLog;
220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700293import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Map;
295import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296
297/**
298 * System service for managing activities and their containers (task, stacks, displays,... ).
299 *
300 * {@hide}
301 */
302public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700303 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700305 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
306 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
307 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
308 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
309 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700310 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700311
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100316 // How long we permit background activity starts after an activity in the process
317 // started or finished.
318 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319
Wale Ogunwale98875612018-10-12 07:53:02 -0700320 /** Used to indicate that an app transition should be animated. */
321 static final boolean ANIMATE = true;
322
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700323 /** Hardware-reported OpenGLES version. */
324 final int GL_ES_VERSION;
325
Wale Ogunwale31913b52018-10-13 08:29:31 -0700326 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
327 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
328 public static final String DUMP_LASTANR_CMD = "lastanr" ;
329 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
330 public static final String DUMP_STARTER_CMD = "starter" ;
331 public static final String DUMP_CONTAINERS_CMD = "containers" ;
332 public static final String DUMP_RECENTS_CMD = "recents" ;
333 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
334
Wale Ogunwale64258362018-10-16 15:13:37 -0700335 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
336 public static final int RELAUNCH_REASON_NONE = 0;
337 /** This activity is being relaunched due to windowing mode change. */
338 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
339 /** This activity is being relaunched due to a free-resize operation. */
340 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
341
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700342 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700343
Wale Ogunwalef6733932018-06-27 05:14:34 -0700344 /**
345 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
346 * change at runtime. Use mContext for non-UI purposes.
347 */
348 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700350 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700353 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700354 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800355 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800356 @VisibleForTesting
357 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 PowerManagerInternal mPowerManagerInternal;
359 private UsageStatsManagerInternal mUsageStatsInternal;
360
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700361 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 IntentFirewall mIntentFirewall;
363
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700364 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800365 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800366 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700367 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
369 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
370 *
371 * @see WindowManagerThreadPriorityBooster
372 */
373 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700374 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800375 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700376 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700377 private UserManagerService mUserManager;
378 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700379 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800380 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700381 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** All processes currently running that might have a window organized by name. */
383 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100384 /** All processes we currently have running mapped by pid and uid */
385 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** This is the process holding what we currently consider to be the "home" activity. */
387 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700388 /** The currently running heavy-weight process, if any. */
389 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700390 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /**
392 * This is the process holding the activity the user last visited that is in a different process
393 * from the one they are currently in.
394 */
395 WindowProcessController mPreviousProcess;
396 /** The time at which the previous process was last visible. */
397 long mPreviousProcessVisibleTime;
398
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700399 /** List of intents that were used to start the most recent tasks. */
400 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700401 /** State of external calls telling us if the device is awake or asleep. */
402 private boolean mKeyguardShown = false;
403
404 // Wrapper around VoiceInteractionServiceManager
405 private AssistUtils mAssistUtils;
406
407 // VoiceInteraction session ID that changes for each new request except when
408 // being called for multi-window assist in a single session.
409 private int mViSessionId = 1000;
410
411 // How long to wait in getAssistContextExtras for the activity and foreground services
412 // to respond with the result.
413 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
414
415 // How long top wait when going through the modern assist (which doesn't need to block
416 // on getting this result before starting to launch its UI).
417 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
418
419 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
420 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
421
Alison Cichowlas3e340502018-08-07 17:15:01 -0400422 // Permission tokens are used to temporarily granted a trusted app the ability to call
423 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
424 // showing any appropriate error messages to the user.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
426 10 * MINUTE_IN_MILLIS;
427
428 // How long before the service actually expires a token. This is slightly longer than
429 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
430 // expiration exception.
431 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
432 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
433
434 // How long the service will remember expired tokens, for the purpose of providing error
435 // messaging when a client uses an expired token.
436 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
437 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
438
439 // Activity tokens of system activities that are delegating their call to
440 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
441 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
442
443 // Permission tokens that have expired, but we remember for error reporting.
444 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
447
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700448 // Keeps track of the active voice interaction service component, notified from
449 // VoiceInteractionManagerService
450 ComponentName mActiveVoiceInteractionServiceComponent;
451
Michal Karpinskida34cd42019-04-02 19:46:52 +0100452 // A map userId and all its companion app uids
453 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000454
Wale Ogunwalee2172292018-10-25 10:11:10 -0700455 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700456 KeyguardController mKeyguardController;
457 private final ClientLifecycleManager mLifecycleManager;
458 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700459 /** The controller for all operations related to locktask. */
460 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700461 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700462
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 boolean mSuppressResizeConfigChanges;
464
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700465 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 new UpdateConfigurationResult();
467
468 static final class UpdateConfigurationResult {
469 // Configuration changes that were updated.
470 int changes;
471 // If the activity was relaunched to match the new configuration.
472 boolean activityRelaunched;
473
474 void reset() {
475 changes = 0;
476 activityRelaunched = false;
477 }
478 }
479
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 private int mConfigurationSeq;
482 // To cache the list of supported system locales
483 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484
485 /**
486 * Temp object used when global and/or display override configuration is updated. It is also
487 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
488 * anyone...
489 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private Configuration mTempConfig = new Configuration();
491
Wale Ogunwalef6733932018-06-27 05:14:34 -0700492 /** Temporary to avoid allocations. */
493 final StringBuilder mStringBuilder = new StringBuilder(256);
494
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 // Amount of time after a call to stopAppSwitches() during which we will
496 // prevent further untrusted switches from happening.
497 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
498
499 /**
500 * The time at which we will allow normal application switches again,
501 * after a call to {@link #stopAppSwitches()}.
502 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700503 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 /**
505 * This is set to true after the first switch after mAppSwitchesAllowedTime
506 * is set; any switches after that will clear the time.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509
Ricky Wai906af482019-06-03 17:25:28 +0100510 /**
511 * Last stop app switches time, apps finished before this time cannot start background activity
512 * even if they are in grace period.
513 */
514 private long mLastStopAppSwitchesTime;
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 IActivityController mController = null;
517 boolean mControllerIsAMonkey = false;
518
Wale Ogunwale214f3482018-10-04 11:00:47 -0700519 final int mFactoryTest;
520
521 /** Used to control how we initialize the service. */
522 ComponentName mTopComponent;
523 String mTopAction = Intent.ACTION_MAIN;
524 String mTopData;
525
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800526 /** Profiling app information. */
527 String mProfileApp = null;
528 WindowProcessController mProfileProc = null;
529 ProfilerInfo mProfilerInfo = null;
530
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700532 * Dump of the activity state at the time of the last ANR. Cleared after
533 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
534 */
535 String mLastANRState;
536
537 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 * Used to retain an update lock when the foreground activity is in
539 * immersive mode.
540 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542
543 /**
544 * Packages that are being allowed to perform unrestricted app switches. Mapping is
545 * User -> Type -> uid.
546 */
547 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
548
549 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private int mThumbnailWidth;
551 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700552
553 /**
554 * Flag that indicates if multi-window is enabled.
555 *
556 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
557 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
558 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
559 * At least one of the forms of multi-window must be enabled in order for this flag to be
560 * initialized to 'true'.
561 *
562 * @see #mSupportsSplitScreenMultiWindow
563 * @see #mSupportsFreeformWindowManagement
564 * @see #mSupportsPictureInPicture
565 * @see #mSupportsMultiDisplay
566 */
567 boolean mSupportsMultiWindow;
568 boolean mSupportsSplitScreenMultiWindow;
569 boolean mSupportsFreeformWindowManagement;
570 boolean mSupportsPictureInPicture;
571 boolean mSupportsMultiDisplay;
572 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700573 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700574
575 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
576
577 // VR Vr2d Display Id.
578 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700579
Wale Ogunwalef6733932018-06-27 05:14:34 -0700580 /**
581 * Set while we are wanting to sleep, to prevent any
582 * activities from being started/resumed.
583 *
584 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
585 *
586 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
587 * while in the sleep state until there is a pending transition out of sleep, in which case
588 * mSleeping is set to false, and remains false while awake.
589 *
590 * Whether mSleeping can quickly toggled between true/false without the device actually
591 * display changing states is undefined.
592 */
593 private boolean mSleeping = false;
594
595 /**
596 * The process state used for processes that are running the top activities.
597 * This changes between TOP and TOP_SLEEPING to following mSleeping.
598 */
599 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
600
Riddle Hsua0022cd2019-09-09 21:12:41 +0800601 @Retention(RetentionPolicy.SOURCE)
602 @IntDef({
603 LAYOUT_REASON_CONFIG_CHANGED,
604 LAYOUT_REASON_VISIBILITY_CHANGED,
605 })
606 @interface LayoutReason {}
607 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
608 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
609
610 /** The reasons to perform surface placement. */
611 @LayoutReason
612 private int mLayoutReasons;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
615 // automatically. Important for devices without direct input devices.
616 private boolean mShowDialogs = true;
617
618 /** Set if we are shutting down the system, similar to sleeping. */
619 boolean mShuttingDown = false;
620
621 /**
622 * We want to hold a wake lock while running a voice interaction session, since
623 * this may happen with the screen off and we need to keep the CPU running to
624 * be able to continue to interact with the user.
625 */
626 PowerManager.WakeLock mVoiceWakeLock;
627
628 /**
629 * Set while we are running a voice interaction. This overrides sleeping while it is active.
630 */
631 IVoiceInteractionSession mRunningVoice;
632
633 /**
634 * The last resumed activity. This is identical to the current resumed activity most
635 * of the time but could be different when we're pausing one activity before we resume
636 * another activity.
637 */
638 ActivityRecord mLastResumedActivity;
639
640 /**
641 * The activity that is currently being traced as the active resumed activity.
642 *
643 * @see #updateResumedAppTrace
644 */
645 private @Nullable ActivityRecord mTracedResumedActivity;
646
647 /** If non-null, we are tracking the time the user spends in the currently focused app. */
648 AppTimeTracker mCurAppTimeTracker;
649
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700650 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700651
Wale Ogunwale53783742018-09-16 10:21:51 -0700652 /**
653 * Packages that the user has asked to have run in screen size
654 * compatibility mode instead of filling the screen.
655 */
656 CompatModePackages mCompatModePackages;
657
Wale Ogunwalef6733932018-06-27 05:14:34 -0700658 private FontScaleSettingObserver mFontScaleSettingObserver;
659
Ricky Wai96f5c352019-04-10 18:40:17 +0100660 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000661
Wale Ogunwalef6733932018-06-27 05:14:34 -0700662 private final class FontScaleSettingObserver extends ContentObserver {
663 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
664 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
665
666 public FontScaleSettingObserver() {
667 super(mH);
668 final ContentResolver resolver = mContext.getContentResolver();
669 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
670 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
671 UserHandle.USER_ALL);
672 }
673
674 @Override
675 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
676 if (mFontScaleUri.equals(uri)) {
677 updateFontScaleIfNeeded(userId);
678 } else if (mHideErrorDialogsUri.equals(uri)) {
679 synchronized (mGlobalLock) {
680 updateShouldShowDialogsLocked(getGlobalConfiguration());
681 }
682 }
683 }
684 }
685
Riddle Hsua0536432019-02-16 00:38:59 +0800686 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
687 @Target(ElementType.METHOD)
688 @Retention(RetentionPolicy.SOURCE)
689 @interface HotPath {
690 int NONE = 0;
691 int OOM_ADJUSTMENT = 1;
692 int LRU_UPDATE = 2;
693 int PROCESS_CHANGE = 3;
694 int caller() default NONE;
695 }
696
Charles Chen8d98dd22018-12-26 17:36:54 +0800697 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
698 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700699 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700700 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700701 mSystemThread = ActivityThread.currentActivityThread();
702 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700703 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800704 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700705 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void onSystemReady() {
709 synchronized (mGlobalLock) {
710 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
711 PackageManager.FEATURE_CANT_SAVE_STATE);
712 mAssistUtils = new AssistUtils(mContext);
713 mVrController.onSystemReady();
714 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700715 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700716 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700717 }
718
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700719 public void onInitPowerManagement() {
720 synchronized (mGlobalLock) {
721 mStackSupervisor.initPowerManagement();
722 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
723 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
724 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
725 mVoiceWakeLock.setReferenceCounted(false);
726 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700727 }
728
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700729 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700730 mFontScaleSettingObserver = new FontScaleSettingObserver();
731 }
732
Wale Ogunwale59507092018-10-29 09:00:30 -0700733 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734 final boolean freeformWindowManagement =
735 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
736 || Settings.Global.getInt(
737 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
738
739 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
740 final boolean supportsPictureInPicture = supportsMultiWindow &&
741 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
742 final boolean supportsSplitScreenMultiWindow =
743 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
744 final boolean supportsMultiDisplay = mContext.getPackageManager()
745 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700746 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
747 final boolean forceResizable = Settings.Global.getInt(
748 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700749 final boolean sizeCompatFreeform = Settings.Global.getInt(
750 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700751
752 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900753 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700754
755 final Configuration configuration = new Configuration();
756 Settings.System.getConfiguration(resolver, configuration);
757 if (forceRtl) {
758 // This will take care of setting the correct layout direction flags
759 configuration.setLayoutDirection(configuration.locale);
760 }
761
762 synchronized (mGlobalLock) {
763 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 final boolean multiWindowFormEnabled = freeformWindowManagement
766 || supportsSplitScreenMultiWindow
767 || supportsPictureInPicture
768 || supportsMultiDisplay;
769 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
770 mSupportsMultiWindow = true;
771 mSupportsFreeformWindowManagement = freeformWindowManagement;
772 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
773 mSupportsPictureInPicture = supportsPictureInPicture;
774 mSupportsMultiDisplay = supportsMultiDisplay;
775 } else {
776 mSupportsMultiWindow = false;
777 mSupportsFreeformWindowManagement = false;
778 mSupportsSplitScreenMultiWindow = false;
779 mSupportsPictureInPicture = false;
780 mSupportsMultiDisplay = false;
781 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700782 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 // This happens before any activities are started, so we can change global configuration
784 // in-place.
785 updateConfigurationLocked(configuration, null, true);
786 final Configuration globalConfig = getGlobalConfiguration();
787 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
788
789 // Load resources only after the current configuration has been set.
790 final Resources res = mContext.getResources();
791 mThumbnailWidth = res.getDimensionPixelSize(
792 com.android.internal.R.dimen.thumbnail_width);
793 mThumbnailHeight = res.getDimensionPixelSize(
794 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700795 }
796 }
797
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800798 public WindowManagerGlobalLock getGlobalLock() {
799 return mGlobalLock;
800 }
801
Yunfan Chen585f2932019-01-29 16:04:45 +0900802 /** For test purpose only. */
803 @VisibleForTesting
804 public ActivityTaskManagerInternal getAtmInternal() {
805 return mInternal;
806 }
807
Riddle Hsud93a6c42018-11-29 21:50:06 +0800808 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
809 Looper looper) {
810 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700811 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700813 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800814 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700815 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700816 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817
818 mTempConfig.setToDefaults();
819 mTempConfig.setLocales(LocaleList.getDefault());
820 mConfigurationSeq = mTempConfig.seq = 1;
821 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800822 mRootActivityContainer = new RootActivityContainer(this);
823 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700825 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700827 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700829 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700831 mKeyguardController = mStackSupervisor.getKeyguardController();
832 }
833
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700834 public void onActivityManagerInternalAdded() {
835 synchronized (mGlobalLock) {
836 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
837 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
838 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700839 }
840
Yunfan Chen75157d72018-07-27 14:47:21 +0900841 int increaseConfigurationSeqLocked() {
842 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
843 return mConfigurationSeq;
844 }
845
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700846 protected ActivityStackSupervisor createStackSupervisor() {
847 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
848 supervisor.initialize();
849 return supervisor;
850 }
851
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800852 protected AppWarnings createAppWarnings(
853 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
854 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
855 }
856
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700857 public void setWindowManager(WindowManagerService wm) {
858 synchronized (mGlobalLock) {
859 mWindowManager = wm;
860 mLockTaskController.setWindowManager(wm);
861 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800862 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700863 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
867 synchronized (mGlobalLock) {
868 mUsageStatsInternal = usageStatsManager;
869 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700870 }
871
Wale Ogunwalef6733932018-06-27 05:14:34 -0700872 UserManagerService getUserManager() {
873 if (mUserManager == null) {
874 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
875 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
876 }
877 return mUserManager;
878 }
879
880 AppOpsService getAppOpsService() {
881 if (mAppOpsService == null) {
882 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
883 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
884 }
885 return mAppOpsService;
886 }
887
888 boolean hasUserRestriction(String restriction, int userId) {
889 return getUserManager().hasUserRestriction(restriction, userId);
890 }
891
Michal Karpinski15486842019-04-25 17:33:42 +0100892 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
893 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700894 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100895 if (mode == AppOpsManager.MODE_DEFAULT) {
896 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
897 == PERMISSION_GRANTED;
898 }
899 return mode == AppOpsManager.MODE_ALLOWED;
900 }
901
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700902 @VisibleForTesting
903 protected void setRecentTasks(RecentTasks recentTasks) {
904 mRecentTasks = recentTasks;
905 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700906 }
907
908 RecentTasks getRecentTasks() {
909 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700910 }
911
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700912 ClientLifecycleManager getLifecycleManager() {
913 return mLifecycleManager;
914 }
915
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700916 ActivityStartController getActivityStartController() {
917 return mActivityStartController;
918 }
919
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700920 TaskChangeNotificationController getTaskChangeNotificationController() {
921 return mTaskChangeNotificationController;
922 }
923
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700924 LockTaskController getLockTaskController() {
925 return mLockTaskController;
926 }
927
Yunfan Chen75157d72018-07-27 14:47:21 +0900928 /**
929 * Return the global configuration used by the process corresponding to the input pid. This is
930 * usually the global configuration with some overrides specific to that process.
931 */
932 Configuration getGlobalConfigurationForCallingPid() {
933 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800934 return getGlobalConfigurationForPid(pid);
935 }
936
937 /**
938 * Return the global configuration used by the process corresponding to the given pid.
939 */
940 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 if (pid == MY_PID || pid < 0) {
942 return getGlobalConfiguration();
943 }
944 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100945 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900946 return app != null ? app.getConfiguration() : getGlobalConfiguration();
947 }
948 }
949
950 /**
951 * Return the device configuration info used by the process corresponding to the input pid.
952 * The value is consistent with the global configuration for the process.
953 */
954 @Override
955 public ConfigurationInfo getDeviceConfigurationInfo() {
956 ConfigurationInfo config = new ConfigurationInfo();
957 synchronized (mGlobalLock) {
958 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
959 config.reqTouchScreen = globalConfig.touchscreen;
960 config.reqKeyboardType = globalConfig.keyboard;
961 config.reqNavigation = globalConfig.navigation;
962 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
963 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
964 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
965 }
966 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
967 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
968 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
969 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700970 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900971 }
972 return config;
973 }
974
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700975 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700976 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700977 }
978
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700979 public static final class Lifecycle extends SystemService {
980 private final ActivityTaskManagerService mService;
981
982 public Lifecycle(Context context) {
983 super(context);
984 mService = new ActivityTaskManagerService(context);
985 }
986
987 @Override
988 public void onStart() {
989 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700990 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 }
992
Garfield Tan891146c2018-10-09 12:14:00 -0700993 @Override
994 public void onUnlockUser(int userId) {
995 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800996 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700997 }
998 }
999
1000 @Override
1001 public void onCleanupUser(int userId) {
1002 synchronized (mService.getGlobalLock()) {
1003 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1004 }
1005 }
1006
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001007 public ActivityTaskManagerService getService() {
1008 return mService;
1009 }
1010 }
1011
1012 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 public final int startActivity(IApplicationThread caller, String callingPackage,
1014 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1015 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1016 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1017 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1018 UserHandle.getCallingUserId());
1019 }
1020
1021 @Override
1022 public final int startActivities(IApplicationThread caller, String callingPackage,
1023 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1024 int userId) {
1025 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001026 enforceNotIsolatedCaller(reason);
1027 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001029 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1030 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1031 reason, null /* originatingPendingIntent */,
1032 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 }
1034
1035 @Override
1036 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1037 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1038 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1039 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1040 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1041 true /*validateIncomingUser*/);
1042 }
1043
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001044 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1046 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1047 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001048 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001050 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1052
1053 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001054 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 .setCaller(caller)
1056 .setCallingPackage(callingPackage)
1057 .setResolvedType(resolvedType)
1058 .setResultTo(resultTo)
1059 .setResultWho(resultWho)
1060 .setRequestCode(requestCode)
1061 .setStartFlags(startFlags)
1062 .setProfilerInfo(profilerInfo)
1063 .setActivityOptions(bOptions)
1064 .setMayWait(userId)
1065 .execute();
1066
1067 }
1068
1069 @Override
1070 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1071 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001072 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1073 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 // Refuse possible leaked file descriptors
1075 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1076 throw new IllegalArgumentException("File descriptors passed in Intent");
1077 }
1078
1079 if (!(target instanceof PendingIntentRecord)) {
1080 throw new IllegalArgumentException("Bad PendingIntent object");
1081 }
1082
1083 PendingIntentRecord pir = (PendingIntentRecord)target;
1084
1085 synchronized (mGlobalLock) {
1086 // If this is coming from the currently resumed activity, it is
1087 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001088 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 if (stack.mResumedActivity != null &&
1090 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001091 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 }
1093 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001094 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 }
1097
1098 @Override
1099 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1100 Bundle bOptions) {
1101 // Refuse possible leaked file descriptors
1102 if (intent != null && intent.hasFileDescriptors()) {
1103 throw new IllegalArgumentException("File descriptors passed in Intent");
1104 }
1105 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1106
1107 synchronized (mGlobalLock) {
1108 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1109 if (r == null) {
1110 SafeActivityOptions.abort(options);
1111 return false;
1112 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001113 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 // The caller is not running... d'oh!
1115 SafeActivityOptions.abort(options);
1116 return false;
1117 }
1118 intent = new Intent(intent);
1119 // The caller is not allowed to change the data.
1120 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1121 // And we are resetting to find the next component...
1122 intent.setComponent(null);
1123
1124 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1125
1126 ActivityInfo aInfo = null;
1127 try {
1128 List<ResolveInfo> resolves =
1129 AppGlobals.getPackageManager().queryIntentActivities(
1130 intent, r.resolvedType,
1131 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1132 UserHandle.getCallingUserId()).getList();
1133
1134 // Look for the original activity in the list...
1135 final int N = resolves != null ? resolves.size() : 0;
1136 for (int i=0; i<N; i++) {
1137 ResolveInfo rInfo = resolves.get(i);
1138 if (rInfo.activityInfo.packageName.equals(r.packageName)
1139 && rInfo.activityInfo.name.equals(r.info.name)) {
1140 // We found the current one... the next matching is
1141 // after it.
1142 i++;
1143 if (i<N) {
1144 aInfo = resolves.get(i).activityInfo;
1145 }
1146 if (debug) {
1147 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1148 + "/" + r.info.name);
1149 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1150 ? "null" : aInfo.packageName + "/" + aInfo.name));
1151 }
1152 break;
1153 }
1154 }
1155 } catch (RemoteException e) {
1156 }
1157
1158 if (aInfo == null) {
1159 // Nobody who is next!
1160 SafeActivityOptions.abort(options);
1161 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1162 return false;
1163 }
1164
1165 intent.setComponent(new ComponentName(
1166 aInfo.applicationInfo.packageName, aInfo.name));
1167 intent.setFlags(intent.getFlags()&~(
1168 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1169 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1170 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1171 FLAG_ACTIVITY_NEW_TASK));
1172
1173 // Okay now we need to start the new activity, replacing the currently running activity.
1174 // This is a little tricky because we want to start the new one as if the current one is
1175 // finished, but not finish the current one first so that there is no flicker.
1176 // And thus...
1177 final boolean wasFinishing = r.finishing;
1178 r.finishing = true;
1179
1180 // Propagate reply information over to the new activity.
1181 final ActivityRecord resultTo = r.resultTo;
1182 final String resultWho = r.resultWho;
1183 final int requestCode = r.requestCode;
1184 r.resultTo = null;
1185 if (resultTo != null) {
1186 resultTo.removeResultsLocked(r, resultWho, requestCode);
1187 }
1188
1189 final long origId = Binder.clearCallingIdentity();
1190 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001191 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001193 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setResolvedType(r.resolvedType)
1195 .setActivityInfo(aInfo)
1196 .setResultTo(resultTo != null ? resultTo.appToken : null)
1197 .setResultWho(resultWho)
1198 .setRequestCode(requestCode)
1199 .setCallingPid(-1)
1200 .setCallingUid(r.launchedFromUid)
1201 .setCallingPackage(r.launchedFromPackage)
1202 .setRealCallingPid(-1)
1203 .setRealCallingUid(r.launchedFromUid)
1204 .setActivityOptions(options)
1205 .execute();
1206 Binder.restoreCallingIdentity(origId);
1207
1208 r.finishing = wasFinishing;
1209 if (res != ActivityManager.START_SUCCESS) {
1210 return false;
1211 }
1212 return true;
1213 }
1214 }
1215
1216 @Override
1217 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1218 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1219 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1220 final WaitResult res = new WaitResult();
1221 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001222 enforceNotIsolatedCaller("startActivityAndWait");
1223 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1224 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001226 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 .setCaller(caller)
1228 .setCallingPackage(callingPackage)
1229 .setResolvedType(resolvedType)
1230 .setResultTo(resultTo)
1231 .setResultWho(resultWho)
1232 .setRequestCode(requestCode)
1233 .setStartFlags(startFlags)
1234 .setActivityOptions(bOptions)
1235 .setMayWait(userId)
1236 .setProfilerInfo(profilerInfo)
1237 .setWaitResult(res)
1238 .execute();
1239 }
1240 return res;
1241 }
1242
1243 @Override
1244 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1245 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1246 int startFlags, Configuration config, Bundle bOptions, int userId) {
1247 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001248 enforceNotIsolatedCaller("startActivityWithConfig");
1249 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1250 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001251 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001252 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001253 .setCaller(caller)
1254 .setCallingPackage(callingPackage)
1255 .setResolvedType(resolvedType)
1256 .setResultTo(resultTo)
1257 .setResultWho(resultWho)
1258 .setRequestCode(requestCode)
1259 .setStartFlags(startFlags)
1260 .setGlobalConfiguration(config)
1261 .setActivityOptions(bOptions)
1262 .setMayWait(userId)
1263 .execute();
1264 }
1265 }
1266
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267
1268 @Override
1269 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1270 int callingUid = Binder.getCallingUid();
1271 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1272 throw new SecurityException("Only the system process can request a permission token, "
1273 + "received request from uid: " + callingUid);
1274 }
1275 IBinder permissionToken = new Binder();
1276 synchronized (mGlobalLock) {
1277 mStartActivitySources.put(permissionToken, delegatorToken);
1278 }
1279
1280 Message expireMsg = PooledLambda.obtainMessage(
1281 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1282 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1283
1284 Message forgetMsg = PooledLambda.obtainMessage(
1285 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1286 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1287
1288 return permissionToken;
1289 }
1290
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 @Override
1292 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1293 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001294 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1295 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001296 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001297 // permission grants) as any app that may launch one of your own activities. So we only
1298 // allow this in two cases:
1299 // 1) The caller is an activity that is part of the core framework, and then only when it
1300 // is running as the system.
1301 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1302 // can only be requested by a system activity, which may then delegate this call to
1303 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 final ActivityRecord sourceRecord;
1305 final int targetUid;
1306 final String targetPackage;
1307 final boolean isResolver;
1308 synchronized (mGlobalLock) {
1309 if (resultTo == null) {
1310 throw new SecurityException("Must be called from an activity");
1311 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001312 final IBinder sourceToken;
1313 if (permissionToken != null) {
1314 // To even attempt to use a permissionToken, an app must also have this signature
1315 // permission.
1316 mAmInternal.enforceCallingPermission(
1317 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1318 "startActivityAsCaller");
1319 // If called with a permissionToken, we want the sourceRecord from the delegator
1320 // activity that requested this token.
1321 sourceToken = mStartActivitySources.remove(permissionToken);
1322 if (sourceToken == null) {
1323 // Invalid permissionToken, check if it recently expired.
1324 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1325 throw new SecurityException("Called with expired permission token: "
1326 + permissionToken);
1327 } else {
1328 throw new SecurityException("Called with invalid permission token: "
1329 + permissionToken);
1330 }
1331 }
1332 } else {
1333 // This method was called directly by the source.
1334 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001336
Wale Ogunwaled32da472018-11-16 07:19:28 -08001337 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338 if (sourceRecord == null) {
1339 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 }
1341 if (sourceRecord.app == null) {
1342 throw new SecurityException("Called without a process attached to activity");
1343 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001344
1345 // Whether called directly or from a delegate, the source activity must be from the
1346 // android package.
1347 if (!sourceRecord.info.packageName.equals("android")) {
1348 throw new SecurityException("Must be called from an activity that is "
1349 + "declared in the android package");
1350 }
1351
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001352 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 // This is still okay, as long as this activity is running under the
1354 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001355 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001357 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 + " must be system uid or original calling uid "
1359 + sourceRecord.launchedFromUid);
1360 }
1361 }
1362 if (ignoreTargetSecurity) {
1363 if (intent.getComponent() == null) {
1364 throw new SecurityException(
1365 "Component must be specified with ignoreTargetSecurity");
1366 }
1367 if (intent.getSelector() != null) {
1368 throw new SecurityException(
1369 "Selector not allowed with ignoreTargetSecurity");
1370 }
1371 }
1372 targetUid = sourceRecord.launchedFromUid;
1373 targetPackage = sourceRecord.launchedFromPackage;
1374 isResolver = sourceRecord.isResolverOrChildActivity();
1375 }
1376
1377 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001378 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 }
1380
1381 // TODO: Switch to user app stacks here.
1382 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001383 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 .setCallingUid(targetUid)
1385 .setCallingPackage(targetPackage)
1386 .setResolvedType(resolvedType)
1387 .setResultTo(resultTo)
1388 .setResultWho(resultWho)
1389 .setRequestCode(requestCode)
1390 .setStartFlags(startFlags)
1391 .setActivityOptions(bOptions)
1392 .setMayWait(userId)
1393 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1394 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001395 // The target may well be in the background, which would normally prevent it
1396 // from starting an activity. Here we definitely want the start to succeed.
1397 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 .execute();
1399 } catch (SecurityException e) {
1400 // XXX need to figure out how to propagate to original app.
1401 // A SecurityException here is generally actually a fault of the original
1402 // calling activity (such as a fairly granting permissions), so propagate it
1403 // back to them.
1404 /*
1405 StringBuilder msg = new StringBuilder();
1406 msg.append("While launching");
1407 msg.append(intent.toString());
1408 msg.append(": ");
1409 msg.append(e.getMessage());
1410 */
1411 throw e;
1412 }
1413 }
1414
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001415 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1416 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1417 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1418 }
1419
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 @Override
1421 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1422 Intent intent, String resolvedType, IVoiceInteractionSession session,
1423 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1424 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 if (session == null || interactor == null) {
1427 throw new NullPointerException("null session or interactor");
1428 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001429 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001431 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 .setCallingUid(callingUid)
1433 .setCallingPackage(callingPackage)
1434 .setResolvedType(resolvedType)
1435 .setVoiceSession(session)
1436 .setVoiceInteractor(interactor)
1437 .setStartFlags(startFlags)
1438 .setProfilerInfo(profilerInfo)
1439 .setActivityOptions(bOptions)
1440 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001441 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .execute();
1443 }
1444
1445 @Override
1446 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1447 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001448 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1449 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001451 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .setCallingUid(callingUid)
1453 .setCallingPackage(callingPackage)
1454 .setResolvedType(resolvedType)
1455 .setActivityOptions(bOptions)
1456 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001457 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .execute();
1459 }
1460
Riddle Hsu609a8e22019-06-27 16:46:29 -06001461 /**
1462 * Start the recents activity to perform the recents animation.
1463 *
1464 * @param intent The intent to start the recents activity.
1465 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1466 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1469 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001472 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 final long origId = Binder.clearCallingIdentity();
1474 try {
1475 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001476 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1477 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001478 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479
1480 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001481 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001482 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001483 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001484 if (recentsAnimationRunner == null) {
1485 anim.preloadRecentsActivity();
1486 } else {
1487 anim.startRecentsActivity(recentsAnimationRunner);
1488 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 }
1490 } finally {
1491 Binder.restoreCallingIdentity(origId);
1492 }
1493 }
1494
1495 @Override
1496 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001497 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001498 "startActivityFromRecents()");
1499
1500 final int callingPid = Binder.getCallingPid();
1501 final int callingUid = Binder.getCallingUid();
1502 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1503 final long origId = Binder.clearCallingIdentity();
1504 try {
1505 synchronized (mGlobalLock) {
1506 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1507 safeOptions);
1508 }
1509 } finally {
1510 Binder.restoreCallingIdentity(origId);
1511 }
1512 }
1513
1514 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001515 * Public API to check if the client is allowed to start an activity on specified display.
1516 *
1517 * If the target display is private or virtual, some restrictions will apply.
1518 *
1519 * @param displayId Target display id.
1520 * @param intent Intent used to launch the activity.
1521 * @param resolvedType The MIME type of the intent.
1522 * @param userId The id of the user for whom the call is made.
1523 * @return {@code true} if a call to start an activity on the target display should succeed and
1524 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1525 */
1526 @Override
1527 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1528 String resolvedType, int userId) {
1529 final int callingUid = Binder.getCallingUid();
1530 final int callingPid = Binder.getCallingPid();
1531 final long origId = Binder.clearCallingIdentity();
1532
1533 try {
1534 // Collect information about the target of the Intent.
1535 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1536 0 /* startFlags */, null /* profilerInfo */, userId,
1537 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1538 UserHandle.USER_NULL));
1539 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1540
1541 synchronized (mGlobalLock) {
1542 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1543 aInfo);
1544 }
1545 } finally {
1546 Binder.restoreCallingIdentity(origId);
1547 }
1548 }
1549
1550 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 * This is the internal entry point for handling Activity.finish().
1552 *
1553 * @param token The Binder token referencing the Activity we want to finish.
1554 * @param resultCode Result code, if any, from this Activity.
1555 * @param resultData Result data (Intent), if any, from this Activity.
1556 * @param finishTask Whether to finish the task associated with this Activity.
1557 *
1558 * @return Returns true if the activity successfully finished, or false if it is still running.
1559 */
1560 @Override
1561 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1562 int finishTask) {
1563 // Refuse possible leaked file descriptors
1564 if (resultData != null && resultData.hasFileDescriptors()) {
1565 throw new IllegalArgumentException("File descriptors passed in Intent");
1566 }
1567
1568 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001569 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 if (r == null) {
1571 return true;
1572 }
1573 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001574 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001575 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 if (rootR == null) {
1577 Slog.w(TAG, "Finishing task with all activities already finished");
1578 }
1579 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1580 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001581 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 return false;
1583 }
1584
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001585 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1586 // We should consolidate.
1587 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001589 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 if (next != null) {
1591 // ask watcher if this is allowed
1592 boolean resumeOK = true;
1593 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001594 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001596 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 Watchdog.getInstance().setActivityController(null);
1598 }
1599
1600 if (!resumeOK) {
1601 Slog.i(TAG, "Not finishing activity because controller resumed");
1602 return false;
1603 }
1604 }
1605 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001606
1607 // note down that the process has finished an activity and is in background activity
1608 // starts grace period
1609 if (r.app != null) {
1610 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1611 }
1612
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001614 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 try {
1616 boolean res;
1617 final boolean finishWithRootActivity =
1618 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1619 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1620 || (finishWithRootActivity && r == rootR)) {
1621 // If requested, remove the task that is associated to this activity only if it
1622 // was the root activity in the task. The result code and data is ignored
1623 // because we don't support returning them across task boundaries. Also, to
1624 // keep backwards compatibility we remove the task from recents when finishing
1625 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001626 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001627 finishWithRootActivity, "finish-activity");
1628 if (!res) {
1629 Slog.i(TAG, "Removing task failed to finish activity");
1630 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001631 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001632 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001633 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001634 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001635 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001636 if (!res) {
1637 Slog.i(TAG, "Failed to finish by app-request");
1638 }
1639 }
1640 return res;
1641 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001642 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 Binder.restoreCallingIdentity(origId);
1644 }
1645 }
1646 }
1647
1648 @Override
1649 public boolean finishActivityAffinity(IBinder token) {
1650 synchronized (mGlobalLock) {
1651 final long origId = Binder.clearCallingIdentity();
1652 try {
1653 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1654 if (r == null) {
1655 return false;
1656 }
1657
1658 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1659 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001660 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 return false;
1662 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001663 r.finishActivityAffinity();
1664 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 } finally {
1666 Binder.restoreCallingIdentity(origId);
1667 }
1668 }
1669 }
1670
1671 @Override
1672 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1673 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001674 try {
1675 WindowProcessController proc = null;
1676 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001677 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001678 ActivityStack stack = ActivityRecord.getStackLocked(token);
1679 if (stack == null) {
1680 return;
1681 }
1682 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1683 false /* fromTimeout */, false /* processPausingActivities */, config);
1684 if (r != null) {
1685 proc = r.app;
1686 }
1687 if (stopProfiling && proc != null) {
1688 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001691 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001692 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001693 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 }
1696
1697 @Override
1698 public final void activityResumed(IBinder token) {
1699 final long origId = Binder.clearCallingIdentity();
1700 synchronized (mGlobalLock) {
1701 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 }
1703 Binder.restoreCallingIdentity(origId);
1704 }
1705
1706 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001707 public final void activityTopResumedStateLost() {
1708 final long origId = Binder.clearCallingIdentity();
1709 synchronized (mGlobalLock) {
1710 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1711 }
1712 Binder.restoreCallingIdentity(origId);
1713 }
1714
1715 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 public final void activityPaused(IBinder token) {
1717 final long origId = Binder.clearCallingIdentity();
1718 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001719 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 ActivityStack stack = ActivityRecord.getStackLocked(token);
1721 if (stack != null) {
1722 stack.activityPausedLocked(token, false);
1723 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001724 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 }
1726 Binder.restoreCallingIdentity(origId);
1727 }
1728
1729 @Override
1730 public final void activityStopped(IBinder token, Bundle icicle,
1731 PersistableBundle persistentState, CharSequence description) {
1732 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1733
1734 // Refuse possible leaked file descriptors
1735 if (icicle != null && icicle.hasFileDescriptors()) {
1736 throw new IllegalArgumentException("File descriptors passed in Bundle");
1737 }
1738
1739 final long origId = Binder.clearCallingIdentity();
1740
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001741 String restartingName = null;
1742 int restartingUid = 0;
1743 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001745 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001746 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001748 if (r.attachedToProcess()
1749 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1750 // The activity was requested to restart from
1751 // {@link #restartActivityProcessIfVisible}.
1752 restartingName = r.app.mName;
1753 restartingUid = r.app.mUid;
1754 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 r.activityStoppedLocked(icicle, persistentState, description);
1756 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 }
1759
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001760 if (restartingName != null) {
1761 // In order to let the foreground activity can be restarted with its saved state from
1762 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1763 // until the activity reports stopped with the state. And the activity record will be
1764 // kept because the record state is restarting, then the activity will be restarted
1765 // immediately if it is still the top one.
1766 mStackSupervisor.removeRestartTimeouts(r);
1767 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1768 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001769 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770
1771 Binder.restoreCallingIdentity(origId);
1772 }
1773
1774 @Override
1775 public final void activityDestroyed(IBinder token) {
1776 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1777 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001778 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001779 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001780 try {
1781 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1782 if (activity != null) {
1783 activity.destroyed("activityDestroyed");
1784 }
1785 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001786 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001787 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 }
1789 }
1790 }
1791
1792 @Override
1793 public final void activityRelaunched(IBinder token) {
1794 final long origId = Binder.clearCallingIdentity();
1795 synchronized (mGlobalLock) {
1796 mStackSupervisor.activityRelaunchedLocked(token);
1797 }
1798 Binder.restoreCallingIdentity(origId);
1799 }
1800
1801 public final void activitySlept(IBinder token) {
1802 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1803
1804 final long origId = Binder.clearCallingIdentity();
1805
1806 synchronized (mGlobalLock) {
1807 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1808 if (r != null) {
1809 mStackSupervisor.activitySleptLocked(r);
1810 }
1811 }
1812
1813 Binder.restoreCallingIdentity(origId);
1814 }
1815
1816 @Override
1817 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1818 synchronized (mGlobalLock) {
1819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r == null) {
1821 return;
1822 }
1823 final long origId = Binder.clearCallingIdentity();
1824 try {
1825 r.setRequestedOrientation(requestedOrientation);
1826 } finally {
1827 Binder.restoreCallingIdentity(origId);
1828 }
1829 }
1830 }
1831
1832 @Override
1833 public int getRequestedOrientation(IBinder token) {
1834 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001835 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1836 return (r != null)
1837 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001838 }
1839 }
1840
1841 @Override
1842 public void setImmersive(IBinder token, boolean immersive) {
1843 synchronized (mGlobalLock) {
1844 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1845 if (r == null) {
1846 throw new IllegalArgumentException();
1847 }
1848 r.immersive = immersive;
1849
1850 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001851 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 }
1855 }
1856 }
1857
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001858 void applyUpdateLockStateLocked(ActivityRecord r) {
1859 // Modifications to the UpdateLock state are done on our handler, outside
1860 // the activity manager's locks. The new state is determined based on the
1861 // state *now* of the relevant activity record. The object is passed to
1862 // the handler solely for logging detail, not to be consulted/modified.
1863 final boolean nextState = r != null && r.immersive;
1864 mH.post(() -> {
1865 if (mUpdateLock.isHeld() != nextState) {
1866 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1867 "Applying new update lock state '" + nextState + "' for " + r);
1868 if (nextState) {
1869 mUpdateLock.acquire();
1870 } else {
1871 mUpdateLock.release();
1872 }
1873 }
1874 });
1875 }
1876
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 @Override
1878 public boolean isImmersive(IBinder token) {
1879 synchronized (mGlobalLock) {
1880 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1881 if (r == null) {
1882 throw new IllegalArgumentException();
1883 }
1884 return r.immersive;
1885 }
1886 }
1887
1888 @Override
1889 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001890 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001892 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 return (r != null) ? r.immersive : false;
1894 }
1895 }
1896
1897 @Override
1898 public void overridePendingTransition(IBinder token, String packageName,
1899 int enterAnim, int exitAnim) {
1900 synchronized (mGlobalLock) {
1901 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1902 if (self == null) {
1903 return;
1904 }
1905
1906 final long origId = Binder.clearCallingIdentity();
1907
1908 if (self.isState(
1909 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001910 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001911 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
1913
1914 Binder.restoreCallingIdentity(origId);
1915 }
1916 }
1917
1918 @Override
1919 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001922 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 if (r == null) {
1924 return ActivityManager.COMPAT_MODE_UNKNOWN;
1925 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001926 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 }
1929
1930 @Override
1931 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001933 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001936 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 if (r == null) {
1938 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1939 return;
1940 }
1941 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001942 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001943 }
1944 }
1945
1946 @Override
1947 public int getLaunchedFromUid(IBinder activityToken) {
1948 ActivityRecord srec;
1949 synchronized (mGlobalLock) {
1950 srec = ActivityRecord.forTokenLocked(activityToken);
1951 }
1952 if (srec == null) {
1953 return -1;
1954 }
1955 return srec.launchedFromUid;
1956 }
1957
1958 @Override
1959 public String getLaunchedFromPackage(IBinder activityToken) {
1960 ActivityRecord srec;
1961 synchronized (mGlobalLock) {
1962 srec = ActivityRecord.forTokenLocked(activityToken);
1963 }
1964 if (srec == null) {
1965 return null;
1966 }
1967 return srec.launchedFromPackage;
1968 }
1969
1970 @Override
1971 public boolean convertFromTranslucent(IBinder token) {
1972 final long origId = Binder.clearCallingIdentity();
1973 try {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1976 if (r == null) {
1977 return false;
1978 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001979 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 }
1981 } finally {
1982 Binder.restoreCallingIdentity(origId);
1983 }
1984 }
1985
1986 @Override
1987 public boolean convertToTranslucent(IBinder token, Bundle options) {
1988 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1989 final long origId = Binder.clearCallingIdentity();
1990 try {
1991 synchronized (mGlobalLock) {
1992 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1993 if (r == null) {
1994 return false;
1995 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001996 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 int index = task.mActivities.lastIndexOf(r);
1998 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001999 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2001 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002002 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(origId);
2006 }
2007 }
2008
2009 @Override
2010 public void notifyActivityDrawn(IBinder token) {
2011 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2012 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002013 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002015 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018 }
2019
2020 @Override
2021 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2022 synchronized (mGlobalLock) {
2023 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2024 if (r == null) {
2025 return;
2026 }
2027 r.reportFullyDrawnLocked(restoredFromBundle);
2028 }
2029 }
2030
2031 @Override
2032 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2033 synchronized (mGlobalLock) {
2034 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2035 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2036 return stack.mDisplayId;
2037 }
2038 return DEFAULT_DISPLAY;
2039 }
2040 }
2041
2042 @Override
2043 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002044 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 long ident = Binder.clearCallingIdentity();
2046 try {
2047 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002048 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002050 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 }
2052 return null;
2053 }
2054 } finally {
2055 Binder.restoreCallingIdentity(ident);
2056 }
2057 }
2058
2059 @Override
2060 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002061 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2063 final long callingId = Binder.clearCallingIdentity();
2064 try {
2065 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002066 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 if (stack == null) {
2068 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2069 return;
2070 }
2071 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002072 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002073 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 }
2075 }
2076 } finally {
2077 Binder.restoreCallingIdentity(callingId);
2078 }
2079 }
2080
2081 @Override
2082 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002083 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2085 final long callingId = Binder.clearCallingIdentity();
2086 try {
2087 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002088 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002089 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 if (task == null) {
2091 return;
2092 }
2093 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002094 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002095 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 }
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(callingId);
2100 }
2101 }
2102
2103 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002104 public void restartActivityProcessIfVisible(IBinder activityToken) {
2105 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2106 final long callingId = Binder.clearCallingIdentity();
2107 try {
2108 synchronized (mGlobalLock) {
2109 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2110 if (r == null) {
2111 return;
2112 }
2113 r.restartProcessIfVisible();
2114 }
2115 } finally {
2116 Binder.restoreCallingIdentity(callingId);
2117 }
2118 }
2119
2120 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002122 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 synchronized (mGlobalLock) {
2124 final long ident = Binder.clearCallingIdentity();
2125 try {
2126 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2127 "remove-task");
2128 } finally {
2129 Binder.restoreCallingIdentity(ident);
2130 }
2131 }
2132 }
2133
2134 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002135 public void removeAllVisibleRecentTasks() {
2136 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2137 synchronized (mGlobalLock) {
2138 final long ident = Binder.clearCallingIdentity();
2139 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002140 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002141 } finally {
2142 Binder.restoreCallingIdentity(ident);
2143 }
2144 }
2145 }
2146
2147 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002148 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2149 synchronized (mGlobalLock) {
2150 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2151 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002152 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 }
2154 }
2155 return false;
2156 }
2157
2158 @Override
2159 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2160 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002161
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002162 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2164 if (r != null) {
2165 return r.getActivityStack().navigateUpToLocked(
2166 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002167 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002168 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002169 }
2170 }
2171
2172 /**
2173 * Attempts to move a task backwards in z-order (the order of activities within the task is
2174 * unchanged).
2175 *
2176 * There are several possible results of this call:
2177 * - if the task is locked, then we will show the lock toast
2178 * - if there is a task behind the provided task, then that task is made visible and resumed as
2179 * this task is moved to the back
2180 * - otherwise, if there are no other tasks in the stack:
2181 * - if this task is in the pinned stack, then we remove the stack completely, which will
2182 * have the effect of moving the task to the top or bottom of the fullscreen stack
2183 * (depending on whether it is visible)
2184 * - otherwise, we simply return home and hide this task
2185 *
2186 * @param token A reference to the activity we wish to move
2187 * @param nonRoot If false then this only works if the activity is the root
2188 * of a task; if true it will work for any activity in a task.
2189 * @return Returns true if the move completed, false if not.
2190 */
2191 @Override
2192 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 synchronized (mGlobalLock) {
2195 final long origId = Binder.clearCallingIdentity();
2196 try {
2197 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002198 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 if (task != null) {
2200 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2201 }
2202 } finally {
2203 Binder.restoreCallingIdentity(origId);
2204 }
2205 }
2206 return false;
2207 }
2208
2209 @Override
2210 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002211 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 long ident = Binder.clearCallingIdentity();
2213 Rect rect = new Rect();
2214 try {
2215 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002216 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2218 if (task == null) {
2219 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2220 return rect;
2221 }
2222 if (task.getStack() != null) {
2223 // Return the bounds from window manager since it will be adjusted for various
2224 // things like the presense of a docked stack for tasks that aren't resizeable.
2225 task.getWindowContainerBounds(rect);
2226 } else {
2227 // Task isn't in window manager yet since it isn't associated with a stack.
2228 // Return the persist value from activity manager
2229 if (!task.matchParentBounds()) {
2230 rect.set(task.getBounds());
2231 } else if (task.mLastNonFullscreenBounds != null) {
2232 rect.set(task.mLastNonFullscreenBounds);
2233 }
2234 }
2235 }
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
2239 return rect;
2240 }
2241
2242 @Override
2243 public ActivityManager.TaskDescription getTaskDescription(int id) {
2244 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002245 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002247 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2249 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002250 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 }
2252 }
2253 return null;
2254 }
2255
2256 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2258 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2259 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2260 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2261 return;
2262 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002263 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002264 synchronized (mGlobalLock) {
2265 final long ident = Binder.clearCallingIdentity();
2266 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002267 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002268 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002269 if (task == null) {
2270 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2271 return;
2272 }
2273
2274 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2275 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2276
2277 if (!task.isActivityTypeStandardOrUndefined()) {
2278 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2279 + " non-standard task " + taskId + " to windowing mode="
2280 + windowingMode);
2281 }
2282
2283 final ActivityStack stack = task.getStack();
2284 if (toTop) {
2285 stack.moveToFront("setTaskWindowingMode", task);
2286 }
2287 stack.setWindowingMode(windowingMode);
2288 } finally {
2289 Binder.restoreCallingIdentity(ident);
2290 }
2291 }
2292 }
2293
2294 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 ActivityRecord r = getCallingRecordLocked(token);
2298 return r != null ? r.info.packageName : null;
2299 }
2300 }
2301
2302 @Override
2303 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002304 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305 ActivityRecord r = getCallingRecordLocked(token);
2306 return r != null ? r.intent.getComponent() : null;
2307 }
2308 }
2309
2310 private ActivityRecord getCallingRecordLocked(IBinder token) {
2311 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2312 if (r == null) {
2313 return null;
2314 }
2315 return r.resultTo;
2316 }
2317
2318 @Override
2319 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002320 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321
2322 synchronized (mGlobalLock) {
2323 final long origId = Binder.clearCallingIdentity();
2324 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002325 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002326 } finally {
2327 Binder.restoreCallingIdentity(origId);
2328 }
2329 }
2330 }
2331
Mark Renouf446251d2019-04-26 10:22:41 -04002332 @Override
2333 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2334 synchronized (mGlobalLock) {
2335 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2336 if (r == null) {
2337 return;
2338 }
2339 ActivityStack stack = r.getActivityStack();
2340 if (stack != null && stack.isSingleTaskInstance()) {
2341 // Single-task stacks are used for activities which are presented in floating
2342 // windows above full screen activities. Instead of directly finishing the
2343 // task, a task change listener is used to notify SystemUI so the action can be
2344 // handled specially.
2345 final TaskRecord task = r.getTaskRecord();
2346 mTaskChangeNotificationController
2347 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2348 } else {
2349 try {
2350 callback.requestFinish();
2351 } catch (RemoteException e) {
2352 Slog.e(TAG, "Failed to invoke request finish callback", e);
2353 }
2354 }
2355 }
2356 }
2357
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358 /**
2359 * TODO: Add mController hook
2360 */
2361 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2363 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002364 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365
2366 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2367 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2369 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 }
2371 }
2372
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2374 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002376
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 final int callingPid = Binder.getCallingPid();
2378 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002379 if (!isSameApp(callingUid, callingPackage)) {
2380 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2381 + Binder.getCallingPid() + " as package " + callingPackage;
2382 Slog.w(TAG, msg);
2383 throw new SecurityException(msg);
2384 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002385 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 SafeActivityOptions.abort(options);
2387 return;
2388 }
2389 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002390 WindowProcessController callerApp = null;
2391 if (appThread != null) {
2392 callerApp = getProcessController(appThread);
2393 }
2394 final ActivityStarter starter = getActivityStartController().obtainStarter(
2395 null /* intent */, "moveTaskToFront");
2396 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2397 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002398 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 return;
2400 }
2401 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002403 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 if (task == null) {
2405 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002406 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 return;
2408 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002409 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002411 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 return;
2413 }
2414 ActivityOptions realOptions = options != null
2415 ? options.getOptions(mStackSupervisor)
2416 : null;
2417 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2418 false /* forceNonResizable */);
2419
2420 final ActivityRecord topActivity = task.getTopActivity();
2421 if (topActivity != null) {
2422
2423 // We are reshowing a task, use a starting window to hide the initial draw delay
2424 // so the transition can start earlier.
2425 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2426 true /* taskSwitch */, fromRecents);
2427 }
2428 } finally {
2429 Binder.restoreCallingIdentity(origId);
2430 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 }
2432
Ricky Waiaca8a772019-04-04 16:01:06 +01002433 /**
2434 * Return true if callingUid is system, or packageName belongs to that callingUid.
2435 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002436 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002437 try {
2438 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2439 if (packageName == null) {
2440 return false;
2441 }
2442 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2443 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2444 UserHandle.getUserId(callingUid));
2445 return UserHandle.isSameApp(callingUid, uid);
2446 }
2447 } catch (RemoteException e) {
2448 // Should not happen
2449 }
2450 return true;
2451 }
2452
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002453 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2454 int callingPid, int callingUid, String name) {
2455 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2456 return true;
2457 }
2458
2459 if (getRecentTasks().isCallerRecents(sourceUid)) {
2460 return true;
2461 }
2462
2463 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2464 if (perm == PackageManager.PERMISSION_GRANTED) {
2465 return true;
2466 }
2467 if (checkAllowAppSwitchUid(sourceUid)) {
2468 return true;
2469 }
2470
2471 // If the actual IPC caller is different from the logical source, then
2472 // also see if they are allowed to control app switches.
2473 if (callingUid != -1 && callingUid != sourceUid) {
2474 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2475 if (perm == PackageManager.PERMISSION_GRANTED) {
2476 return true;
2477 }
2478 if (checkAllowAppSwitchUid(callingUid)) {
2479 return true;
2480 }
2481 }
2482
2483 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2484 return false;
2485 }
2486
2487 private boolean checkAllowAppSwitchUid(int uid) {
2488 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2489 if (types != null) {
2490 for (int i = types.size() - 1; i >= 0; i--) {
2491 if (types.valueAt(i).intValue() == uid) {
2492 return true;
2493 }
2494 }
2495 }
2496 return false;
2497 }
2498
2499 @Override
2500 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2501 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2502 "setActivityController()");
2503 synchronized (mGlobalLock) {
2504 mController = controller;
2505 mControllerIsAMonkey = imAMonkey;
2506 Watchdog.getInstance().setActivityController(controller);
2507 }
2508 }
2509
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002510 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 synchronized (mGlobalLock) {
2512 return mController != null && mControllerIsAMonkey;
2513 }
2514 }
2515
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 @Override
2517 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2518 synchronized (mGlobalLock) {
2519 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2520 }
2521 }
2522
2523 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002524 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2525 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2526 }
2527
2528 @Override
2529 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2530 @WindowConfiguration.ActivityType int ignoreActivityType,
2531 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2532 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002533 final int callingPid = Binder.getCallingPid();
2534 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002535 final int[] profileIds = getUserManager().getProfileIds(
2536 UserHandle.getUserId(callingUid), true);
2537 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2538 for (int i = 0; i < profileIds.length; i++) {
2539 callingProfileIds.add(profileIds[i]);
2540 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002541 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2542
2543 synchronized (mGlobalLock) {
2544 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2545
Nicholas Sauer0259e532019-08-30 08:24:55 -07002546 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002547 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002548 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 }
2550
2551 return list;
2552 }
2553
2554 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002555 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2556 synchronized (mGlobalLock) {
2557 final long origId = Binder.clearCallingIdentity();
2558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2559 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002560 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561 }
2562 Binder.restoreCallingIdentity(origId);
2563 }
2564 }
2565
2566 @Override
2567 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002568 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569 ActivityStack stack = ActivityRecord.getStackLocked(token);
2570 if (stack != null) {
2571 return stack.willActivityBeVisibleLocked(token);
2572 }
2573 return false;
2574 }
2575 }
2576
2577 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002579 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 synchronized (mGlobalLock) {
2581 final long ident = Binder.clearCallingIdentity();
2582 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002583 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002584 if (task == null) {
2585 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2586 return;
2587 }
2588
2589 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2590 + " to stackId=" + stackId + " toTop=" + toTop);
2591
Wale Ogunwaled32da472018-11-16 07:19:28 -08002592 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 if (stack == null) {
2594 throw new IllegalStateException(
2595 "moveTaskToStack: No stack for stackId=" + stackId);
2596 }
2597 if (!stack.isActivityTypeStandardOrUndefined()) {
2598 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2599 + taskId + " to stack " + stackId);
2600 }
2601 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002602 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2604 }
2605 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2606 "moveTaskToStack");
2607 } finally {
2608 Binder.restoreCallingIdentity(ident);
2609 }
2610 }
2611 }
2612
2613 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002614 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2615 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616
2617 final long ident = Binder.clearCallingIdentity();
2618 try {
2619 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002620 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2621 if (stack == null) {
2622 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2623 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002625 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2626 throw new IllegalArgumentException("Stack: " + stackId
2627 + " doesn't support animated resize.");
2628 }
2629 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2630 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(ident);
2634 }
2635 }
2636
wilsonshih5c4cf522019-01-25 09:03:47 +08002637 @Override
2638 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2639 int animationDuration) {
2640 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2641
2642 final long ident = Binder.clearCallingIdentity();
2643 try {
2644 synchronized (mGlobalLock) {
2645 if (xOffset == 0 && yOffset == 0) {
2646 return;
2647 }
2648 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2649 if (stack == null) {
2650 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2651 return;
2652 }
2653 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2654 throw new IllegalArgumentException("Stack: " + stackId
2655 + " doesn't support animated resize.");
2656 }
2657 final Rect destBounds = new Rect();
2658 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002659 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002660 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2661 return;
2662 }
2663 destBounds.offset(xOffset, yOffset);
2664 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2665 animationDuration, false /* fromFullscreen */);
2666 }
2667 } finally {
2668 Binder.restoreCallingIdentity(ident);
2669 }
2670 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002671 /**
2672 * Moves the specified task to the primary-split-screen stack.
2673 *
2674 * @param taskId Id of task to move.
2675 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2676 * exist already. See
2677 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2678 * and
2679 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2680 * @param toTop If the task and stack should be moved to the top.
2681 * @param animate Whether we should play an animation for the moving the task.
2682 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2683 * stack. Pass {@code null} to use default bounds.
2684 * @param showRecents If the recents activity should be shown on the other side of the task
2685 * going into split-screen mode.
2686 */
2687 @Override
2688 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2689 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002690 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 "setTaskWindowingModeSplitScreenPrimary()");
2692 synchronized (mGlobalLock) {
2693 final long ident = Binder.clearCallingIdentity();
2694 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002695 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002696 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002697 if (task == null) {
2698 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2699 return false;
2700 }
2701 if (DEBUG_STACK) Slog.d(TAG_STACK,
2702 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2703 + " to createMode=" + createMode + " toTop=" + toTop);
2704 if (!task.isActivityTypeStandardOrUndefined()) {
2705 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2706 + " non-standard task " + taskId + " to split-screen windowing mode");
2707 }
2708
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002709 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 final int windowingMode = task.getWindowingMode();
2711 final ActivityStack stack = task.getStack();
2712 if (toTop) {
2713 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2714 }
2715 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002716 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2717 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 return windowingMode != task.getWindowingMode();
2719 } finally {
2720 Binder.restoreCallingIdentity(ident);
2721 }
2722 }
2723 }
2724
2725 /**
2726 * Removes stacks in the input windowing modes from the system if they are of activity type
2727 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2728 */
2729 @Override
2730 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002731 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 "removeStacksInWindowingModes()");
2733
2734 synchronized (mGlobalLock) {
2735 final long ident = Binder.clearCallingIdentity();
2736 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002737 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 } finally {
2739 Binder.restoreCallingIdentity(ident);
2740 }
2741 }
2742 }
2743
2744 @Override
2745 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002747 "removeStacksWithActivityTypes()");
2748
2749 synchronized (mGlobalLock) {
2750 final long ident = Binder.clearCallingIdentity();
2751 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002752 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002753 } finally {
2754 Binder.restoreCallingIdentity(ident);
2755 }
2756 }
2757 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758
2759 @Override
2760 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2761 int userId) {
2762 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002763 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2764 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002766 final boolean detailed = checkGetTasksPermission(
2767 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2768 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 == PackageManager.PERMISSION_GRANTED;
2770
2771 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002772 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 callingUid);
2774 }
2775 }
2776
2777 @Override
2778 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 long ident = Binder.clearCallingIdentity();
2781 try {
2782 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002783 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 }
2785 } finally {
2786 Binder.restoreCallingIdentity(ident);
2787 }
2788 }
2789
2790 @Override
2791 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 long ident = Binder.clearCallingIdentity();
2794 try {
2795 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002796 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(ident);
2800 }
2801 }
2802
2803 @Override
2804 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 final long callingUid = Binder.getCallingUid();
2807 final long origId = Binder.clearCallingIdentity();
2808 try {
2809 synchronized (mGlobalLock) {
2810 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002811 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2813 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2814 }
2815 } finally {
2816 Binder.restoreCallingIdentity(origId);
2817 }
2818 }
2819
2820 @Override
2821 public void startLockTaskModeByToken(IBinder token) {
2822 synchronized (mGlobalLock) {
2823 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2824 if (r == null) {
2825 return;
2826 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002827 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 }
2829 }
2830
2831 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002832 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002833 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002834 // This makes inner call to look as if it was initiated by system.
2835 long ident = Binder.clearCallingIdentity();
2836 try {
2837 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002838 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002839 MATCH_TASK_IN_STACKS_ONLY);
2840 if (task == null) {
2841 return;
2842 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843
2844 // When starting lock task mode the stack must be in front and focused
2845 task.getStack().moveToFront("startSystemLockTaskMode");
2846 startLockTaskModeLocked(task, true /* isSystemCaller */);
2847 }
2848 } finally {
2849 Binder.restoreCallingIdentity(ident);
2850 }
2851 }
2852
2853 @Override
2854 public void stopLockTaskModeByToken(IBinder token) {
2855 synchronized (mGlobalLock) {
2856 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2857 if (r == null) {
2858 return;
2859 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002860 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002861 }
2862 }
2863
2864 /**
2865 * This API should be called by SystemUI only when user perform certain action to dismiss
2866 * lock task mode. We should only dismiss pinned lock task mode in this case.
2867 */
2868 @Override
2869 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002870 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002871 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2872 }
2873
2874 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2875 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2876 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2877 return;
2878 }
2879
Wale Ogunwaled32da472018-11-16 07:19:28 -08002880 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 if (stack == null || task != stack.topTask()) {
2882 throw new IllegalArgumentException("Invalid task, not in foreground");
2883 }
2884
2885 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2886 // system or a specific app.
2887 // * System-initiated requests will only start the pinned mode (screen pinning)
2888 // * App-initiated requests
2889 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2890 // - will start the pinned mode, otherwise
2891 final int callingUid = Binder.getCallingUid();
2892 long ident = Binder.clearCallingIdentity();
2893 try {
2894 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002895 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002897 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 } finally {
2899 Binder.restoreCallingIdentity(ident);
2900 }
2901 }
2902
2903 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2904 final int callingUid = Binder.getCallingUid();
2905 long ident = Binder.clearCallingIdentity();
2906 try {
2907 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002908 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 }
2910 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2911 // task and jumping straight into a call in the case of emergency call back.
2912 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2913 if (tm != null) {
2914 tm.showInCallScreen(false);
2915 }
2916 } finally {
2917 Binder.restoreCallingIdentity(ident);
2918 }
2919 }
2920
2921 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002922 public void updateLockTaskPackages(int userId, String[] packages) {
2923 final int callingUid = Binder.getCallingUid();
2924 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2925 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2926 "updateLockTaskPackages()");
2927 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002928 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002929 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2930 + Arrays.toString(packages));
2931 getLockTaskController().updateLockTaskPackages(userId, packages);
2932 }
2933 }
2934
2935 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 public boolean isInLockTaskMode() {
2937 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2938 }
2939
2940 @Override
2941 public int getLockTaskModeState() {
2942 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002943 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 }
2945 }
2946
2947 @Override
2948 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2949 synchronized (mGlobalLock) {
2950 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2951 if (r != null) {
2952 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002953 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002955 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957 }
2958 }
2959
2960 @Override
2961 public Bundle getActivityOptions(IBinder token) {
2962 final long origId = Binder.clearCallingIdentity();
2963 try {
2964 synchronized (mGlobalLock) {
2965 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2966 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002967 final ActivityOptions activityOptions = r.takeOptionsLocked(
2968 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 return activityOptions == null ? null : activityOptions.toBundle();
2970 }
2971 return null;
2972 }
2973 } finally {
2974 Binder.restoreCallingIdentity(origId);
2975 }
2976 }
2977
2978 @Override
2979 public List<IBinder> getAppTasks(String callingPackage) {
2980 int callingUid = Binder.getCallingUid();
2981 long ident = Binder.clearCallingIdentity();
2982 try {
2983 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002984 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 }
2986 } finally {
2987 Binder.restoreCallingIdentity(ident);
2988 }
2989 }
2990
2991 @Override
2992 public void finishVoiceTask(IVoiceInteractionSession session) {
2993 synchronized (mGlobalLock) {
2994 final long origId = Binder.clearCallingIdentity();
2995 try {
2996 // TODO: VI Consider treating local voice interactions and voice tasks
2997 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002998 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 } finally {
3000 Binder.restoreCallingIdentity(origId);
3001 }
3002 }
3003
3004 }
3005
3006 @Override
3007 public boolean isTopOfTask(IBinder token) {
3008 synchronized (mGlobalLock) {
3009 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003010 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 }
3012 }
3013
3014 @Override
3015 public void notifyLaunchTaskBehindComplete(IBinder token) {
3016 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3017 }
3018
3019 @Override
3020 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003021 mH.post(() -> {
3022 synchronized (mGlobalLock) {
3023 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003024 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003025 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003026 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003027 } catch (RemoteException e) {
3028 }
3029 }
3030 }
3031
3032 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 }
3034
3035 /** Called from an app when assist data is ready. */
3036 @Override
3037 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3038 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003039 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 synchronized (pae) {
3041 pae.result = extras;
3042 pae.structure = structure;
3043 pae.content = content;
3044 if (referrer != null) {
3045 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3046 }
3047 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003048 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003049 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003050 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 structure.setHomeActivity(pae.isHome);
3052 }
3053 pae.haveResult = true;
3054 pae.notifyAll();
3055 if (pae.intent == null && pae.receiver == null) {
3056 // Caller is just waiting for the result.
3057 return;
3058 }
3059 }
3060 // We are now ready to launch the assist activity.
3061 IAssistDataReceiver sendReceiver = null;
3062 Bundle sendBundle = null;
3063 synchronized (mGlobalLock) {
3064 buildAssistBundleLocked(pae, extras);
3065 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 if (!exists) {
3068 // Timed out.
3069 return;
3070 }
3071
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003072 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 // Caller wants result sent back to them.
3074 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003075 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003076 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003077 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3078 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3080 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3081 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3082 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3083 }
3084 }
3085 if (sendReceiver != null) {
3086 try {
3087 sendReceiver.onHandleAssistData(sendBundle);
3088 } catch (RemoteException e) {
3089 }
3090 return;
3091 }
3092
3093 final long ident = Binder.clearCallingIdentity();
3094 try {
3095 if (TextUtils.equals(pae.intent.getAction(),
3096 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003097 // Start voice interaction through VoiceInteractionManagerService.
3098 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3099 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 } else {
3101 pae.intent.replaceExtras(pae.extras);
3102 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3103 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3104 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003105 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003106
3107 try {
3108 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3109 } catch (ActivityNotFoundException e) {
3110 Slog.w(TAG, "No activity to handle assist action.", e);
3111 }
3112 }
3113 } finally {
3114 Binder.restoreCallingIdentity(ident);
3115 }
3116 }
3117
3118 @Override
3119 public int addAppTask(IBinder activityToken, Intent intent,
3120 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3121 final int callingUid = Binder.getCallingUid();
3122 final long callingIdent = Binder.clearCallingIdentity();
3123
3124 try {
3125 synchronized (mGlobalLock) {
3126 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3127 if (r == null) {
3128 throw new IllegalArgumentException("Activity does not exist; token="
3129 + activityToken);
3130 }
3131 ComponentName comp = intent.getComponent();
3132 if (comp == null) {
3133 throw new IllegalArgumentException("Intent " + intent
3134 + " must specify explicit component");
3135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003136 if (thumbnail.getWidth() != mThumbnailWidth
3137 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 throw new IllegalArgumentException("Bad thumbnail size: got "
3139 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003140 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 }
3142 if (intent.getSelector() != null) {
3143 intent.setSelector(null);
3144 }
3145 if (intent.getSourceBounds() != null) {
3146 intent.setSourceBounds(null);
3147 }
3148 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3149 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3150 // The caller has added this as an auto-remove task... that makes no
3151 // sense, so turn off auto-remove.
3152 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3153 }
3154 }
3155 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3156 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3157 if (ainfo.applicationInfo.uid != callingUid) {
3158 throw new SecurityException(
3159 "Can't add task for another application: target uid="
3160 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3161 }
3162
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003163 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003165 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003167 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 // The app has too many tasks already and we can't add any more
3169 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3170 return INVALID_TASK_ID;
3171 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003172 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173
3174 // TODO: Send the thumbnail to WM to store it.
3175
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003176 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 }
3178 } finally {
3179 Binder.restoreCallingIdentity(callingIdent);
3180 }
3181 }
3182
3183 @Override
3184 public Point getAppTaskThumbnailSize() {
3185 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 }
3188 }
3189
3190 @Override
3191 public void setTaskResizeable(int taskId, int resizeableMode) {
3192 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003193 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3195 if (task == null) {
3196 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3197 return;
3198 }
3199 task.setResizeMode(resizeableMode);
3200 }
3201 }
3202
3203 @Override
3204 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 long ident = Binder.clearCallingIdentity();
3207 try {
3208 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003209 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003210 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 if (task == null) {
3212 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3213 return;
3214 }
3215 // Place the task in the right stack if it isn't there already based on
3216 // the requested bounds.
3217 // The stack transition logic is:
3218 // - a null bounds on a freeform task moves that task to fullscreen
3219 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3220 // that task to freeform
3221 // - otherwise the task is not moved
3222 ActivityStack stack = task.getStack();
3223 if (!task.getWindowConfiguration().canResizeTask()) {
3224 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3225 }
3226 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3227 stack = stack.getDisplay().getOrCreateStack(
3228 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3229 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3230 stack = stack.getDisplay().getOrCreateStack(
3231 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3232 }
3233
3234 // Reparent the task to the right stack if necessary
3235 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3236 if (stack != task.getStack()) {
3237 // Defer resume until the task is resized below
3238 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3239 DEFER_RESUME, "resizeTask");
3240 preserveWindow = false;
3241 }
3242
3243 // After reparenting (which only resizes the task to the stack bounds), resize the
3244 // task to the actual bounds provided
3245 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3246 }
3247 } finally {
3248 Binder.restoreCallingIdentity(ident);
3249 }
3250 }
3251
3252 @Override
3253 public boolean releaseActivityInstance(IBinder token) {
3254 synchronized (mGlobalLock) {
3255 final long origId = Binder.clearCallingIdentity();
3256 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003257 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3258 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 return false;
3260 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003261 r.destroyImmediately(true /* removeFromApp */, "app-req");
3262 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003263 } finally {
3264 Binder.restoreCallingIdentity(origId);
3265 }
3266 }
3267 }
3268
3269 @Override
3270 public void releaseSomeActivities(IApplicationThread appInt) {
3271 synchronized (mGlobalLock) {
3272 final long origId = Binder.clearCallingIdentity();
3273 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003274 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003275 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 } finally {
3277 Binder.restoreCallingIdentity(origId);
3278 }
3279 }
3280 }
3281
3282 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003283 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003284 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 != PackageManager.PERMISSION_GRANTED) {
3286 throw new SecurityException("Requires permission "
3287 + android.Manifest.permission.DEVICE_POWER);
3288 }
3289
3290 synchronized (mGlobalLock) {
3291 long ident = Binder.clearCallingIdentity();
3292 if (mKeyguardShown != keyguardShowing) {
3293 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003294 final Message msg = PooledLambda.obtainMessage(
3295 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3296 keyguardShowing);
3297 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 }
3299 try {
wilsonshih177261f2019-02-22 12:02:18 +08003300 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 } finally {
3302 Binder.restoreCallingIdentity(ident);
3303 }
3304 }
3305
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003306 mH.post(() -> {
3307 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3308 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3309 }
3310 });
3311 }
3312
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003313 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mH.post(() -> {
3315 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3316 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3317 }
3318 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 }
3320
3321 @Override
3322 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003323 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3324 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325
3326 final File passedIconFile = new File(filePath);
3327 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3328 passedIconFile.getName());
3329 if (!legitIconFile.getPath().equals(filePath)
3330 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3331 throw new IllegalArgumentException("Bad file path: " + filePath
3332 + " passed for userId " + userId);
3333 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003334 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 }
3336
3337 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003338 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003339 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 synchronized (mGlobalLock) {
3341 final long ident = Binder.clearCallingIdentity();
3342 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003343 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 if (stack == null) {
3345 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3346 return;
3347 }
3348 if (!stack.isActivityTypeStandardOrUndefined()) {
3349 throw new IllegalArgumentException(
3350 "Removing non-standard stack is not allowed.");
3351 }
3352 mStackSupervisor.removeStack(stack);
3353 } finally {
3354 Binder.restoreCallingIdentity(ident);
3355 }
3356 }
3357 }
3358
3359 @Override
3360 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362
3363 synchronized (mGlobalLock) {
3364 final long ident = Binder.clearCallingIdentity();
3365 try {
3366 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3367 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003368 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 } finally {
3370 Binder.restoreCallingIdentity(ident);
3371 }
3372 }
3373 }
3374
3375 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003376 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 synchronized (mGlobalLock) {
3378 long ident = Binder.clearCallingIdentity();
3379 try {
3380 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3381 if (r == null) {
3382 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003383 "toggleFreeformWindowingMode: No activity record matching token="
3384 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 }
3386
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003387 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003388 if (stack == null) {
3389 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3390 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392
Yunfan Chend967af82019-01-17 18:30:18 +09003393 if (!stack.inFreeformWindowingMode()
3394 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3395 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3396 + "toggle between fullscreen and freeform.");
3397 }
3398
3399 if (stack.inFreeformWindowingMode()) {
3400 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003401 } else if (!mSizeCompatFreeform) {
3402 throw new IllegalStateException("Size-compat windows are currently not"
3403 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003404 } else if (stack.getParent().inFreeformWindowingMode()) {
3405 // If the window is on a freeform display, set it to undefined. It will be
3406 // resolved to freeform and it can adjust windowing mode when the display mode
3407 // changes in runtime.
3408 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003409 } else {
3410 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3411 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
3415 }
3416 }
3417
3418 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3419 @Override
3420 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003423 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425
3426 /** Unregister a task stack listener so that it stops receiving callbacks. */
3427 @Override
3428 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003431 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 @Override
3435 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3436 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3437 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3438 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3439 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3440 }
3441
3442 @Override
3443 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3444 IBinder activityToken, int flags) {
3445 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3446 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3447 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3448 }
3449
3450 @Override
3451 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3452 Bundle args) {
3453 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3454 true /* focused */, true /* newSessionId */, userHandle, args,
3455 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3456 }
3457
3458 @Override
3459 public Bundle getAssistContextExtras(int requestType) {
3460 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3461 null, null, true /* focused */, true /* newSessionId */,
3462 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3463 if (pae == null) {
3464 return null;
3465 }
3466 synchronized (pae) {
3467 while (!pae.haveResult) {
3468 try {
3469 pae.wait();
3470 } catch (InterruptedException e) {
3471 }
3472 }
3473 }
3474 synchronized (mGlobalLock) {
3475 buildAssistBundleLocked(pae, pae.result);
3476 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003477 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 }
3479 return pae.extras;
3480 }
3481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 /**
3483 * Binder IPC calls go through the public entry point.
3484 * This can be called with or without the global lock held.
3485 */
3486 private static int checkCallingPermission(String permission) {
3487 return checkPermission(
3488 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3489 }
3490
3491 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003492 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003493 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3494 mAmInternal.enforceCallingPermission(permission, func);
3495 }
3496 }
3497
3498 @VisibleForTesting
3499 int checkGetTasksPermission(String permission, int pid, int uid) {
3500 return checkPermission(permission, pid, uid);
3501 }
3502
3503 static int checkPermission(String permission, int pid, int uid) {
3504 if (permission == null) {
3505 return PackageManager.PERMISSION_DENIED;
3506 }
3507 return checkComponentPermission(permission, pid, uid, -1, true);
3508 }
3509
Wale Ogunwale214f3482018-10-04 11:00:47 -07003510 public static int checkComponentPermission(String permission, int pid, int uid,
3511 int owningUid, boolean exported) {
3512 return ActivityManagerService.checkComponentPermission(
3513 permission, pid, uid, owningUid, exported);
3514 }
3515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3517 if (getRecentTasks().isCallerRecents(callingUid)) {
3518 // Always allow the recents component to get tasks
3519 return true;
3520 }
3521
3522 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3523 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3524 if (!allowed) {
3525 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3526 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3527 // Temporary compatibility: some existing apps on the system image may
3528 // still be requesting the old permission and not switched to the new
3529 // one; if so, we'll still allow them full access. This means we need
3530 // to see if they are holding the old permission and are a system app.
3531 try {
3532 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3533 allowed = true;
3534 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3535 + " is using old GET_TASKS but privileged; allowing");
3536 }
3537 } catch (RemoteException e) {
3538 }
3539 }
3540 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3541 + " does not hold REAL_GET_TASKS; limiting output");
3542 }
3543 return allowed;
3544 }
3545
Nicholas Sauer0259e532019-08-30 08:24:55 -07003546 boolean isCrossUserAllowed(int pid, int uid) {
3547 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3548 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3549 }
3550
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3552 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3553 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3554 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003555 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 "enqueueAssistContext()");
3557
3558 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003559 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 if (activity == null) {
3561 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3562 return null;
3563 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003564 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003565 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3566 return null;
3567 }
3568 if (focused) {
3569 if (activityToken != null) {
3570 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3571 if (activity != caller) {
3572 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3573 + " is not current top " + activity);
3574 return null;
3575 }
3576 }
3577 } else {
3578 activity = ActivityRecord.forTokenLocked(activityToken);
3579 if (activity == null) {
3580 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3581 + " couldn't be found");
3582 return null;
3583 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003584 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3586 return null;
3587 }
3588 }
3589
3590 PendingAssistExtras pae;
3591 Bundle extras = new Bundle();
3592 if (args != null) {
3593 extras.putAll(args);
3594 }
3595 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003596 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003597
3598 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3599 userHandle);
3600 pae.isHome = activity.isActivityTypeHome();
3601
3602 // Increment the sessionId if necessary
3603 if (newSessionId) {
3604 mViSessionId++;
3605 }
3606 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3608 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003610 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 } catch (RemoteException e) {
3612 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3613 return null;
3614 }
3615 return pae;
3616 }
3617 }
3618
3619 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3620 if (result != null) {
3621 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3622 }
3623 if (pae.hint != null) {
3624 pae.extras.putBoolean(pae.hint, true);
3625 }
3626 }
3627
3628 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3629 IAssistDataReceiver receiver;
3630 synchronized (mGlobalLock) {
3631 mPendingAssistExtras.remove(pae);
3632 receiver = pae.receiver;
3633 }
3634 if (receiver != null) {
3635 // Caller wants result sent back to them.
3636 Bundle sendBundle = new Bundle();
3637 // At least return the receiver extras
3638 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3639 try {
3640 pae.receiver.onHandleAssistData(sendBundle);
3641 } catch (RemoteException e) {
3642 }
3643 }
3644 }
3645
3646 public class PendingAssistExtras extends Binder implements Runnable {
3647 public final ActivityRecord activity;
3648 public boolean isHome;
3649 public final Bundle extras;
3650 public final Intent intent;
3651 public final String hint;
3652 public final IAssistDataReceiver receiver;
3653 public final int userHandle;
3654 public boolean haveResult = false;
3655 public Bundle result = null;
3656 public AssistStructure structure = null;
3657 public AssistContent content = null;
3658 public Bundle receiverExtras;
3659
3660 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3661 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3662 int _userHandle) {
3663 activity = _activity;
3664 extras = _extras;
3665 intent = _intent;
3666 hint = _hint;
3667 receiver = _receiver;
3668 receiverExtras = _receiverExtras;
3669 userHandle = _userHandle;
3670 }
3671
3672 @Override
3673 public void run() {
3674 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3675 synchronized (this) {
3676 haveResult = true;
3677 notifyAll();
3678 }
3679 pendingAssistExtrasTimedOut(this);
3680 }
3681 }
3682
3683 @Override
3684 public boolean isAssistDataAllowedOnCurrentActivity() {
3685 int userId;
3686 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003687 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003688 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3689 return false;
3690 }
3691
3692 final ActivityRecord activity = focusedStack.getTopActivity();
3693 if (activity == null) {
3694 return false;
3695 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003696 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 }
3698 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3699 }
3700
3701 @Override
3702 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3703 long ident = Binder.clearCallingIdentity();
3704 try {
3705 synchronized (mGlobalLock) {
3706 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003707 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 if (top != caller) {
3709 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3710 + " is not current top " + top);
3711 return false;
3712 }
3713 if (!top.nowVisible) {
3714 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3715 + " is not visible");
3716 return false;
3717 }
3718 }
3719 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3720 token);
3721 } finally {
3722 Binder.restoreCallingIdentity(ident);
3723 }
3724 }
3725
3726 @Override
3727 public boolean isRootVoiceInteraction(IBinder token) {
3728 synchronized (mGlobalLock) {
3729 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3730 if (r == null) {
3731 return false;
3732 }
3733 return r.rootVoiceInteraction;
3734 }
3735 }
3736
Wale Ogunwalef6733932018-06-27 05:14:34 -07003737 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3738 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3739 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3740 if (activityToCallback == null) return;
3741 activityToCallback.setVoiceSessionLocked(voiceSession);
3742
3743 // Inform the activity
3744 try {
3745 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3746 voiceInteractor);
3747 long token = Binder.clearCallingIdentity();
3748 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003749 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003750 } finally {
3751 Binder.restoreCallingIdentity(token);
3752 }
3753 // TODO: VI Should we cache the activity so that it's easier to find later
3754 // rather than scan through all the stacks and activities?
3755 } catch (RemoteException re) {
3756 activityToCallback.clearVoiceSessionLocked();
3757 // TODO: VI Should this terminate the voice session?
3758 }
3759 }
3760
3761 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3762 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3763 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3764 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3765 boolean wasRunningVoice = mRunningVoice != null;
3766 mRunningVoice = session;
3767 if (!wasRunningVoice) {
3768 mVoiceWakeLock.acquire();
3769 updateSleepIfNeededLocked();
3770 }
3771 }
3772 }
3773
3774 void finishRunningVoiceLocked() {
3775 if (mRunningVoice != null) {
3776 mRunningVoice = null;
3777 mVoiceWakeLock.release();
3778 updateSleepIfNeededLocked();
3779 }
3780 }
3781
3782 @Override
3783 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3784 synchronized (mGlobalLock) {
3785 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3786 if (keepAwake) {
3787 mVoiceWakeLock.acquire();
3788 } else {
3789 mVoiceWakeLock.release();
3790 }
3791 }
3792 }
3793 }
3794
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 @Override
3796 public ComponentName getActivityClassForToken(IBinder token) {
3797 synchronized (mGlobalLock) {
3798 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3799 if (r == null) {
3800 return null;
3801 }
3802 return r.intent.getComponent();
3803 }
3804 }
3805
3806 @Override
3807 public String getPackageForToken(IBinder token) {
3808 synchronized (mGlobalLock) {
3809 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3810 if (r == null) {
3811 return null;
3812 }
3813 return r.packageName;
3814 }
3815 }
3816
3817 @Override
3818 public void showLockTaskEscapeMessage(IBinder token) {
3819 synchronized (mGlobalLock) {
3820 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3821 if (r == null) {
3822 return;
3823 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003824 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 }
3826 }
3827
3828 @Override
3829 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003830 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 final long token = Binder.clearCallingIdentity();
3832 try {
3833 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003834 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 }
3836 } finally {
3837 Binder.restoreCallingIdentity(token);
3838 }
3839 }
3840
3841 /**
3842 * Try to place task to provided position. The final position might be different depending on
3843 * current user and stacks state. The task will be moved to target stack if it's currently in
3844 * different stack.
3845 */
3846 @Override
3847 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003848 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 synchronized (mGlobalLock) {
3850 long ident = Binder.clearCallingIdentity();
3851 try {
3852 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3853 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003854 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 if (task == null) {
3856 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3857 + taskId);
3858 }
3859
Wale Ogunwaled32da472018-11-16 07:19:28 -08003860 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861
3862 if (stack == null) {
3863 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3864 + stackId);
3865 }
3866 if (!stack.isActivityTypeStandardOrUndefined()) {
3867 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3868 + " the position of task " + taskId + " in/to non-standard stack");
3869 }
3870
3871 // TODO: Have the callers of this API call a separate reparent method if that is
3872 // what they intended to do vs. having this method also do reparenting.
3873 if (task.getStack() == stack) {
3874 // Change position in current stack.
3875 stack.positionChildAt(task, position);
3876 } else {
3877 // Reparent to new stack.
3878 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3879 !DEFER_RESUME, "positionTaskInStack");
3880 }
3881 } finally {
3882 Binder.restoreCallingIdentity(ident);
3883 }
3884 }
3885 }
3886
3887 @Override
3888 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3889 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3890 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003891 + Arrays.toString(horizontalSizeConfiguration) + " "
3892 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 synchronized (mGlobalLock) {
3894 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3895 if (record == null) {
3896 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3897 + "found for: " + token);
3898 }
3899 record.setSizeConfigurations(horizontalSizeConfiguration,
3900 verticalSizeConfigurations, smallestSizeConfigurations);
3901 }
3902 }
3903
3904 /**
3905 * Dismisses split-screen multi-window mode.
3906 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3907 */
3908 @Override
3909 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3912 final long ident = Binder.clearCallingIdentity();
3913 try {
3914 synchronized (mGlobalLock) {
3915 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003916 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 if (stack == null) {
3918 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3919 return;
3920 }
3921
3922 if (toTop) {
3923 // Caller wants the current split-screen primary stack to be the top stack after
3924 // it goes fullscreen, so move it to the front.
3925 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003926 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003928 // stack after it goes fullscreen, so we move the focus to the top-most
3929 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3931 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3932 if (otherStack != null) {
3933 otherStack.moveToFront("dismissSplitScreenMode_other");
3934 }
3935 }
3936
Evan Rosky10475742018-09-05 19:02:48 -07003937 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 }
3939 } finally {
3940 Binder.restoreCallingIdentity(ident);
3941 }
3942 }
3943
3944 /**
3945 * Dismisses Pip
3946 * @param animate True if the dismissal should be animated.
3947 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3948 * default animation duration should be used.
3949 */
3950 @Override
3951 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003952 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 final long ident = Binder.clearCallingIdentity();
3954 try {
3955 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003956 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003957 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 if (stack == null) {
3959 Slog.w(TAG, "dismissPip: pinned stack not found.");
3960 return;
3961 }
3962 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3963 throw new IllegalArgumentException("Stack: " + stack
3964 + " doesn't support animated resize.");
3965 }
3966 if (animate) {
3967 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3968 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3969 } else {
3970 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3971 }
3972 }
3973 } finally {
3974 Binder.restoreCallingIdentity(ident);
3975 }
3976 }
3977
3978 @Override
3979 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003980 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 synchronized (mGlobalLock) {
3982 mSuppressResizeConfigChanges = suppress;
3983 }
3984 }
3985
3986 /**
3987 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3988 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3989 * activity and clearing the task at the same time.
3990 */
3991 @Override
3992 // TODO: API should just be about changing windowing modes...
3993 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003994 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 "moveTasksToFullscreenStack()");
3996 synchronized (mGlobalLock) {
3997 final long origId = Binder.clearCallingIdentity();
3998 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003999 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 if (stack != null){
4001 if (!stack.isActivityTypeStandardOrUndefined()) {
4002 throw new IllegalArgumentException(
4003 "You can't move tasks from non-standard stacks.");
4004 }
4005 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4006 }
4007 } finally {
4008 Binder.restoreCallingIdentity(origId);
4009 }
4010 }
4011 }
4012
4013 /**
4014 * Moves the top activity in the input stackId to the pinned stack.
4015 *
4016 * @param stackId Id of stack to move the top activity to pinned stack.
4017 * @param bounds Bounds to use for pinned stack.
4018 *
4019 * @return True if the top activity of the input stack was successfully moved to the pinned
4020 * stack.
4021 */
4022 @Override
4023 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 "moveTopActivityToPinnedStack()");
4026 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4029 + "Device doesn't support picture-in-picture mode");
4030 }
4031
4032 long ident = Binder.clearCallingIdentity();
4033 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004034 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 } finally {
4036 Binder.restoreCallingIdentity(ident);
4037 }
4038 }
4039 }
4040
4041 @Override
4042 public boolean isInMultiWindowMode(IBinder token) {
4043 final long origId = Binder.clearCallingIdentity();
4044 try {
4045 synchronized (mGlobalLock) {
4046 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4047 if (r == null) {
4048 return false;
4049 }
4050 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4051 return r.inMultiWindowMode();
4052 }
4053 } finally {
4054 Binder.restoreCallingIdentity(origId);
4055 }
4056 }
4057
4058 @Override
4059 public boolean isInPictureInPictureMode(IBinder token) {
4060 final long origId = Binder.clearCallingIdentity();
4061 try {
4062 synchronized (mGlobalLock) {
4063 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(origId);
4067 }
4068 }
4069
4070 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004071 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4072 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 return false;
4074 }
4075
4076 // If we are animating to fullscreen then we have already dispatched the PIP mode
4077 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004078 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4079 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 }
4081
4082 @Override
4083 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4084 final long origId = Binder.clearCallingIdentity();
4085 try {
4086 synchronized (mGlobalLock) {
4087 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4088 "enterPictureInPictureMode", token, params);
4089
4090 // If the activity is already in picture in picture mode, then just return early
4091 if (isInPictureInPictureMode(r)) {
4092 return true;
4093 }
4094
4095 // Activity supports picture-in-picture, now check that we can enter PiP at this
4096 // point, if it is
4097 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4098 false /* beforeStopping */)) {
4099 return false;
4100 }
4101
4102 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 synchronized (mGlobalLock) {
4104 // Only update the saved args from the args that are set
4105 r.pictureInPictureArgs.copyOnlySet(params);
4106 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4107 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4108 // Adjust the source bounds by the insets for the transition down
4109 final Rect sourceBounds = new Rect(
4110 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004111 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004112 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004113 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004114 stack.setPictureInPictureAspectRatio(aspectRatio);
4115 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004116 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4117 r.info.applicationInfo.uid, r.shortComponentName,
4118 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004119 logPictureInPictureArgs(params);
4120 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 };
4122
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004123 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 // If the keyguard is showing or occluded, then try and dismiss it before
4125 // entering picture-in-picture (this will prompt the user to authenticate if the
4126 // device is currently locked).
4127 dismissKeyguard(token, new KeyguardDismissCallback() {
4128 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004129 public void onDismissSucceeded() {
4130 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 }
4132 }, null /* message */);
4133 } else {
4134 // Enter picture in picture immediately otherwise
4135 enterPipRunnable.run();
4136 }
4137 return true;
4138 }
4139 } finally {
4140 Binder.restoreCallingIdentity(origId);
4141 }
4142 }
4143
4144 @Override
4145 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4146 final long origId = Binder.clearCallingIdentity();
4147 try {
4148 synchronized (mGlobalLock) {
4149 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4150 "setPictureInPictureParams", token, params);
4151
4152 // Only update the saved args from the args that are set
4153 r.pictureInPictureArgs.copyOnlySet(params);
4154 if (r.inPinnedWindowingMode()) {
4155 // If the activity is already in picture-in-picture, update the pinned stack now
4156 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4157 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004158 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 if (!stack.isAnimatingBoundsToFullscreen()) {
4160 stack.setPictureInPictureAspectRatio(
4161 r.pictureInPictureArgs.getAspectRatio());
4162 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4163 }
4164 }
4165 logPictureInPictureArgs(params);
4166 }
4167 } finally {
4168 Binder.restoreCallingIdentity(origId);
4169 }
4170 }
4171
4172 @Override
4173 public int getMaxNumPictureInPictureActions(IBinder token) {
4174 // Currently, this is a static constant, but later, we may change this to be dependent on
4175 // the context of the activity
4176 return 3;
4177 }
4178
4179 private void logPictureInPictureArgs(PictureInPictureParams params) {
4180 if (params.hasSetActions()) {
4181 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4182 params.getActions().size());
4183 }
4184 if (params.hasSetAspectRatio()) {
4185 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4186 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4187 MetricsLogger.action(lm);
4188 }
4189 }
4190
4191 /**
4192 * Checks the state of the system and the activity associated with the given {@param token} to
4193 * verify that picture-in-picture is supported for that activity.
4194 *
4195 * @return the activity record for the given {@param token} if all the checks pass.
4196 */
4197 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4198 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 throw new IllegalStateException(caller
4201 + ": Device doesn't support picture-in-picture mode.");
4202 }
4203
4204 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4205 if (r == null) {
4206 throw new IllegalStateException(caller
4207 + ": Can't find activity for token=" + token);
4208 }
4209
4210 if (!r.supportsPictureInPicture()) {
4211 throw new IllegalStateException(caller
4212 + ": Current activity does not support picture-in-picture.");
4213 }
4214
4215 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004216 && !mWindowManager.isValidPictureInPictureAspectRatio(
4217 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 final float minAspectRatio = mContext.getResources().getFloat(
4219 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4220 final float maxAspectRatio = mContext.getResources().getFloat(
4221 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4222 throw new IllegalArgumentException(String.format(caller
4223 + ": Aspect ratio is too extreme (must be between %f and %f).",
4224 minAspectRatio, maxAspectRatio));
4225 }
4226
4227 // Truncate the number of actions if necessary
4228 params.truncateActions(getMaxNumPictureInPictureActions(token));
4229
4230 return r;
4231 }
4232
4233 @Override
4234 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 synchronized (mGlobalLock) {
4237 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4238 if (r == null) {
4239 throw new IllegalArgumentException("Activity does not exist; token="
4240 + activityToken);
4241 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004242 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 }
4244 }
4245
4246 @Override
4247 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4248 Rect tempDockedTaskInsetBounds,
4249 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 long ident = Binder.clearCallingIdentity();
4252 try {
4253 synchronized (mGlobalLock) {
4254 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4255 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4256 PRESERVE_WINDOWS);
4257 }
4258 } finally {
4259 Binder.restoreCallingIdentity(ident);
4260 }
4261 }
4262
4263 @Override
4264 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 final long ident = Binder.clearCallingIdentity();
4267 try {
4268 synchronized (mGlobalLock) {
4269 mStackSupervisor.setSplitScreenResizing(resizing);
4270 }
4271 } finally {
4272 Binder.restoreCallingIdentity(ident);
4273 }
4274 }
4275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 /**
4277 * Check that we have the features required for VR-related API calls, and throw an exception if
4278 * not.
4279 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004280 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004281 if (!mContext.getPackageManager().hasSystemFeature(
4282 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4283 throw new UnsupportedOperationException("VR mode not supported on this device!");
4284 }
4285 }
4286
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 @Override
4288 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004289 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290
4291 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4292
4293 ActivityRecord r;
4294 synchronized (mGlobalLock) {
4295 r = ActivityRecord.isInStackLocked(token);
4296 }
4297
4298 if (r == null) {
4299 throw new IllegalArgumentException();
4300 }
4301
4302 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004303 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 VrManagerInternal.NO_ERROR) {
4305 return err;
4306 }
4307
4308 // Clear the binder calling uid since this path may call moveToTask().
4309 final long callingId = Binder.clearCallingIdentity();
4310 try {
4311 synchronized (mGlobalLock) {
4312 r.requestedVrComponent = (enabled) ? packageName : null;
4313
4314 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004315 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004316 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 }
4318 return 0;
4319 }
4320 } finally {
4321 Binder.restoreCallingIdentity(callingId);
4322 }
4323 }
4324
4325 @Override
4326 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4327 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4328 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004329 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4331 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4332 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004333 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 || activity.voiceSession != null) {
4335 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4336 return;
4337 }
4338 if (activity.pendingVoiceInteractionStart) {
4339 Slog.w(TAG, "Pending start of voice interaction already.");
4340 return;
4341 }
4342 activity.pendingVoiceInteractionStart = true;
4343 }
4344 LocalServices.getService(VoiceInteractionManagerInternal.class)
4345 .startLocalVoiceInteraction(callingActivity, options);
4346 }
4347
4348 @Override
4349 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .stopLocalVoiceInteraction(callingActivity);
4352 }
4353
4354 @Override
4355 public boolean supportsLocalVoiceInteraction() {
4356 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .supportsLocalVoiceInteraction();
4358 }
4359
4360 /** Notifies all listeners when the pinned stack animation starts. */
4361 @Override
4362 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004363 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 }
4365
4366 /** Notifies all listeners when the pinned stack animation ends. */
4367 @Override
4368 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004369 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371
4372 @Override
4373 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 final long ident = Binder.clearCallingIdentity();
4376 try {
4377 synchronized (mGlobalLock) {
4378 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4379 }
4380 } finally {
4381 Binder.restoreCallingIdentity(ident);
4382 }
4383 }
4384
4385 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388
4389 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004390 if (mWindowManager == null) {
4391 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4392 return false;
4393 }
4394
4395 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
Riddle Hsua0022cd2019-09-09 21:12:41 +08004400 mH.sendMessage(PooledLambda.obtainMessage(
4401 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4402 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403
4404 final long origId = Binder.clearCallingIdentity();
4405 try {
4406 if (values != null) {
4407 Settings.System.clearConfiguration(values);
4408 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004409 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 UserHandle.USER_NULL, false /* deferResume */,
4411 mTmpUpdateConfigurationResult);
4412 return mTmpUpdateConfigurationResult.changes != 0;
4413 } finally {
4414 Binder.restoreCallingIdentity(origId);
4415 }
4416 }
4417 }
4418
4419 @Override
4420 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4421 CharSequence message) {
4422 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4425 }
4426 final long callingId = Binder.clearCallingIdentity();
4427 try {
4428 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004429 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431 } finally {
4432 Binder.restoreCallingIdentity(callingId);
4433 }
4434 }
4435
4436 @Override
4437 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 "cancelTaskWindowTransition()");
4440 final long ident = Binder.clearCallingIdentity();
4441 try {
4442 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004443 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 MATCH_TASK_IN_STACKS_ONLY);
4445 if (task == null) {
4446 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4447 return;
4448 }
4449 task.cancelWindowTransition();
4450 }
4451 } finally {
4452 Binder.restoreCallingIdentity(ident);
4453 }
4454 }
4455
4456 @Override
4457 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 final long ident = Binder.clearCallingIdentity();
4460 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004461 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 } finally {
4463 Binder.restoreCallingIdentity(ident);
4464 }
4465 }
4466
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004467 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4468 boolean restoreFromDisk) {
4469 final TaskRecord task;
4470 synchronized (mGlobalLock) {
4471 task = mRootActivityContainer.anyTaskForId(taskId,
4472 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4473 if (task == null) {
4474 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4475 return null;
4476 }
4477 }
4478 // Don't call this while holding the lock as this operation might hit the disk.
4479 return task.getSnapshot(reducedResolution, restoreFromDisk);
4480 }
4481
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 @Override
4483 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4484 synchronized (mGlobalLock) {
4485 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4486 if (r == null) {
4487 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4488 + token);
4489 return;
4490 }
4491 final long origId = Binder.clearCallingIdentity();
4492 try {
4493 r.setDisablePreviewScreenshots(disable);
4494 } finally {
4495 Binder.restoreCallingIdentity(origId);
4496 }
4497 }
4498 }
4499
4500 /** Return the user id of the last resumed activity. */
4501 @Override
4502 public @UserIdInt
4503 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004504 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4506 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004507 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004510 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 }
4512 }
4513
4514 @Override
4515 public void updateLockTaskFeatures(int userId, int flags) {
4516 final int callingUid = Binder.getCallingUid();
4517 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004518 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004519 "updateLockTaskFeatures()");
4520 }
4521 synchronized (mGlobalLock) {
4522 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4523 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004524 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 }
4526 }
4527
4528 @Override
4529 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4530 synchronized (mGlobalLock) {
4531 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4532 if (r == null) {
4533 return;
4534 }
4535 final long origId = Binder.clearCallingIdentity();
4536 try {
4537 r.setShowWhenLocked(showWhenLocked);
4538 } finally {
4539 Binder.restoreCallingIdentity(origId);
4540 }
4541 }
4542 }
4543
4544 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004545 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4546 synchronized (mGlobalLock) {
4547 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4548 if (r == null) {
4549 return;
4550 }
4551 final long origId = Binder.clearCallingIdentity();
4552 try {
4553 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4554 } finally {
4555 Binder.restoreCallingIdentity(origId);
4556 }
4557 }
4558 }
4559
4560 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4562 synchronized (mGlobalLock) {
4563 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4564 if (r == null) {
4565 return;
4566 }
4567 final long origId = Binder.clearCallingIdentity();
4568 try {
4569 r.setTurnScreenOn(turnScreenOn);
4570 } finally {
4571 Binder.restoreCallingIdentity(origId);
4572 }
4573 }
4574 }
4575
4576 @Override
4577 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004578 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004580 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 synchronized (mGlobalLock) {
4582 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4583 if (r == null) {
4584 return;
4585 }
4586 final long origId = Binder.clearCallingIdentity();
4587 try {
4588 r.registerRemoteAnimations(definition);
4589 } finally {
4590 Binder.restoreCallingIdentity(origId);
4591 }
4592 }
4593 }
4594
4595 @Override
4596 public void registerRemoteAnimationForNextActivityStart(String packageName,
4597 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004598 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004599 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004600 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 synchronized (mGlobalLock) {
4602 final long origId = Binder.clearCallingIdentity();
4603 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004604 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004605 packageName, adapter);
4606 } finally {
4607 Binder.restoreCallingIdentity(origId);
4608 }
4609 }
4610 }
4611
Evan Rosky966759f2019-01-15 10:33:58 -08004612 @Override
4613 public void registerRemoteAnimationsForDisplay(int displayId,
4614 RemoteAnimationDefinition definition) {
4615 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4616 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004617 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004618 synchronized (mGlobalLock) {
4619 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4620 if (display == null) {
4621 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4622 return;
4623 }
4624 final long origId = Binder.clearCallingIdentity();
4625 try {
4626 display.mDisplayContent.registerRemoteAnimations(definition);
4627 } finally {
4628 Binder.restoreCallingIdentity(origId);
4629 }
4630 }
4631 }
4632
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4634 @Override
4635 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4636 synchronized (mGlobalLock) {
4637 final long origId = Binder.clearCallingIdentity();
4638 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004639 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004640 } finally {
4641 Binder.restoreCallingIdentity(origId);
4642 }
4643 }
4644 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004645
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004646 @Override
4647 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004648 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004650 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004651 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004652 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004653 }
4654 }
4655
4656 @Override
4657 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 != PERMISSION_GRANTED) {
4660 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4661 + Binder.getCallingPid()
4662 + ", uid=" + Binder.getCallingUid()
4663 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4664 Slog.w(TAG, msg);
4665 throw new SecurityException(msg);
4666 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004667 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004668 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004669 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004670 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004671 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004672 }
4673 }
4674
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004675 @Override
4676 public void stopAppSwitches() {
4677 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4678 synchronized (mGlobalLock) {
4679 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004680 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004681 mDidAppSwitch = false;
4682 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4683 }
4684 }
4685
4686 @Override
4687 public void resumeAppSwitches() {
4688 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4689 synchronized (mGlobalLock) {
4690 // Note that we don't execute any pending app switches... we will
4691 // let those wait until either the timeout, or the next start
4692 // activity request.
4693 mAppSwitchesAllowedTime = 0;
4694 }
4695 }
4696
Ricky Wai906af482019-06-03 17:25:28 +01004697 long getLastStopAppSwitchesTime() {
4698 return mLastStopAppSwitchesTime;
4699 }
4700
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004701 void onStartActivitySetDidAppSwitch() {
4702 if (mDidAppSwitch) {
4703 // This is the second allowed switch since we stopped switches, so now just generally
4704 // allow switches. Use case:
4705 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4706 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4707 // anyone to switch again).
4708 mAppSwitchesAllowedTime = 0;
4709 } else {
4710 mDidAppSwitch = true;
4711 }
4712 }
4713
4714 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 boolean shouldDisableNonVrUiLocked() {
4716 return mVrController.shouldDisableNonVrUiLocked();
4717 }
4718
Wale Ogunwale53783742018-09-16 10:21:51 -07004719 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 // 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 +00004721 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004723 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4724 + " to main display for VR");
4725 mRootActivityContainer.moveStackToDisplay(
4726 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004727 }
4728 mH.post(() -> {
4729 if (!mVrController.onVrModeChanged(r)) {
4730 return;
4731 }
4732 synchronized (mGlobalLock) {
4733 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4734 mWindowManager.disableNonVrUi(disableNonVrUi);
4735 if (disableNonVrUi) {
4736 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4737 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004738 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004739 }
4740 }
4741 });
4742 }
4743
Wale Ogunwale53783742018-09-16 10:21:51 -07004744 @Override
4745 public int getPackageScreenCompatMode(String packageName) {
4746 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4747 synchronized (mGlobalLock) {
4748 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4749 }
4750 }
4751
4752 @Override
4753 public void setPackageScreenCompatMode(String packageName, int mode) {
4754 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4755 "setPackageScreenCompatMode");
4756 synchronized (mGlobalLock) {
4757 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4758 }
4759 }
4760
4761 @Override
4762 public boolean getPackageAskScreenCompat(String packageName) {
4763 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4764 synchronized (mGlobalLock) {
4765 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4766 }
4767 }
4768
4769 @Override
4770 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4771 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4772 "setPackageAskScreenCompat");
4773 synchronized (mGlobalLock) {
4774 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4775 }
4776 }
4777
Wale Ogunwale64258362018-10-16 15:13:37 -07004778 public static String relaunchReasonToString(int relaunchReason) {
4779 switch (relaunchReason) {
4780 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4781 return "window_resize";
4782 case RELAUNCH_REASON_FREE_RESIZE:
4783 return "free_resize";
4784 default:
4785 return null;
4786 }
4787 }
4788
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004789 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004790 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004791 }
4792
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 /** Pokes the task persister. */
4794 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4795 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4796 }
4797
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 boolean isKeyguardLocked() {
4799 return mKeyguardController.isKeyguardLocked();
4800 }
4801
Garfield Tan01548632018-11-27 10:15:48 -08004802 /**
4803 * Clears launch params for the given package.
4804 * @param packageNames the names of the packages of which the launch params are to be cleared
4805 */
4806 @Override
4807 public void clearLaunchParamsForPackages(List<String> packageNames) {
4808 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4809 "clearLaunchParamsForPackages");
4810 synchronized (mGlobalLock) {
4811 for (int i = 0; i < packageNames.size(); ++i) {
4812 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4813 }
4814 }
4815 }
4816
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004817 /**
4818 * Makes the display with the given id a single task instance display. I.e the display can only
4819 * contain one task.
4820 */
4821 @Override
4822 public void setDisplayToSingleTaskInstance(int displayId) {
4823 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4824 "setDisplayToSingleTaskInstance");
4825 final long origId = Binder.clearCallingIdentity();
4826 try {
4827 final ActivityDisplay display =
4828 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4829 if (display != null) {
4830 display.setDisplayToSingleTaskInstance();
4831 }
4832 } finally {
4833 Binder.restoreCallingIdentity(origId);
4834 }
4835 }
4836
Wale Ogunwale31913b52018-10-13 08:29:31 -07004837 void dumpLastANRLocked(PrintWriter pw) {
4838 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4839 if (mLastANRState == null) {
4840 pw.println(" <no ANR has occurred since boot>");
4841 } else {
4842 pw.println(mLastANRState);
4843 }
4844 }
4845
4846 void dumpLastANRTracesLocked(PrintWriter pw) {
4847 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4848
4849 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4850 if (ArrayUtils.isEmpty(files)) {
4851 pw.println(" <no ANR has occurred since boot>");
4852 return;
4853 }
4854 // Find the latest file.
4855 File latest = null;
4856 for (File f : files) {
4857 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4858 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004859 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004860 }
4861 pw.print("File: ");
4862 pw.print(latest.getName());
4863 pw.println();
4864 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4865 String line;
4866 while ((line = in.readLine()) != null) {
4867 pw.println(line);
4868 }
4869 } catch (IOException e) {
4870 pw.print("Unable to read: ");
4871 pw.print(e);
4872 pw.println();
4873 }
4874 }
4875
4876 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4877 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4878 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4879 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4880 }
4881
4882 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4883 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4884 pw.println(header);
4885
Wale Ogunwaled32da472018-11-16 07:19:28 -08004886 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004887 dumpPackage);
4888 boolean needSep = printedAnything;
4889
4890 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004891 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004892 " ResumedActivity: ");
4893 if (printed) {
4894 printedAnything = true;
4895 needSep = false;
4896 }
4897
4898 if (dumpPackage == null) {
4899 if (needSep) {
4900 pw.println();
4901 }
4902 printedAnything = true;
4903 mStackSupervisor.dump(pw, " ");
4904 }
4905
4906 if (!printedAnything) {
4907 pw.println(" (nothing)");
4908 }
4909 }
4910
4911 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004912 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004913 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004914 pw.println(" ");
4915 }
4916
4917 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4918 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4919 getActivityStartController().dump(pw, "", dumpPackage);
4920 }
4921
4922 /**
4923 * There are three things that cmd can be:
4924 * - a flattened component name that matches an existing activity
4925 * - the cmd arg isn't the flattened component name of an existing activity:
4926 * dump all activity whose component contains the cmd as a substring
4927 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004928 * <p>
4929 * The caller should not hold lock when calling this method because it will wait for the
4930 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 *
4932 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4933 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4934 */
4935 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4936 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4937 ArrayList<ActivityRecord> activities;
4938
4939 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004940 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004941 dumpFocusedStackOnly);
4942 }
4943
4944 if (activities.size() <= 0) {
4945 return false;
4946 }
4947
4948 String[] newArgs = new String[args.length - opti];
4949 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4950
4951 TaskRecord lastTask = null;
4952 boolean needSep = false;
4953 for (int i = activities.size() - 1; i >= 0; i--) {
4954 ActivityRecord r = activities.get(i);
4955 if (needSep) {
4956 pw.println();
4957 }
4958 needSep = true;
4959 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004960 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004961 if (lastTask != task) {
4962 lastTask = task;
4963 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004964 pw.print(" id="); pw.print(lastTask.mTaskId);
4965 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004966 if (dumpAll) {
4967 lastTask.dump(pw, " ");
4968 }
4969 }
4970 }
4971 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4972 }
4973 return true;
4974 }
4975
4976 /**
4977 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4978 * there is a thread associated with the activity.
4979 */
4980 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4981 final ActivityRecord r, String[] args, boolean dumpAll) {
4982 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004983 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 synchronized (mGlobalLock) {
4985 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4986 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4987 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004988 if (r.hasProcess()) {
4989 pw.println(r.app.getPid());
4990 appThread = r.app.getThread();
4991 } else {
4992 pw.println("(not running)");
4993 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004994 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07004995 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004996 }
4997 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004998 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 // flush anything that is already in the PrintWriter since the thread is going
5000 // to write to the file descriptor directly
5001 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005002 try (TransferPipe tp = new TransferPipe()) {
5003 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5004 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005005 } catch (IOException e) {
5006 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5007 } catch (RemoteException e) {
5008 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5009 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005010 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005011 }
5012
sanryhuang498e77e2018-12-06 14:57:01 +08005013 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5014 boolean testPssMode) {
5015 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5016 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5017 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005018 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005019 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5020 st.toString());
5021 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5023 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5024 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5026 testPssMode);
5027 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005028 }
5029
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005030 int getCurrentUserId() {
5031 return mAmInternal.getCurrentUserId();
5032 }
5033
5034 private void enforceNotIsolatedCaller(String caller) {
5035 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5036 throw new SecurityException("Isolated process not allowed to call " + caller);
5037 }
5038 }
5039
Wale Ogunwalef6733932018-06-27 05:14:34 -07005040 public Configuration getConfiguration() {
5041 Configuration ci;
5042 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005043 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005044 ci.userSetLocale = false;
5045 }
5046 return ci;
5047 }
5048
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005049 /**
5050 * Current global configuration information. Contains general settings for the entire system,
5051 * also corresponds to the merged configuration of the default display.
5052 */
5053 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005054 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 }
5056
5057 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5058 boolean initLocale) {
5059 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5060 }
5061
5062 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5063 boolean initLocale, boolean deferResume) {
5064 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5065 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5066 UserHandle.USER_NULL, deferResume);
5067 }
5068
Wale Ogunwale59507092018-10-29 09:00:30 -07005069 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 final long origId = Binder.clearCallingIdentity();
5071 try {
5072 synchronized (mGlobalLock) {
5073 updateConfigurationLocked(values, null, false, true, userId,
5074 false /* deferResume */);
5075 }
5076 } finally {
5077 Binder.restoreCallingIdentity(origId);
5078 }
5079 }
5080
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005081 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5082 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5083 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5084 deferResume, null /* result */);
5085 }
5086
5087 /**
5088 * Do either or both things: (1) change the current configuration, and (2)
5089 * make sure the given activity is running with the (now) current
5090 * configuration. Returns true if the activity has been left running, or
5091 * false if <var>starting</var> is being destroyed to match the new
5092 * configuration.
5093 *
5094 * @param userId is only used when persistent parameter is set to true to persist configuration
5095 * for that particular user
5096 */
5097 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5098 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5099 ActivityTaskManagerService.UpdateConfigurationResult result) {
5100 int changes = 0;
5101 boolean kept = true;
5102
Riddle Hsua0022cd2019-09-09 21:12:41 +08005103 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005104 try {
5105 if (values != null) {
5106 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5107 deferResume);
5108 }
5109
5110 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5111 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005112 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005113 }
5114
5115 if (result != null) {
5116 result.changes = changes;
5117 result.activityRelaunched = !kept;
5118 }
5119 return kept;
5120 }
5121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005122 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005123 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005125
5126 final ActivityDisplay defaultDisplay =
5127 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5128
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 mTempConfig.setTo(getGlobalConfiguration());
5130 final int changes = mTempConfig.updateFrom(values);
5131 if (changes == 0) {
5132 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5133 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5134 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5135 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005136 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 return 0;
5138 }
5139
5140 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5141 "Updating global configuration to: " + values);
5142
5143 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5144 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5145 values.colorMode,
5146 values.densityDpi,
5147 values.fontScale,
5148 values.hardKeyboardHidden,
5149 values.keyboard,
5150 values.keyboardHidden,
5151 values.mcc,
5152 values.mnc,
5153 values.navigation,
5154 values.navigationHidden,
5155 values.orientation,
5156 values.screenHeightDp,
5157 values.screenLayout,
5158 values.screenWidthDp,
5159 values.smallestScreenWidthDp,
5160 values.touchscreen,
5161 values.uiMode);
5162
5163
5164 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5165 final LocaleList locales = values.getLocales();
5166 int bestLocaleIndex = 0;
5167 if (locales.size() > 1) {
5168 if (mSupportedSystemLocales == null) {
5169 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5170 }
5171 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5172 }
5173 SystemProperties.set("persist.sys.locale",
5174 locales.get(bestLocaleIndex).toLanguageTag());
5175 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005176
5177 final Message m = PooledLambda.obtainMessage(
5178 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5179 locales.get(bestLocaleIndex));
5180 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181 }
5182
Yunfan Chen75157d72018-07-27 14:47:21 +09005183 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184
5185 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005186 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5189 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005190 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191
5192 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005193 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194
5195 AttributeCache ac = AttributeCache.instance();
5196 if (ac != null) {
5197 ac.updateConfiguration(mTempConfig);
5198 }
5199
5200 // Make sure all resources in our process are updated right now, so that anyone who is going
5201 // to retrieve resource values after we return will be sure to get the new ones. This is
5202 // especially important during boot, where the first config change needs to guarantee all
5203 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005204 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205
5206 // We need another copy of global config because we're scheduling some calls instead of
5207 // running them in place. We need to be sure that object we send will be handled unchanged.
5208 final Configuration configCopy = new Configuration(mTempConfig);
5209 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005210 final Message msg = PooledLambda.obtainMessage(
5211 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5212 this, userId, configCopy);
5213 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005214 }
5215
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005216 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5217 for (int i = pidMap.size() - 1; i >= 0; i--) {
5218 final int pid = pidMap.keyAt(i);
5219 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005220 if (DEBUG_CONFIGURATION) {
5221 Slog.v(TAG_CONFIGURATION, "Update process config of "
5222 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005224 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005227 final Message msg = PooledLambda.obtainMessage(
5228 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5229 mAmInternal, changes, initLocale);
5230 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231
5232 // Override configuration of the default display duplicates global config, so we need to
5233 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005234 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5235 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236
5237 return changes;
5238 }
5239
Riddle Hsua0022cd2019-09-09 21:12:41 +08005240 /** @see WindowSurfacePlacer#deferLayout */
5241 void deferWindowLayout() {
5242 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5243 // Reset the reasons at the first entrance because we only care about the changes in the
5244 // deferred scope.
5245 mLayoutReasons = 0;
5246 }
5247
5248 mWindowManager.mWindowPlacerLocked.deferLayout();
5249 }
5250
5251 /** @see WindowSurfacePlacer#continueLayout */
5252 void continueWindowLayout() {
5253 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5254 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5255 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5256 }
5257 }
5258
5259 /**
5260 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5261 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5262 * defer count is gone.
5263 */
5264 void addWindowLayoutReasons(@LayoutReason int reasons) {
5265 mLayoutReasons |= reasons;
5266 }
5267
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 private void updateEventDispatchingLocked(boolean booted) {
5269 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5270 }
5271
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005272 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5273 final ContentResolver resolver = mContext.getContentResolver();
5274 Settings.System.putConfigurationForUser(resolver, config, userId);
5275 }
5276
5277 private void sendLocaleToMountDaemonMsg(Locale l) {
5278 try {
5279 IBinder service = ServiceManager.getService("mount");
5280 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5281 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5282 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5283 } catch (RemoteException e) {
5284 Log.e(TAG, "Error storing locale for decryption UI", e);
5285 }
5286 }
5287
Alison Cichowlas3e340502018-08-07 17:15:01 -04005288 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5289 mStartActivitySources.remove(permissionToken);
5290 mExpiredStartAsCallerTokens.add(permissionToken);
5291 }
5292
5293 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5294 mExpiredStartAsCallerTokens.remove(permissionToken);
5295 }
5296
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005297 boolean isActivityStartsLoggingEnabled() {
5298 return mAmInternal.isActivityStartsLoggingEnabled();
5299 }
5300
Michal Karpinski8596ded2018-11-14 14:43:48 +00005301 boolean isBackgroundActivityStartsEnabled() {
5302 return mAmInternal.isBackgroundActivityStartsEnabled();
5303 }
5304
Wale Ogunwalef6733932018-06-27 05:14:34 -07005305 void enableScreenAfterBoot(boolean booted) {
5306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5307 SystemClock.uptimeMillis());
5308 mWindowManager.enableScreenAfterBoot();
5309
5310 synchronized (mGlobalLock) {
5311 updateEventDispatchingLocked(booted);
5312 }
5313 }
5314
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005315 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5316 if (r == null || !r.hasProcess()) {
5317 return KEY_DISPATCHING_TIMEOUT_MS;
5318 }
5319 return getInputDispatchingTimeoutLocked(r.app);
5320 }
5321
5322 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005323 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005324 }
5325
Wale Ogunwalef6733932018-06-27 05:14:34 -07005326 /**
5327 * Decide based on the configuration whether we should show the ANR,
5328 * crash, etc dialogs. The idea is that if there is no affordance to
5329 * press the on-screen buttons, or the user experience would be more
5330 * greatly impacted than the crash itself, we shouldn't show the dialog.
5331 *
5332 * A thought: SystemUI might also want to get told about this, the Power
5333 * dialog / global actions also might want different behaviors.
5334 */
5335 private void updateShouldShowDialogsLocked(Configuration config) {
5336 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5337 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5338 && config.navigation == Configuration.NAVIGATION_NONAV);
5339 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5340 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5341 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5342 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5343 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5344 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5345 HIDE_ERROR_DIALOGS, 0) != 0;
5346 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5347 }
5348
5349 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5350 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5351 FONT_SCALE, 1.0f, userId);
5352
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005353 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 if (getGlobalConfiguration().fontScale == scaleFactor) {
5355 return;
5356 }
5357
5358 final Configuration configuration
5359 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5360 configuration.fontScale = scaleFactor;
5361 updatePersistentConfiguration(configuration, userId);
5362 }
5363 }
5364
5365 // Actually is sleeping or shutting down or whatever else in the future
5366 // is an inactive state.
5367 boolean isSleepingOrShuttingDownLocked() {
5368 return isSleepingLocked() || mShuttingDown;
5369 }
5370
5371 boolean isSleepingLocked() {
5372 return mSleeping;
5373 }
5374
Riddle Hsu16567132018-08-16 21:37:47 +08005375 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005376 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005377 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 if (task.isActivityTypeStandard()) {
5379 if (mCurAppTimeTracker != r.appTimeTracker) {
5380 // We are switching app tracking. Complete the current one.
5381 if (mCurAppTimeTracker != null) {
5382 mCurAppTimeTracker.stop();
5383 mH.obtainMessage(
5384 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005385 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005386 mCurAppTimeTracker = null;
5387 }
5388 if (r.appTimeTracker != null) {
5389 mCurAppTimeTracker = r.appTimeTracker;
5390 startTimeTrackingFocusedActivityLocked();
5391 }
5392 } else {
5393 startTimeTrackingFocusedActivityLocked();
5394 }
5395 } else {
5396 r.appTimeTracker = null;
5397 }
5398 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5399 // TODO: Probably not, because we don't want to resume voice on switching
5400 // back to this activity
5401 if (task.voiceInteractor != null) {
5402 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5403 } else {
5404 finishRunningVoiceLocked();
5405
5406 if (mLastResumedActivity != null) {
5407 final IVoiceInteractionSession session;
5408
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005409 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005410 if (lastResumedActivityTask != null
5411 && lastResumedActivityTask.voiceSession != null) {
5412 session = lastResumedActivityTask.voiceSession;
5413 } else {
5414 session = mLastResumedActivity.voiceSession;
5415 }
5416
5417 if (session != null) {
5418 // We had been in a voice interaction session, but now focused has
5419 // move to something different. Just finish the session, we can't
5420 // return to it and retain the proper state and synchronization with
5421 // the voice interaction service.
5422 finishVoiceTask(session);
5423 }
5424 }
5425 }
5426
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005427 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5428 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 }
5430 updateResumedAppTrace(r);
5431 mLastResumedActivity = r;
5432
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005433 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005434
5435 applyUpdateLockStateLocked(r);
5436 applyUpdateVrModeLocked(r);
5437
5438 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005439 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 r == null ? "NULL" : r.shortComponentName,
5441 reason);
5442 }
5443
5444 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5445 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005446 final ActivityTaskManagerInternal.SleepToken token =
5447 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 updateSleepIfNeededLocked();
5449 return token;
5450 }
5451 }
5452
5453 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005454 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 final boolean wasSleeping = mSleeping;
5456 boolean updateOomAdj = false;
5457
5458 if (!shouldSleep) {
5459 // If wasSleeping is true, we need to wake up activity manager state from when
5460 // we started sleeping. In either case, we need to apply the sleep tokens, which
5461 // will wake up stacks or put them to sleep as appropriate.
5462 if (wasSleeping) {
5463 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005464 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5465 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 startTimeTrackingFocusedActivityLocked();
5467 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005468 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5470 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005471 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 if (wasSleeping) {
5473 updateOomAdj = true;
5474 }
5475 } else if (!mSleeping && shouldSleep) {
5476 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005477 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5478 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479 if (mCurAppTimeTracker != null) {
5480 mCurAppTimeTracker.stop();
5481 }
5482 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005483 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005484 mStackSupervisor.goingToSleepLocked();
5485 updateResumedAppTrace(null /* resumed */);
5486 updateOomAdj = true;
5487 }
5488 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005489 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 }
5491 }
5492
5493 void updateOomAdj() {
5494 mH.post(mAmInternal::updateOomAdj);
5495 }
5496
Wale Ogunwale53783742018-09-16 10:21:51 -07005497 void updateCpuStats() {
5498 mH.post(mAmInternal::updateCpuStats);
5499 }
5500
Hui Yu03d12402018-12-06 18:00:37 -08005501 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5502 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005503 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5504 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005505 mH.sendMessage(m);
5506 }
5507
Hui Yu03d12402018-12-06 18:00:37 -08005508 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005509 ComponentName taskRoot = null;
5510 final TaskRecord task = activity.getTaskRecord();
5511 if (task != null) {
5512 final ActivityRecord rootActivity = task.getRootActivity();
5513 if (rootActivity != null) {
5514 taskRoot = rootActivity.mActivityComponent;
5515 }
5516 }
5517
Hui Yu03d12402018-12-06 18:00:37 -08005518 final Message m = PooledLambda.obtainMessage(
5519 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005520 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005521 mH.sendMessage(m);
5522 }
5523
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005524 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5525 String hostingType) {
5526 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005527 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5528 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005529 + activity.processName);
5530 }
5531 // Post message to start process to avoid possible deadlock of calling into AMS with the
5532 // ATMS lock held.
5533 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5534 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5535 isTop, hostingType, activity.intent.getComponent());
5536 mH.sendMessage(m);
5537 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005538 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005539 }
5540 }
5541
Wale Ogunwale53783742018-09-16 10:21:51 -07005542 void setBooting(boolean booting) {
5543 mAmInternal.setBooting(booting);
5544 }
5545
5546 boolean isBooting() {
5547 return mAmInternal.isBooting();
5548 }
5549
5550 void setBooted(boolean booted) {
5551 mAmInternal.setBooted(booted);
5552 }
5553
5554 boolean isBooted() {
5555 return mAmInternal.isBooted();
5556 }
5557
5558 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5559 mH.post(() -> {
5560 if (finishBooting) {
5561 mAmInternal.finishBooting();
5562 }
5563 if (enableScreen) {
5564 mInternal.enableScreenAfterBoot(isBooted());
5565 }
5566 });
5567 }
5568
5569 void setHeavyWeightProcess(ActivityRecord root) {
5570 mHeavyWeightProcess = root.app;
5571 final Message m = PooledLambda.obtainMessage(
5572 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005573 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005574 mH.sendMessage(m);
5575 }
5576
5577 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5578 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5579 return;
5580 }
5581
5582 mHeavyWeightProcess = null;
5583 final Message m = PooledLambda.obtainMessage(
5584 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5585 proc.mUserId);
5586 mH.sendMessage(m);
5587 }
5588
5589 private void cancelHeavyWeightProcessNotification(int userId) {
5590 final INotificationManager inm = NotificationManager.getService();
5591 if (inm == null) {
5592 return;
5593 }
5594 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005595 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005596 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5597 } catch (RuntimeException e) {
5598 Slog.w(TAG, "Error canceling notification for service", e);
5599 } catch (RemoteException e) {
5600 }
5601
5602 }
5603
5604 private void postHeavyWeightProcessNotification(
5605 WindowProcessController proc, Intent intent, int userId) {
5606 if (proc == null) {
5607 return;
5608 }
5609
5610 final INotificationManager inm = NotificationManager.getService();
5611 if (inm == null) {
5612 return;
5613 }
5614
5615 try {
5616 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5617 String text = mContext.getString(R.string.heavy_weight_notification,
5618 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5619 Notification notification =
5620 new Notification.Builder(context,
5621 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5622 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5623 .setWhen(0)
5624 .setOngoing(true)
5625 .setTicker(text)
5626 .setColor(mContext.getColor(
5627 com.android.internal.R.color.system_notification_accent_color))
5628 .setContentTitle(text)
5629 .setContentText(
5630 mContext.getText(R.string.heavy_weight_notification_detail))
5631 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5632 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5633 new UserHandle(userId)))
5634 .build();
5635 try {
5636 inm.enqueueNotificationWithTag("android", "android", null,
5637 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5638 } catch (RuntimeException e) {
5639 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5640 } catch (RemoteException e) {
5641 }
5642 } catch (PackageManager.NameNotFoundException e) {
5643 Slog.w(TAG, "Unable to create context for heavy notification", e);
5644 }
5645
5646 }
5647
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005648 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5649 IBinder token, String resultWho, int requestCode, Intent[] intents,
5650 String[] resolvedTypes, int flags, Bundle bOptions) {
5651
5652 ActivityRecord activity = null;
5653 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5654 activity = ActivityRecord.isInStackLocked(token);
5655 if (activity == null) {
5656 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5657 return null;
5658 }
5659 if (activity.finishing) {
5660 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5661 return null;
5662 }
5663 }
5664
5665 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5666 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5667 bOptions);
5668 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5669 if (noCreate) {
5670 return rec;
5671 }
5672 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5673 if (activity.pendingResults == null) {
5674 activity.pendingResults = new HashSet<>();
5675 }
5676 activity.pendingResults.add(rec.ref);
5677 }
5678 return rec;
5679 }
5680
Andrii Kulian52d255c2018-07-13 11:32:19 -07005681 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005682 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005683 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005684 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5685 mCurAppTimeTracker.start(resumedActivity.packageName);
5686 }
5687 }
5688
5689 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5690 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005691 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005692 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5693 }
5694 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005695 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005696 constructResumedTraceName(resumed.packageName), 0);
5697 }
5698 mTracedResumedActivity = resumed;
5699 }
5700
5701 private String constructResumedTraceName(String packageName) {
5702 return "focused app: " + packageName;
5703 }
5704
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005705 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005706 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005707 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005708 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005709 // mainStack is null during startup.
5710 if (mainStack != null) {
5711 if (changes != 0 && starting == null) {
5712 // If the configuration changed, and the caller is not already
5713 // in the process of starting an activity, then find the top
5714 // activity to check if its configuration needs to change.
5715 starting = mainStack.topRunningActivityLocked();
5716 }
5717
5718 if (starting != null) {
5719 kept = starting.ensureActivityConfiguration(changes,
5720 false /* preserveWindow */);
5721 // And we need to make sure at this point that all other activities
5722 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005723 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005724 !PRESERVE_WINDOWS);
5725 }
5726 }
5727
5728 return kept;
5729 }
5730
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005731 void scheduleAppGcsLocked() {
5732 mH.post(() -> mAmInternal.scheduleAppGcs());
5733 }
5734
Wale Ogunwale53783742018-09-16 10:21:51 -07005735 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5736 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5737 }
5738
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005739 /**
5740 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5741 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5742 * on demand.
5743 */
5744 IPackageManager getPackageManager() {
5745 return AppGlobals.getPackageManager();
5746 }
5747
5748 PackageManagerInternal getPackageManagerInternalLocked() {
5749 if (mPmInternal == null) {
5750 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5751 }
5752 return mPmInternal;
5753 }
5754
Hai Zhangf4da9be2019-05-01 13:46:06 +08005755 PermissionPolicyInternal getPermissionPolicyInternal() {
5756 if (mPermissionPolicyInternal == null) {
5757 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5758 }
5759 return mPermissionPolicyInternal;
5760 }
5761
Wale Ogunwale008163e2018-07-23 23:11:08 -07005762 AppWarnings getAppWarningsLocked() {
5763 return mAppWarnings;
5764 }
5765
Wale Ogunwale214f3482018-10-04 11:00:47 -07005766 Intent getHomeIntent() {
5767 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5768 intent.setComponent(mTopComponent);
5769 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5770 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5771 intent.addCategory(Intent.CATEGORY_HOME);
5772 }
5773 return intent;
5774 }
5775
Chilun2ef71f72018-11-16 17:57:15 +08005776 /**
5777 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5778 * activities.
5779 *
5780 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5781 * component defined in config_secondaryHomeComponent.
5782 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5783 */
5784 Intent getSecondaryHomeIntent(String preferredPackage) {
5785 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005786 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5787 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5788 if (preferredPackage == null || useSystemProvidedLauncher) {
5789 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005790 final String secondaryHomeComponent = mContext.getResources().getString(
5791 com.android.internal.R.string.config_secondaryHomeComponent);
5792 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5793 } else {
5794 intent.setPackage(preferredPackage);
5795 }
5796 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5797 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5798 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5799 }
5800 return intent;
5801 }
5802
Wale Ogunwale214f3482018-10-04 11:00:47 -07005803 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5804 if (info == null) return null;
5805 ApplicationInfo newInfo = new ApplicationInfo(info);
5806 newInfo.initForUser(userId);
5807 return newInfo;
5808 }
5809
Wale Ogunwale9c103022018-10-18 07:44:54 -07005810 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005811 if (uid == SYSTEM_UID) {
5812 // The system gets to run in any process. If there are multiple processes with the same
5813 // uid, just pick the first (this should never happen).
5814 final SparseArray<WindowProcessController> procs =
5815 mProcessNames.getMap().get(processName);
5816 if (procs == null) return null;
5817 final int procCount = procs.size();
5818 for (int i = 0; i < procCount; i++) {
5819 final int procUid = procs.keyAt(i);
5820 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5821 // Don't use an app process or different user process for system component.
5822 continue;
5823 }
5824 return procs.valueAt(i);
5825 }
5826 }
5827
5828 return mProcessNames.get(processName, uid);
5829 }
5830
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005831 WindowProcessController getProcessController(IApplicationThread thread) {
5832 if (thread == null) {
5833 return null;
5834 }
5835
5836 final IBinder threadBinder = thread.asBinder();
5837 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5838 for (int i = pmap.size()-1; i >= 0; i--) {
5839 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5840 for (int j = procs.size() - 1; j >= 0; j--) {
5841 final WindowProcessController proc = procs.valueAt(j);
5842 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5843 return proc;
5844 }
5845 }
5846 }
5847
5848 return null;
5849 }
5850
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005851 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005852 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005853 if (proc == null) return null;
5854 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5855 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005856 }
5857 return null;
5858 }
5859
Riddle Hsua0536432019-02-16 00:38:59 +08005860 int getUidState(int uid) {
5861 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005862 }
5863
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005864 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005865 // A uid is considered to be foreground if it has a visible non-toast window.
5866 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005867 }
5868
Ricky Wai96f5c352019-04-10 18:40:17 +01005869 boolean isDeviceOwner(int uid) {
5870 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005871 }
5872
Ricky Wai96f5c352019-04-10 18:40:17 +01005873 void setDeviceOwnerUid(int uid) {
5874 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005875 }
5876
Wale Ogunwale9de19442018-10-18 19:05:03 -07005877 /**
5878 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5879 * the whitelist
5880 */
5881 String getPendingTempWhitelistTagForUidLocked(int uid) {
5882 return mPendingTempWhitelist.get(uid);
5883 }
5884
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005885 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5886 if (true || Build.IS_USER) {
5887 return;
5888 }
5889
5890 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5891 StrictMode.allowThreadDiskWrites();
5892 try {
5893 File tracesDir = new File("/data/anr");
5894 File tracesFile = null;
5895 try {
5896 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5897
5898 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005899 String timeString =
5900 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5901 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005902 sb.append(": ");
5903 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5904 sb.append(" since ");
5905 sb.append(msg);
5906 FileOutputStream fos = new FileOutputStream(tracesFile);
5907 fos.write(sb.toString().getBytes());
5908 if (app == null) {
5909 fos.write("\n*** No application process!".getBytes());
5910 }
5911 fos.close();
5912 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5913 } catch (IOException e) {
5914 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5915 return;
5916 }
5917
5918 if (app != null && app.getPid() > 0) {
5919 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5920 firstPids.add(app.getPid());
5921 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5922 }
5923
5924 File lastTracesFile = null;
5925 File curTracesFile = null;
5926 for (int i=9; i>=0; i--) {
5927 String name = String.format(Locale.US, "slow%02d.txt", i);
5928 curTracesFile = new File(tracesDir, name);
5929 if (curTracesFile.exists()) {
5930 if (lastTracesFile != null) {
5931 curTracesFile.renameTo(lastTracesFile);
5932 } else {
5933 curTracesFile.delete();
5934 }
5935 }
5936 lastTracesFile = curTracesFile;
5937 }
5938 tracesFile.renameTo(curTracesFile);
5939 } finally {
5940 StrictMode.setThreadPolicy(oldPolicy);
5941 }
5942 }
5943
Michal Karpinskida34cd42019-04-02 19:46:52 +01005944 boolean isAssociatedCompanionApp(int userId, int uid) {
5945 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5946 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005947 return false;
5948 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005949 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005950 }
5951
Issei Suzuki734bc942019-06-05 13:59:52 +02005952 void notifySingleTaskDisplayEmpty(int displayId) {
5953 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5954 }
5955
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005956 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005957 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005958
5959
Wale Ogunwale98875612018-10-12 07:53:02 -07005960 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5961 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005962
Riddle Hsud93a6c42018-11-29 21:50:06 +08005963 H(Looper looper) {
5964 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005965 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005966
5967 @Override
5968 public void handleMessage(Message msg) {
5969 switch (msg.what) {
5970 case REPORT_TIME_TRACKER_MSG: {
5971 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5972 tracker.deliverResult(mContext);
5973 } break;
5974 }
5975 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005976 }
5977
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005978 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005979 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005980
5981 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005982 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005983 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005984
5985 @Override
5986 public void handleMessage(Message msg) {
5987 switch (msg.what) {
5988 case DISMISS_DIALOG_UI_MSG: {
5989 final Dialog d = (Dialog) msg.obj;
5990 d.dismiss();
5991 break;
5992 }
5993 }
5994 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005995 }
5996
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005997 final class LocalService extends ActivityTaskManagerInternal {
5998 @Override
5999 public SleepToken acquireSleepToken(String tag, int displayId) {
6000 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006001 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006002 }
6003
6004 @Override
6005 public ComponentName getHomeActivityForUser(int userId) {
6006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006007 final ActivityRecord homeActivity =
6008 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006009 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011 }
6012
6013 @Override
6014 public void onLocalVoiceInteractionStarted(IBinder activity,
6015 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6016 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006017 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006018 }
6019 }
6020
6021 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006022 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006023 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024 synchronized (mGlobalLock) {
6025 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006026 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006027 }
6028 }
6029
6030 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006031 public void notifySingleTaskDisplayDrawn(int displayId) {
6032 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6033 }
6034
6035 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006036 public void notifyAppTransitionFinished() {
6037 synchronized (mGlobalLock) {
6038 mStackSupervisor.notifyAppTransitionDone();
6039 }
6040 }
6041
6042 @Override
6043 public void notifyAppTransitionCancelled() {
6044 synchronized (mGlobalLock) {
6045 mStackSupervisor.notifyAppTransitionDone();
6046 }
6047 }
6048
6049 @Override
6050 public List<IBinder> getTopVisibleActivities() {
6051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006052 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054 }
6055
6056 @Override
6057 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6058 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006059 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006060 }
6061 }
6062
6063 @Override
6064 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6065 Bundle bOptions) {
6066 Preconditions.checkNotNull(intents, "intents");
6067 final String[] resolvedTypes = new String[intents.length];
6068
6069 // UID of the package on user userId.
6070 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6071 // packageUid may not be initialized.
6072 int packageUid = 0;
6073 final long ident = Binder.clearCallingIdentity();
6074
6075 try {
6076 for (int i = 0; i < intents.length; i++) {
6077 resolvedTypes[i] =
6078 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6079 }
6080
6081 packageUid = AppGlobals.getPackageManager().getPackageUid(
6082 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6083 } catch (RemoteException e) {
6084 // Shouldn't happen.
6085 } finally {
6086 Binder.restoreCallingIdentity(ident);
6087 }
6088
Riddle Hsu591bf612019-02-14 17:55:31 +08006089 return getActivityStartController().startActivitiesInPackage(
6090 packageUid, packageName,
6091 intents, resolvedTypes, null /* resultTo */,
6092 SafeActivityOptions.fromBundle(bOptions), userId,
6093 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6094 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 }
6096
6097 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006098 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6099 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6100 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6101 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006102 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006103 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006104 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6105 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6106 userId, validateIncomingUser, originatingPendingIntent,
6107 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006108 }
6109 }
6110
6111 @Override
6112 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6113 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6114 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6115 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006116 PendingIntentRecord originatingPendingIntent,
6117 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006118 synchronized (mGlobalLock) {
6119 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6120 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6121 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006122 validateIncomingUser, originatingPendingIntent,
6123 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006124 }
6125 }
6126
6127 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6129 Intent intent, Bundle options, int userId) {
6130 return ActivityTaskManagerService.this.startActivityAsUser(
6131 caller, callerPacakge, intent,
6132 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6133 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6134 false /*validateIncomingUser*/);
6135 }
6136
6137 @Override
lumark588a3e82018-07-20 18:53:54 +08006138 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006139 synchronized (mGlobalLock) {
6140
6141 // We might change the visibilities here, so prepare an empty app transition which
6142 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006143 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006144 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006145 if (activityDisplay == null) {
6146 return;
6147 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006148 final DisplayContent dc = activityDisplay.mDisplayContent;
6149 final boolean wasTransitionSet =
6150 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006151 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006152 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006154 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155
6156 // If there was a transition set already we don't want to interfere with it as we
6157 // might be starting it too early.
6158 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006159 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 }
6161 }
6162 if (callback != null) {
6163 callback.run();
6164 }
6165 }
6166
6167 @Override
6168 public void notifyKeyguardTrustedChanged() {
6169 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006170 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006171 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 }
6173 }
6174 }
6175
6176 /**
6177 * Called after virtual display Id is updated by
6178 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6179 * {@param vrVr2dDisplayId}.
6180 */
6181 @Override
6182 public void setVr2dDisplayId(int vr2dDisplayId) {
6183 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6184 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006185 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187 }
6188
6189 @Override
6190 public void setFocusedActivity(IBinder token) {
6191 synchronized (mGlobalLock) {
6192 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6193 if (r == null) {
6194 throw new IllegalArgumentException(
6195 "setFocusedActivity: No activity record matching token=" + token);
6196 }
Louis Chang19443452018-10-09 12:10:21 +08006197 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006199 }
6200 }
6201 }
6202
6203 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006205 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
6207
6208 @Override
6209 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006210 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212
6213 @Override
6214 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006215 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 }
6217
6218 @Override
6219 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6220 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6221 }
6222
6223 @Override
6224 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006225 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006227
6228 @Override
6229 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6230 synchronized (mGlobalLock) {
6231 mActiveVoiceInteractionServiceComponent = component;
6232 }
6233 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006234
6235 @Override
6236 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6237 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6238 return;
6239 }
6240 synchronized (mGlobalLock) {
6241 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6242 if (types == null) {
6243 if (uid < 0) {
6244 return;
6245 }
6246 types = new ArrayMap<>();
6247 mAllowAppSwitchUids.put(userId, types);
6248 }
6249 if (uid < 0) {
6250 types.remove(type);
6251 } else {
6252 types.put(type, uid);
6253 }
6254 }
6255 }
6256
6257 @Override
6258 public void onUserStopped(int userId) {
6259 synchronized (mGlobalLock) {
6260 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6261 mAllowAppSwitchUids.remove(userId);
6262 }
6263 }
6264
6265 @Override
6266 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6267 synchronized (mGlobalLock) {
6268 return ActivityTaskManagerService.this.isGetTasksAllowed(
6269 caller, callingPid, callingUid);
6270 }
6271 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006272
Riddle Hsua0536432019-02-16 00:38:59 +08006273 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006274 @Override
6275 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006277 mProcessNames.put(proc.mName, proc.mUid, proc);
6278 }
6279 }
6280
Riddle Hsua0536432019-02-16 00:38:59 +08006281 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006282 @Override
6283 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006284 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006285 mProcessNames.remove(name, uid);
6286 }
6287 }
6288
Riddle Hsua0536432019-02-16 00:38:59 +08006289 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006290 @Override
6291 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006292 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006293 if (proc == mHomeProcess) {
6294 mHomeProcess = null;
6295 }
6296 if (proc == mPreviousProcess) {
6297 mPreviousProcess = null;
6298 }
6299 }
6300 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006301
Riddle Hsua0536432019-02-16 00:38:59 +08006302 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006303 @Override
6304 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 return mTopProcessState;
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006311 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006312 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 return proc == mHeavyWeightProcess;
6315 }
6316 }
6317
Riddle Hsua0536432019-02-16 00:38:59 +08006318 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006319 @Override
6320 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006321 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006322 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6323 }
6324 }
6325
6326 @Override
6327 public void finishHeavyWeightApp() {
6328 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006329 if (mHeavyWeightProcess != null) {
6330 mHeavyWeightProcess.finishActivities();
6331 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006332 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6333 mHeavyWeightProcess);
6334 }
6335 }
6336
Riddle Hsua0536432019-02-16 00:38:59 +08006337 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006338 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006339 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006340 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006341 return isSleepingLocked();
6342 }
6343 }
6344
6345 @Override
6346 public boolean isShuttingDown() {
6347 synchronized (mGlobalLock) {
6348 return mShuttingDown;
6349 }
6350 }
6351
6352 @Override
6353 public boolean shuttingDown(boolean booted, int timeout) {
6354 synchronized (mGlobalLock) {
6355 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006356 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006357 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006358 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006359 return mStackSupervisor.shutdownLocked(timeout);
6360 }
6361 }
6362
6363 @Override
6364 public void enableScreenAfterBoot(boolean booted) {
6365 synchronized (mGlobalLock) {
6366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6367 SystemClock.uptimeMillis());
6368 mWindowManager.enableScreenAfterBoot();
6369 updateEventDispatchingLocked(booted);
6370 }
6371 }
6372
6373 @Override
6374 public boolean showStrictModeViolationDialog() {
6375 synchronized (mGlobalLock) {
6376 return mShowDialogs && !mSleeping && !mShuttingDown;
6377 }
6378 }
6379
6380 @Override
6381 public void showSystemReadyErrorDialogsIfNeeded() {
6382 synchronized (mGlobalLock) {
6383 try {
6384 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6385 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6386 + " data partition or your device will be unstable.");
6387 mUiHandler.post(() -> {
6388 if (mShowDialogs) {
6389 AlertDialog d = new BaseErrorDialog(mUiContext);
6390 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6391 d.setCancelable(false);
6392 d.setTitle(mUiContext.getText(R.string.android_system_label));
6393 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6394 d.setButton(DialogInterface.BUTTON_POSITIVE,
6395 mUiContext.getText(R.string.ok),
6396 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6397 d.show();
6398 }
6399 });
6400 }
6401 } catch (RemoteException e) {
6402 }
6403
6404 if (!Build.isBuildConsistent()) {
6405 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6406 mUiHandler.post(() -> {
6407 if (mShowDialogs) {
6408 AlertDialog d = new BaseErrorDialog(mUiContext);
6409 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6410 d.setCancelable(false);
6411 d.setTitle(mUiContext.getText(R.string.android_system_label));
6412 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6413 d.setButton(DialogInterface.BUTTON_POSITIVE,
6414 mUiContext.getText(R.string.ok),
6415 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6416 d.show();
6417 }
6418 });
6419 }
6420 }
6421 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006422
6423 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006424 public void onProcessMapped(int pid, WindowProcessController proc) {
6425 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006426 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006427 }
6428 }
6429
6430 @Override
6431 public void onProcessUnMapped(int pid) {
6432 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006433 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006434 }
6435 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006436
6437 @Override
6438 public void onPackageDataCleared(String name) {
6439 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006440 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006441 mAppWarnings.onPackageDataCleared(name);
6442 }
6443 }
6444
6445 @Override
6446 public void onPackageUninstalled(String name) {
6447 synchronized (mGlobalLock) {
6448 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006449 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006450 }
6451 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006452
6453 @Override
6454 public void onPackageAdded(String name, boolean replacing) {
6455 synchronized (mGlobalLock) {
6456 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6457 }
6458 }
6459
6460 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006461 public void onPackageReplaced(ApplicationInfo aInfo) {
6462 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006463 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006464 }
6465 }
6466
6467 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006468 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6469 synchronized (mGlobalLock) {
6470 return compatibilityInfoForPackageLocked(ai);
6471 }
6472 }
6473
Yunfan Chen75157d72018-07-27 14:47:21 +09006474 /**
6475 * Set the corresponding display information for the process global configuration. To be
6476 * called when we need to show IME on a different display.
6477 *
6478 * @param pid The process id associated with the IME window.
6479 * @param displayId The ID of the display showing the IME.
6480 */
6481 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006482 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006483 // Don't update process-level configuration for Multi-Client IME process since other
6484 // IMEs on other displays will also receive this configuration change due to IME
6485 // services use the same application config/context.
6486 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006487
Yunfan Chen75157d72018-07-27 14:47:21 +09006488 if (pid == MY_PID || pid < 0) {
6489 if (DEBUG_CONFIGURATION) {
6490 Slog.w(TAG,
6491 "Trying to update display configuration for system/invalid process.");
6492 }
6493 return;
6494 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006495 synchronized (mGlobalLock) {
6496 final ActivityDisplay activityDisplay =
6497 mRootActivityContainer.getActivityDisplay(displayId);
6498 if (activityDisplay == null) {
6499 // Call might come when display is not yet added or has been removed.
6500 if (DEBUG_CONFIGURATION) {
6501 Slog.w(TAG, "Trying to update display configuration for non-existing "
6502 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006503 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006504 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006505 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006506 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006507 if (process == null) {
6508 if (DEBUG_CONFIGURATION) {
6509 Slog.w(TAG, "Trying to update display configuration for invalid "
6510 + "process, pid=" + pid);
6511 }
6512 return;
6513 }
lumarkddc77fb2019-06-27 22:22:23 +08006514 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006515 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6516 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006517 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006518
6519 @Override
6520 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006521 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006522 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006523 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6524 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006525 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006526 }
6527 }
6528 }
6529
6530 @Override
6531 public void clearPendingResultForActivity(IBinder activityToken,
6532 WeakReference<PendingIntentRecord> pir) {
6533 synchronized (mGlobalLock) {
6534 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6535 if (r != null && r.pendingResults != null) {
6536 r.pendingResults.remove(pir);
6537 }
6538 }
6539 }
6540
6541 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006542 public ActivityTokens getTopActivityForTask(int taskId) {
6543 synchronized (mGlobalLock) {
6544 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6545 if (taskRecord == null) {
6546 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6547 + " Requested task not found");
6548 return null;
6549 }
6550 final ActivityRecord activity = taskRecord.getTopActivity();
6551 if (activity == null) {
6552 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6553 + " Requested activity not found");
6554 return null;
6555 }
6556 if (!activity.attachedToProcess()) {
6557 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6558 + activity);
6559 return null;
6560 }
6561 return new ActivityTokens(activity.appToken, activity.assistToken,
6562 activity.app.getThread());
6563 }
6564 }
6565
6566 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006567 public IIntentSender getIntentSender(int type, String packageName,
6568 int callingUid, int userId, IBinder token, String resultWho,
6569 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6570 Bundle bOptions) {
6571 synchronized (mGlobalLock) {
6572 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6573 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6574 }
6575 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006576
6577 @Override
6578 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6579 synchronized (mGlobalLock) {
6580 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6581 if (r == null) {
6582 return null;
6583 }
6584 if (r.mServiceConnectionsHolder == null) {
6585 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6586 ActivityTaskManagerService.this, r);
6587 }
6588
6589 return r.mServiceConnectionsHolder;
6590 }
6591 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006592
6593 @Override
6594 public Intent getHomeIntent() {
6595 synchronized (mGlobalLock) {
6596 return ActivityTaskManagerService.this.getHomeIntent();
6597 }
6598 }
6599
6600 @Override
6601 public boolean startHomeActivity(int userId, String reason) {
6602 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006603 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006604 }
6605 }
6606
6607 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006608 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006609 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006610 synchronized (mGlobalLock) {
6611 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006612 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006613 }
Chilun8b1f1be2019-03-13 17:14:36 +08006614 }
6615
6616 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006617 public boolean startHomeOnAllDisplays(int userId, String reason) {
6618 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006619 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006620 }
6621 }
6622
Riddle Hsua0536432019-02-16 00:38:59 +08006623 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006624 @Override
6625 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006626 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006627 if (mFactoryTest == FACTORY_TEST_OFF) {
6628 return false;
6629 }
6630 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6631 && wpc.mName.equals(mTopComponent.getPackageName())) {
6632 return true;
6633 }
6634 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6635 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6636 }
6637 }
6638
6639 @Override
6640 public void updateTopComponentForFactoryTest() {
6641 synchronized (mGlobalLock) {
6642 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6643 return;
6644 }
6645 final ResolveInfo ri = mContext.getPackageManager()
6646 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6647 final CharSequence errorMsg;
6648 if (ri != null) {
6649 final ActivityInfo ai = ri.activityInfo;
6650 final ApplicationInfo app = ai.applicationInfo;
6651 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6652 mTopAction = Intent.ACTION_FACTORY_TEST;
6653 mTopData = null;
6654 mTopComponent = new ComponentName(app.packageName, ai.name);
6655 errorMsg = null;
6656 } else {
6657 errorMsg = mContext.getResources().getText(
6658 com.android.internal.R.string.factorytest_not_system);
6659 }
6660 } else {
6661 errorMsg = mContext.getResources().getText(
6662 com.android.internal.R.string.factorytest_no_action);
6663 }
6664 if (errorMsg == null) {
6665 return;
6666 }
6667
6668 mTopAction = null;
6669 mTopData = null;
6670 mTopComponent = null;
6671 mUiHandler.post(() -> {
6672 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6673 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006674 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006675 });
6676 }
6677 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006678
Riddle Hsua0536432019-02-16 00:38:59 +08006679 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006680 @Override
6681 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6682 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006683 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006684 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006685 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006686
6687 wpc.clearRecentTasks();
6688 wpc.clearActivities();
6689
6690 if (wpc.isInstrumenting()) {
6691 finishInstrumentationCallback.run();
6692 }
6693
Jorim Jaggid0752812018-10-16 16:07:20 +02006694 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006695 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006696 try {
6697 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6698 // If there was nothing to resume, and we are not already restarting
6699 // this process, but there is a visible activity that is hosted by the
6700 // process...then make sure all visible activities are running, taking
6701 // care of restarting this process.
6702 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6703 !PRESERVE_WINDOWS);
6704 }
6705 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006706 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006708 }
6709 }
6710 }
6711
6712 @Override
6713 public void closeSystemDialogs(String reason) {
6714 enforceNotIsolatedCaller("closeSystemDialogs");
6715
6716 final int pid = Binder.getCallingPid();
6717 final int uid = Binder.getCallingUid();
6718 final long origId = Binder.clearCallingIdentity();
6719 try {
6720 synchronized (mGlobalLock) {
6721 // Only allow this from foreground processes, so that background
6722 // applications can't abuse it to prevent system UI from being shown.
6723 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006724 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006725 if (!proc.isPerceptible()) {
6726 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6727 + " from background process " + proc);
6728 return;
6729 }
6730 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 mWindowManager.closeSystemDialogs(reason);
6732
Wale Ogunwaled32da472018-11-16 07:19:28 -08006733 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006735 // Call into AM outside the synchronized block.
6736 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 } finally {
6738 Binder.restoreCallingIdentity(origId);
6739 }
6740 }
6741
6742 @Override
6743 public void cleanupDisabledPackageComponents(
6744 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6745 synchronized (mGlobalLock) {
6746 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006749 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 mStackSupervisor.scheduleIdleLocked();
6751 }
6752
6753 // Clean-up disabled tasks
6754 getRecentTasks().cleanupDisabledPackageTasksLocked(
6755 packageName, disabledClasses, userId);
6756 }
6757 }
6758
6759 @Override
6760 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6761 int userId) {
6762 synchronized (mGlobalLock) {
6763
6764 boolean didSomething =
6765 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006766 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 null, doit, evenPersistent, userId);
6768 return didSomething;
6769 }
6770 }
6771
6772 @Override
6773 public void resumeTopActivities(boolean scheduleIdle) {
6774 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006775 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776 if (scheduleIdle) {
6777 mStackSupervisor.scheduleIdleLocked();
6778 }
6779 }
6780 }
6781
Riddle Hsua0536432019-02-16 00:38:59 +08006782 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 @Override
6784 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006785 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6787 }
6788 }
6789
Riddle Hsua0536432019-02-16 00:38:59 +08006790 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 @Override
6792 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006793 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006794 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6795 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6796 }
6797 try {
6798 return mRootActivityContainer.attachApplication(wpc);
6799 } finally {
6800 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6801 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 }
6803 }
6804
6805 @Override
6806 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6807 try {
6808 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6809 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6810 }
6811 } catch (RemoteException ex) {
6812 throw new SecurityException("Fail to check is caller a privileged app", ex);
6813 }
6814
6815 synchronized (mGlobalLock) {
6816 final long ident = Binder.clearCallingIdentity();
6817 try {
6818 if (mAmInternal.shouldConfirmCredentials(userId)) {
6819 if (mKeyguardController.isKeyguardLocked()) {
6820 // Showing launcher to avoid user entering credential twice.
6821 startHomeActivity(currentUserId, "notifyLockedProfile");
6822 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006823 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 }
6825 } finally {
6826 Binder.restoreCallingIdentity(ident);
6827 }
6828 }
6829 }
6830
6831 @Override
6832 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6833 mAmInternal.enforceCallingPermission(
6834 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6835
6836 synchronized (mGlobalLock) {
6837 final long ident = Binder.clearCallingIdentity();
6838 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006839 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6840 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6843 UserHandle.CURRENT);
6844 } finally {
6845 Binder.restoreCallingIdentity(ident);
6846 }
6847 }
6848 }
6849
6850 @Override
6851 public void writeActivitiesToProto(ProtoOutputStream proto) {
6852 synchronized (mGlobalLock) {
6853 // The output proto of "activity --proto activities"
6854 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006855 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006856 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6857 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 }
6859 }
6860
6861 @Override
6862 public void saveANRState(String reason) {
6863 synchronized (mGlobalLock) {
6864 final StringWriter sw = new StringWriter();
6865 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6866 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6867 if (reason != null) {
6868 pw.println(" Reason: " + reason);
6869 }
6870 pw.println();
6871 getActivityStartController().dump(pw, " ", null);
6872 pw.println();
6873 pw.println("-------------------------------------------------------------------------------");
6874 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6875 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6876 "" /* header */);
6877 pw.println();
6878 pw.close();
6879
6880 mLastANRState = sw.toString();
6881 }
6882 }
6883
6884 @Override
6885 public void clearSavedANRState() {
6886 synchronized (mGlobalLock) {
6887 mLastANRState = null;
6888 }
6889 }
6890
6891 @Override
6892 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6893 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6894 synchronized (mGlobalLock) {
6895 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6896 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6897 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6898 dumpLastANRLocked(pw);
6899 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6900 dumpLastANRTracesLocked(pw);
6901 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6902 dumpActivityStarterLocked(pw, dumpPackage);
6903 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6904 dumpActivityContainersLocked(pw);
6905 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6906 if (getRecentTasks() != null) {
6907 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6908 }
6909 }
6910 }
6911 }
6912
6913 @Override
6914 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6915 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6916 int wakefulness) {
6917 synchronized (mGlobalLock) {
6918 if (mHomeProcess != null && (dumpPackage == null
6919 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6920 if (needSep) {
6921 pw.println();
6922 needSep = false;
6923 }
6924 pw.println(" mHomeProcess: " + mHomeProcess);
6925 }
6926 if (mPreviousProcess != null && (dumpPackage == null
6927 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6928 if (needSep) {
6929 pw.println();
6930 needSep = false;
6931 }
6932 pw.println(" mPreviousProcess: " + mPreviousProcess);
6933 }
6934 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6935 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6936 StringBuilder sb = new StringBuilder(128);
6937 sb.append(" mPreviousProcessVisibleTime: ");
6938 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6939 pw.println(sb);
6940 }
6941 if (mHeavyWeightProcess != null && (dumpPackage == null
6942 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6943 if (needSep) {
6944 pw.println();
6945 needSep = false;
6946 }
6947 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6948 }
6949 if (dumpPackage == null) {
6950 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006951 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 }
6953 if (dumpAll) {
6954 if (dumpPackage == null) {
6955 pw.println(" mConfigWillChange: "
6956 + getTopDisplayFocusedStack().mConfigWillChange);
6957 }
6958 if (mCompatModePackages.getPackages().size() > 0) {
6959 boolean printed = false;
6960 for (Map.Entry<String, Integer> entry
6961 : mCompatModePackages.getPackages().entrySet()) {
6962 String pkg = entry.getKey();
6963 int mode = entry.getValue();
6964 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6965 continue;
6966 }
6967 if (!printed) {
6968 pw.println(" mScreenCompatPackages:");
6969 printed = true;
6970 }
6971 pw.println(" " + pkg + ": " + mode);
6972 }
6973 }
6974 }
6975
6976 if (dumpPackage == null) {
6977 pw.println(" mWakefulness="
6978 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006979 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006980 if (mRunningVoice != null) {
6981 pw.println(" mRunningVoice=" + mRunningVoice);
6982 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6983 }
6984 pw.println(" mSleeping=" + mSleeping);
6985 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6986 pw.println(" mVrController=" + mVrController);
6987 }
6988 if (mCurAppTimeTracker != null) {
6989 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6990 }
6991 if (mAllowAppSwitchUids.size() > 0) {
6992 boolean printed = false;
6993 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6994 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6995 for (int j = 0; j < types.size(); j++) {
6996 if (dumpPackage == null ||
6997 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6998 if (needSep) {
6999 pw.println();
7000 needSep = false;
7001 }
7002 if (!printed) {
7003 pw.println(" mAllowAppSwitchUids:");
7004 printed = true;
7005 }
7006 pw.print(" User ");
7007 pw.print(mAllowAppSwitchUids.keyAt(i));
7008 pw.print(": Type ");
7009 pw.print(types.keyAt(j));
7010 pw.print(" = ");
7011 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7012 pw.println();
7013 }
7014 }
7015 }
7016 }
7017 if (dumpPackage == null) {
7018 if (mController != null) {
7019 pw.println(" mController=" + mController
7020 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7021 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007022 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7023 pw.println(" mLaunchingActivityWakeLock="
7024 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 }
7026
7027 return needSep;
7028 }
7029 }
7030
7031 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007032 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7033 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007034 synchronized (mGlobalLock) {
7035 if (dumpPackage == null) {
7036 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7037 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007038 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7039 if (mRunningVoice != null) {
7040 final long vrToken = proto.start(
7041 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7042 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7043 mRunningVoice.toString());
7044 mVoiceWakeLock.writeToProto(
7045 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7046 proto.end(vrToken);
7047 }
7048 mVrController.writeToProto(proto,
7049 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 if (mController != null) {
7051 final long token = proto.start(CONTROLLER);
7052 proto.write(CONTROLLER, mController.toString());
7053 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7054 proto.end(token);
7055 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007056 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7057 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7058 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007059 }
7060
7061 if (mHomeProcess != null && (dumpPackage == null
7062 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007063 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007064 }
7065
7066 if (mPreviousProcess != null && (dumpPackage == null
7067 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007068 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007069 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7070 }
7071
7072 if (mHeavyWeightProcess != null && (dumpPackage == null
7073 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007074 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007075 }
7076
7077 for (Map.Entry<String, Integer> entry
7078 : mCompatModePackages.getPackages().entrySet()) {
7079 String pkg = entry.getKey();
7080 int mode = entry.getValue();
7081 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7082 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7083 proto.write(PACKAGE, pkg);
7084 proto.write(MODE, mode);
7085 proto.end(compatToken);
7086 }
7087 }
7088
7089 if (mCurAppTimeTracker != null) {
7090 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7091 }
7092
7093 }
7094 }
7095
7096 @Override
7097 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7098 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7099 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007100 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7101 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 }
7103
7104 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007105 public void dumpForOom(PrintWriter pw) {
7106 synchronized (mGlobalLock) {
7107 pw.println(" mHomeProcess: " + mHomeProcess);
7108 pw.println(" mPreviousProcess: " + mPreviousProcess);
7109 if (mHeavyWeightProcess != null) {
7110 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7111 }
7112 }
7113 }
7114
7115 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007116 public boolean canGcNow() {
7117 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007118 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120 }
7121
Riddle Hsua0536432019-02-16 00:38:59 +08007122 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007123 @Override
7124 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007125 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 return top != null ? top.app : null;
7128 }
7129 }
7130
Riddle Hsua0536432019-02-16 00:38:59 +08007131 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007132 @Override
7133 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007134 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007135 if (mRootActivityContainer != null) {
7136 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138 }
7139 }
7140
7141 @Override
7142 public void scheduleDestroyAllActivities(String reason) {
7143 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007144 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146 }
7147
7148 @Override
7149 public void removeUser(int userId) {
7150 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007151 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007152 }
7153 }
7154
7155 @Override
7156 public boolean switchUser(int userId, UserState userState) {
7157 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007158 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007159 }
7160 }
7161
7162 @Override
7163 public void onHandleAppCrash(WindowProcessController wpc) {
7164 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007165 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 }
7167 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007168
7169 @Override
7170 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7171 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007172 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007173 }
7174 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007175
Riddle Hsua0536432019-02-16 00:38:59 +08007176 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007177 @Override
7178 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007179 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007180 }
7181
Riddle Hsua0536432019-02-16 00:38:59 +08007182 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007183 @Override
7184 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007185 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007186 }
7187
Riddle Hsua0536432019-02-16 00:38:59 +08007188 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007189 @Override
7190 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007191 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007192 }
7193
Riddle Hsua0536432019-02-16 00:38:59 +08007194 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007195 @Override
7196 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007197 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007198 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007199
7200 @Override
7201 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007202 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007203 mPendingTempWhitelist.put(uid, tag);
7204 }
7205 }
7206
7207 @Override
7208 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007209 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007210 mPendingTempWhitelist.remove(uid);
7211 }
7212 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007213
7214 @Override
7215 public boolean handleAppCrashInActivityController(String processName, int pid,
7216 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7217 Runnable killCrashingAppCallback) {
7218 synchronized (mGlobalLock) {
7219 if (mController == null) {
7220 return false;
7221 }
7222
7223 try {
7224 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7225 stackTrace)) {
7226 killCrashingAppCallback.run();
7227 return true;
7228 }
7229 } catch (RemoteException e) {
7230 mController = null;
7231 Watchdog.getInstance().setActivityController(null);
7232 }
7233 return false;
7234 }
7235 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007236
7237 @Override
7238 public void removeRecentTasksByPackageName(String packageName, int userId) {
7239 synchronized (mGlobalLock) {
7240 mRecentTasks.removeTasksByPackageName(packageName, userId);
7241 }
7242 }
7243
7244 @Override
7245 public void cleanupRecentTasksForUser(int userId) {
7246 synchronized (mGlobalLock) {
7247 mRecentTasks.cleanupLocked(userId);
7248 }
7249 }
7250
7251 @Override
7252 public void loadRecentTasksForUser(int userId) {
7253 synchronized (mGlobalLock) {
7254 mRecentTasks.loadUserRecentsLocked(userId);
7255 }
7256 }
7257
7258 @Override
7259 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7260 synchronized (mGlobalLock) {
7261 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7262 }
7263 }
7264
7265 @Override
7266 public void flushRecentTasks() {
7267 mRecentTasks.flush();
7268 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007269
7270 @Override
7271 public WindowProcessController getHomeProcess() {
7272 synchronized (mGlobalLock) {
7273 return mHomeProcess;
7274 }
7275 }
7276
7277 @Override
7278 public WindowProcessController getPreviousProcess() {
7279 synchronized (mGlobalLock) {
7280 return mPreviousProcess;
7281 }
7282 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007283
7284 @Override
7285 public void clearLockedTasks(String reason) {
7286 synchronized (mGlobalLock) {
7287 getLockTaskController().clearLockedTasks(reason);
7288 }
7289 }
7290
7291 @Override
7292 public void updateUserConfiguration() {
7293 synchronized (mGlobalLock) {
7294 final Configuration configuration = new Configuration(getGlobalConfiguration());
7295 final int currentUserId = mAmInternal.getCurrentUserId();
7296 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7297 configuration, currentUserId, Settings.System.canWrite(mContext));
7298 updateConfigurationLocked(configuration, null /* starting */,
7299 false /* initLocale */, false /* persistent */, currentUserId,
7300 false /* deferResume */);
7301 }
7302 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007303
7304 @Override
7305 public boolean canShowErrorDialogs() {
7306 synchronized (mGlobalLock) {
7307 return mShowDialogs && !mSleeping && !mShuttingDown
7308 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7309 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7310 mAmInternal.getCurrentUserId())
7311 && !(UserManager.isDeviceInDemoMode(mContext)
7312 && mAmInternal.getCurrentUser().isDemo());
7313 }
7314 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007315
7316 @Override
7317 public void setProfileApp(String profileApp) {
7318 synchronized (mGlobalLock) {
7319 mProfileApp = profileApp;
7320 }
7321 }
7322
7323 @Override
7324 public void setProfileProc(WindowProcessController wpc) {
7325 synchronized (mGlobalLock) {
7326 mProfileProc = wpc;
7327 }
7328 }
7329
7330 @Override
7331 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7332 synchronized (mGlobalLock) {
7333 mProfilerInfo = profilerInfo;
7334 }
7335 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007336
7337 @Override
7338 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7339 synchronized (mGlobalLock) {
7340 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7341 }
7342 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007343
7344 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007345 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7346 boolean reducedResolution) {
7347 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7348 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007349 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007350
7351 @Override
7352 public boolean isUidForeground(int uid) {
7353 synchronized (mGlobalLock) {
7354 return ActivityTaskManagerService.this.isUidForeground(uid);
7355 }
7356 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007357
7358 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007359 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007360 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007361 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007362 }
7363 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007364
7365 @Override
7366 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007367 // Translate package names into UIDs
7368 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007369 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007370 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7371 if (uid >= 0) {
7372 result.add(uid);
7373 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007374 }
7375 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007376 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007377 }
7378 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007379 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007380}