blob: 04dab4048e31767e4b6c2dcd715d6516f8e15611 [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;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
49import static android.os.Build.VERSION_CODES.N;
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;
Evan Rosky4505b352018-09-06 11:20:40 -070055import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
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;
Wale Ogunwale59507092018-10-29 09:00:30 -070086import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
87import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
Andrii Kulian7dd39bb2019-07-22 13:11:10 -070089import static com.android.server.wm.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.server.LocalServices;
249import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700250import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800251import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700253import com.android.server.am.ActivityManagerService;
254import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
255import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
256import com.android.server.am.AppTimeTracker;
257import com.android.server.am.BaseErrorDialog;
258import com.android.server.am.EventLogTags;
259import com.android.server.am.PendingIntentController;
260import com.android.server.am.PendingIntentRecord;
261import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900262import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700264import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800266import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100313 // How long we permit background activity starts after an activity in the process
314 // started or finished.
315 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316
Wale Ogunwale98875612018-10-12 07:53:02 -0700317 /** Used to indicate that an app transition should be animated. */
318 static final boolean ANIMATE = true;
319
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700320 /** Hardware-reported OpenGLES version. */
321 final int GL_ES_VERSION;
322
Wale Ogunwale31913b52018-10-13 08:29:31 -0700323 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
324 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
325 public static final String DUMP_LASTANR_CMD = "lastanr" ;
326 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
327 public static final String DUMP_STARTER_CMD = "starter" ;
328 public static final String DUMP_CONTAINERS_CMD = "containers" ;
329 public static final String DUMP_RECENTS_CMD = "recents" ;
330 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
331
Wale Ogunwale64258362018-10-16 15:13:37 -0700332 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
333 public static final int RELAUNCH_REASON_NONE = 0;
334 /** This activity is being relaunched due to windowing mode change. */
335 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
336 /** This activity is being relaunched due to a free-resize operation. */
337 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
338
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700339 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700340
Wale Ogunwalef6733932018-06-27 05:14:34 -0700341 /**
342 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
343 * change at runtime. Use mContext for non-UI purposes.
344 */
345 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700347 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700350 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700351 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800352 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800353 @VisibleForTesting
354 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 PowerManagerInternal mPowerManagerInternal;
356 private UsageStatsManagerInternal mUsageStatsInternal;
357
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700358 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 IntentFirewall mIntentFirewall;
360
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700361 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800362 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800363 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700364 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
366 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
367 *
368 * @see WindowManagerThreadPriorityBooster
369 */
370 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700371 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800372 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700373 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700374 private UserManagerService mUserManager;
375 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700376 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800377 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700378 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /** All processes currently running that might have a window organized by name. */
380 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100381 /** All processes we currently have running mapped by pid and uid */
382 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** This is the process holding what we currently consider to be the "home" activity. */
384 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700385 /** The currently running heavy-weight process, if any. */
386 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700387 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /**
389 * This is the process holding the activity the user last visited that is in a different process
390 * from the one they are currently in.
391 */
392 WindowProcessController mPreviousProcess;
393 /** The time at which the previous process was last visible. */
394 long mPreviousProcessVisibleTime;
395
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700396 /** List of intents that were used to start the most recent tasks. */
397 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700398 /** State of external calls telling us if the device is awake or asleep. */
399 private boolean mKeyguardShown = false;
400
401 // Wrapper around VoiceInteractionServiceManager
402 private AssistUtils mAssistUtils;
403
404 // VoiceInteraction session ID that changes for each new request except when
405 // being called for multi-window assist in a single session.
406 private int mViSessionId = 1000;
407
408 // How long to wait in getAssistContextExtras for the activity and foreground services
409 // to respond with the result.
410 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
411
412 // How long top wait when going through the modern assist (which doesn't need to block
413 // on getting this result before starting to launch its UI).
414 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
415
416 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
417 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
418
Alison Cichowlas3e340502018-08-07 17:15:01 -0400419 // Permission tokens are used to temporarily granted a trusted app the ability to call
420 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
421 // showing any appropriate error messages to the user.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
423 10 * MINUTE_IN_MILLIS;
424
425 // How long before the service actually expires a token. This is slightly longer than
426 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
427 // expiration exception.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
429 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
430
431 // How long the service will remember expired tokens, for the purpose of providing error
432 // messaging when a client uses an expired token.
433 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
434 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
435
436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700462 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
Ricky Wai906af482019-06-03 17:25:28 +0100507 /**
508 * Last stop app switches time, apps finished before this time cannot start background activity
509 * even if they are in grace period.
510 */
511 private long mLastStopAppSwitchesTime;
512
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 IActivityController mController = null;
514 boolean mControllerIsAMonkey = false;
515
Wale Ogunwale214f3482018-10-04 11:00:47 -0700516 final int mFactoryTest;
517
518 /** Used to control how we initialize the service. */
519 ComponentName mTopComponent;
520 String mTopAction = Intent.ACTION_MAIN;
521 String mTopData;
522
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800523 /** Profiling app information. */
524 String mProfileApp = null;
525 WindowProcessController mProfileProc = null;
526 ProfilerInfo mProfilerInfo = null;
527
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700528 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700529 * Dump of the activity state at the time of the last ANR. Cleared after
530 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
531 */
532 String mLastANRState;
533
534 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 * Used to retain an update lock when the foreground activity is in
536 * immersive mode.
537 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700538 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539
540 /**
541 * Packages that are being allowed to perform unrestricted app switches. Mapping is
542 * User -> Type -> uid.
543 */
544 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
545
546 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private int mThumbnailWidth;
548 private int mThumbnailHeight;
549 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700550
551 /**
552 * Flag that indicates if multi-window is enabled.
553 *
554 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
555 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
556 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
557 * At least one of the forms of multi-window must be enabled in order for this flag to be
558 * initialized to 'true'.
559 *
560 * @see #mSupportsSplitScreenMultiWindow
561 * @see #mSupportsFreeformWindowManagement
562 * @see #mSupportsPictureInPicture
563 * @see #mSupportsMultiDisplay
564 */
565 boolean mSupportsMultiWindow;
566 boolean mSupportsSplitScreenMultiWindow;
567 boolean mSupportsFreeformWindowManagement;
568 boolean mSupportsPictureInPicture;
569 boolean mSupportsMultiDisplay;
570 boolean mForceResizableActivities;
571
572 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
573
574 // VR Vr2d Display Id.
575 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700576
Wale Ogunwalef6733932018-06-27 05:14:34 -0700577 /**
578 * Set while we are wanting to sleep, to prevent any
579 * activities from being started/resumed.
580 *
581 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
582 *
583 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
584 * while in the sleep state until there is a pending transition out of sleep, in which case
585 * mSleeping is set to false, and remains false while awake.
586 *
587 * Whether mSleeping can quickly toggled between true/false without the device actually
588 * display changing states is undefined.
589 */
590 private boolean mSleeping = false;
591
592 /**
593 * The process state used for processes that are running the top activities.
594 * This changes between TOP and TOP_SLEEPING to following mSleeping.
595 */
596 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
597
598 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
599 // automatically. Important for devices without direct input devices.
600 private boolean mShowDialogs = true;
601
602 /** Set if we are shutting down the system, similar to sleeping. */
603 boolean mShuttingDown = false;
604
605 /**
606 * We want to hold a wake lock while running a voice interaction session, since
607 * this may happen with the screen off and we need to keep the CPU running to
608 * be able to continue to interact with the user.
609 */
610 PowerManager.WakeLock mVoiceWakeLock;
611
612 /**
613 * Set while we are running a voice interaction. This overrides sleeping while it is active.
614 */
615 IVoiceInteractionSession mRunningVoice;
616
617 /**
618 * The last resumed activity. This is identical to the current resumed activity most
619 * of the time but could be different when we're pausing one activity before we resume
620 * another activity.
621 */
622 ActivityRecord mLastResumedActivity;
623
624 /**
625 * The activity that is currently being traced as the active resumed activity.
626 *
627 * @see #updateResumedAppTrace
628 */
629 private @Nullable ActivityRecord mTracedResumedActivity;
630
631 /** If non-null, we are tracking the time the user spends in the currently focused app. */
632 AppTimeTracker mCurAppTimeTracker;
633
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700634 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700635
Wale Ogunwale53783742018-09-16 10:21:51 -0700636 /**
637 * Packages that the user has asked to have run in screen size
638 * compatibility mode instead of filling the screen.
639 */
640 CompatModePackages mCompatModePackages;
641
Wale Ogunwalef6733932018-06-27 05:14:34 -0700642 private FontScaleSettingObserver mFontScaleSettingObserver;
643
Ricky Wai96f5c352019-04-10 18:40:17 +0100644 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private final class FontScaleSettingObserver extends ContentObserver {
647 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
648 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
649
650 public FontScaleSettingObserver() {
651 super(mH);
652 final ContentResolver resolver = mContext.getContentResolver();
653 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
654 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
655 UserHandle.USER_ALL);
656 }
657
658 @Override
659 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
660 if (mFontScaleUri.equals(uri)) {
661 updateFontScaleIfNeeded(userId);
662 } else if (mHideErrorDialogsUri.equals(uri)) {
663 synchronized (mGlobalLock) {
664 updateShouldShowDialogsLocked(getGlobalConfiguration());
665 }
666 }
667 }
668 }
669
Riddle Hsua0536432019-02-16 00:38:59 +0800670 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
671 @Target(ElementType.METHOD)
672 @Retention(RetentionPolicy.SOURCE)
673 @interface HotPath {
674 int NONE = 0;
675 int OOM_ADJUSTMENT = 1;
676 int LRU_UPDATE = 2;
677 int PROCESS_CHANGE = 3;
678 int caller() default NONE;
679 }
680
Charles Chen8d98dd22018-12-26 17:36:54 +0800681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
682 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700683 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700684 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700685 mSystemThread = ActivityThread.currentActivityThread();
686 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700687 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800688 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700690 }
691
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 public void onSystemReady() {
693 synchronized (mGlobalLock) {
694 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
695 PackageManager.FEATURE_CANT_SAVE_STATE);
696 mAssistUtils = new AssistUtils(mContext);
697 mVrController.onSystemReady();
698 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700699 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700700 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700701 }
702
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700703 public void onInitPowerManagement() {
704 synchronized (mGlobalLock) {
705 mStackSupervisor.initPowerManagement();
706 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
707 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
708 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
709 mVoiceWakeLock.setReferenceCounted(false);
710 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700711 }
712
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700713 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700714 mFontScaleSettingObserver = new FontScaleSettingObserver();
715 }
716
Wale Ogunwale59507092018-10-29 09:00:30 -0700717 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean freeformWindowManagement =
719 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
720 || Settings.Global.getInt(
721 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
722
723 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
724 final boolean supportsPictureInPicture = supportsMultiWindow &&
725 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
726 final boolean supportsSplitScreenMultiWindow =
727 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
728 final boolean supportsMultiDisplay = mContext.getPackageManager()
729 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
731 final boolean forceResizable = Settings.Global.getInt(
732 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
733
734 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900735 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700736
737 final Configuration configuration = new Configuration();
738 Settings.System.getConfiguration(resolver, configuration);
739 if (forceRtl) {
740 // This will take care of setting the correct layout direction flags
741 configuration.setLayoutDirection(configuration.locale);
742 }
743
744 synchronized (mGlobalLock) {
745 mForceResizableActivities = forceResizable;
746 final boolean multiWindowFormEnabled = freeformWindowManagement
747 || supportsSplitScreenMultiWindow
748 || supportsPictureInPicture
749 || supportsMultiDisplay;
750 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
751 mSupportsMultiWindow = true;
752 mSupportsFreeformWindowManagement = freeformWindowManagement;
753 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
754 mSupportsPictureInPicture = supportsPictureInPicture;
755 mSupportsMultiDisplay = supportsMultiDisplay;
756 } else {
757 mSupportsMultiWindow = false;
758 mSupportsFreeformWindowManagement = false;
759 mSupportsSplitScreenMultiWindow = false;
760 mSupportsPictureInPicture = false;
761 mSupportsMultiDisplay = false;
762 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700763 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 // This happens before any activities are started, so we can change global configuration
765 // in-place.
766 updateConfigurationLocked(configuration, null, true);
767 final Configuration globalConfig = getGlobalConfiguration();
768 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
769
770 // Load resources only after the current configuration has been set.
771 final Resources res = mContext.getResources();
772 mThumbnailWidth = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_width);
774 mThumbnailHeight = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_height);
776
777 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
778 mFullscreenThumbnailScale = (float) res
779 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
780 (float) globalConfig.screenWidthDp;
781 } else {
782 mFullscreenThumbnailScale = res.getFraction(
783 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
784 }
785 }
786 }
787
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800788 public WindowManagerGlobalLock getGlobalLock() {
789 return mGlobalLock;
790 }
791
Yunfan Chen585f2932019-01-29 16:04:45 +0900792 /** For test purpose only. */
793 @VisibleForTesting
794 public ActivityTaskManagerInternal getAtmInternal() {
795 return mInternal;
796 }
797
Riddle Hsud93a6c42018-11-29 21:50:06 +0800798 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
799 Looper looper) {
800 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700803 final File systemDir = SystemServiceManager.ensureSystemDir();
804 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
805 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
808 mTempConfig.setToDefaults();
809 mTempConfig.setLocales(LocaleList.getDefault());
810 mConfigurationSeq = mTempConfig.seq = 1;
811 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800812 mRootActivityContainer = new RootActivityContainer(this);
813 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700817 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700819 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Michal Karpinski15486842019-04-25 17:33:42 +0100877 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
878 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
879 callingUid, callingPackage);
880 if (mode == AppOpsManager.MODE_DEFAULT) {
881 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
882 == PERMISSION_GRANTED;
883 }
884 return mode == AppOpsManager.MODE_ALLOWED;
885 }
886
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700887 @VisibleForTesting
888 protected void setRecentTasks(RecentTasks recentTasks) {
889 mRecentTasks = recentTasks;
890 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700891 }
892
893 RecentTasks getRecentTasks() {
894 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700895 }
896
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700897 ClientLifecycleManager getLifecycleManager() {
898 return mLifecycleManager;
899 }
900
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700901 ActivityStartController getActivityStartController() {
902 return mActivityStartController;
903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 TaskChangeNotificationController getTaskChangeNotificationController() {
906 return mTaskChangeNotificationController;
907 }
908
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700909 LockTaskController getLockTaskController() {
910 return mLockTaskController;
911 }
912
Yunfan Chen75157d72018-07-27 14:47:21 +0900913 /**
914 * Return the global configuration used by the process corresponding to the input pid. This is
915 * usually the global configuration with some overrides specific to that process.
916 */
917 Configuration getGlobalConfigurationForCallingPid() {
918 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800919 return getGlobalConfigurationForPid(pid);
920 }
921
922 /**
923 * Return the global configuration used by the process corresponding to the given pid.
924 */
925 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900926 if (pid == MY_PID || pid < 0) {
927 return getGlobalConfiguration();
928 }
929 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100930 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900931 return app != null ? app.getConfiguration() : getGlobalConfiguration();
932 }
933 }
934
935 /**
936 * Return the device configuration info used by the process corresponding to the input pid.
937 * The value is consistent with the global configuration for the process.
938 */
939 @Override
940 public ConfigurationInfo getDeviceConfigurationInfo() {
941 ConfigurationInfo config = new ConfigurationInfo();
942 synchronized (mGlobalLock) {
943 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
944 config.reqTouchScreen = globalConfig.touchscreen;
945 config.reqKeyboardType = globalConfig.keyboard;
946 config.reqNavigation = globalConfig.navigation;
947 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
948 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
949 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
950 }
951 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
952 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
954 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700955 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 }
957 return config;
958 }
959
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700961 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700962 }
963
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700964 public static final class Lifecycle extends SystemService {
965 private final ActivityTaskManagerService mService;
966
967 public Lifecycle(Context context) {
968 super(context);
969 mService = new ActivityTaskManagerService(context);
970 }
971
972 @Override
973 public void onStart() {
974 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700975 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700976 }
977
Garfield Tan891146c2018-10-09 12:14:00 -0700978 @Override
979 public void onUnlockUser(int userId) {
980 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800981 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700982 }
983 }
984
985 @Override
986 public void onCleanupUser(int userId) {
987 synchronized (mService.getGlobalLock()) {
988 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
989 }
990 }
991
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 public ActivityTaskManagerService getService() {
993 return mService;
994 }
995 }
996
997 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 public final int startActivity(IApplicationThread caller, String callingPackage,
999 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1000 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1001 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1002 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1003 UserHandle.getCallingUserId());
1004 }
1005
1006 @Override
1007 public final int startActivities(IApplicationThread caller, String callingPackage,
1008 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1009 int userId) {
1010 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 enforceNotIsolatedCaller(reason);
1012 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001014 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1015 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1016 reason, null /* originatingPendingIntent */,
1017 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001018 }
1019
1020 @Override
1021 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1022 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1023 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1024 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1025 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1026 true /*validateIncomingUser*/);
1027 }
1028
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001029 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1032 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001033 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001035 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1037
1038 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 .setCaller(caller)
1041 .setCallingPackage(callingPackage)
1042 .setResolvedType(resolvedType)
1043 .setResultTo(resultTo)
1044 .setResultWho(resultWho)
1045 .setRequestCode(requestCode)
1046 .setStartFlags(startFlags)
1047 .setProfilerInfo(profilerInfo)
1048 .setActivityOptions(bOptions)
1049 .setMayWait(userId)
1050 .execute();
1051
1052 }
1053
1054 @Override
1055 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1056 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1058 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 // Refuse possible leaked file descriptors
1060 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1061 throw new IllegalArgumentException("File descriptors passed in Intent");
1062 }
1063
1064 if (!(target instanceof PendingIntentRecord)) {
1065 throw new IllegalArgumentException("Bad PendingIntent object");
1066 }
1067
1068 PendingIntentRecord pir = (PendingIntentRecord)target;
1069
1070 synchronized (mGlobalLock) {
1071 // If this is coming from the currently resumed activity, it is
1072 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001073 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 if (stack.mResumedActivity != null &&
1075 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001076 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 }
1078 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001079 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082
1083 @Override
1084 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1085 Bundle bOptions) {
1086 // Refuse possible leaked file descriptors
1087 if (intent != null && intent.hasFileDescriptors()) {
1088 throw new IllegalArgumentException("File descriptors passed in Intent");
1089 }
1090 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1091
1092 synchronized (mGlobalLock) {
1093 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1094 if (r == null) {
1095 SafeActivityOptions.abort(options);
1096 return false;
1097 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001098 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // The caller is not running... d'oh!
1100 SafeActivityOptions.abort(options);
1101 return false;
1102 }
1103 intent = new Intent(intent);
1104 // The caller is not allowed to change the data.
1105 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1106 // And we are resetting to find the next component...
1107 intent.setComponent(null);
1108
1109 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1110
1111 ActivityInfo aInfo = null;
1112 try {
1113 List<ResolveInfo> resolves =
1114 AppGlobals.getPackageManager().queryIntentActivities(
1115 intent, r.resolvedType,
1116 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1117 UserHandle.getCallingUserId()).getList();
1118
1119 // Look for the original activity in the list...
1120 final int N = resolves != null ? resolves.size() : 0;
1121 for (int i=0; i<N; i++) {
1122 ResolveInfo rInfo = resolves.get(i);
1123 if (rInfo.activityInfo.packageName.equals(r.packageName)
1124 && rInfo.activityInfo.name.equals(r.info.name)) {
1125 // We found the current one... the next matching is
1126 // after it.
1127 i++;
1128 if (i<N) {
1129 aInfo = resolves.get(i).activityInfo;
1130 }
1131 if (debug) {
1132 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1133 + "/" + r.info.name);
1134 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1135 ? "null" : aInfo.packageName + "/" + aInfo.name));
1136 }
1137 break;
1138 }
1139 }
1140 } catch (RemoteException e) {
1141 }
1142
1143 if (aInfo == null) {
1144 // Nobody who is next!
1145 SafeActivityOptions.abort(options);
1146 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1147 return false;
1148 }
1149
1150 intent.setComponent(new ComponentName(
1151 aInfo.applicationInfo.packageName, aInfo.name));
1152 intent.setFlags(intent.getFlags()&~(
1153 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1154 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1155 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1156 FLAG_ACTIVITY_NEW_TASK));
1157
1158 // Okay now we need to start the new activity, replacing the currently running activity.
1159 // This is a little tricky because we want to start the new one as if the current one is
1160 // finished, but not finish the current one first so that there is no flicker.
1161 // And thus...
1162 final boolean wasFinishing = r.finishing;
1163 r.finishing = true;
1164
1165 // Propagate reply information over to the new activity.
1166 final ActivityRecord resultTo = r.resultTo;
1167 final String resultWho = r.resultWho;
1168 final int requestCode = r.requestCode;
1169 r.resultTo = null;
1170 if (resultTo != null) {
1171 resultTo.removeResultsLocked(r, resultWho, requestCode);
1172 }
1173
1174 final long origId = Binder.clearCallingIdentity();
1175 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001176 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001178 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001179 .setResolvedType(r.resolvedType)
1180 .setActivityInfo(aInfo)
1181 .setResultTo(resultTo != null ? resultTo.appToken : null)
1182 .setResultWho(resultWho)
1183 .setRequestCode(requestCode)
1184 .setCallingPid(-1)
1185 .setCallingUid(r.launchedFromUid)
1186 .setCallingPackage(r.launchedFromPackage)
1187 .setRealCallingPid(-1)
1188 .setRealCallingUid(r.launchedFromUid)
1189 .setActivityOptions(options)
1190 .execute();
1191 Binder.restoreCallingIdentity(origId);
1192
1193 r.finishing = wasFinishing;
1194 if (res != ActivityManager.START_SUCCESS) {
1195 return false;
1196 }
1197 return true;
1198 }
1199 }
1200
1201 @Override
1202 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1203 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1204 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1205 final WaitResult res = new WaitResult();
1206 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001207 enforceNotIsolatedCaller("startActivityAndWait");
1208 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1209 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001211 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setCaller(caller)
1213 .setCallingPackage(callingPackage)
1214 .setResolvedType(resolvedType)
1215 .setResultTo(resultTo)
1216 .setResultWho(resultWho)
1217 .setRequestCode(requestCode)
1218 .setStartFlags(startFlags)
1219 .setActivityOptions(bOptions)
1220 .setMayWait(userId)
1221 .setProfilerInfo(profilerInfo)
1222 .setWaitResult(res)
1223 .execute();
1224 }
1225 return res;
1226 }
1227
1228 @Override
1229 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1230 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1231 int startFlags, Configuration config, Bundle bOptions, int userId) {
1232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001233 enforceNotIsolatedCaller("startActivityWithConfig");
1234 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1235 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001237 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .setCaller(caller)
1239 .setCallingPackage(callingPackage)
1240 .setResolvedType(resolvedType)
1241 .setResultTo(resultTo)
1242 .setResultWho(resultWho)
1243 .setRequestCode(requestCode)
1244 .setStartFlags(startFlags)
1245 .setGlobalConfiguration(config)
1246 .setActivityOptions(bOptions)
1247 .setMayWait(userId)
1248 .execute();
1249 }
1250 }
1251
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252
1253 @Override
1254 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1255 int callingUid = Binder.getCallingUid();
1256 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1257 throw new SecurityException("Only the system process can request a permission token, "
1258 + "received request from uid: " + callingUid);
1259 }
1260 IBinder permissionToken = new Binder();
1261 synchronized (mGlobalLock) {
1262 mStartActivitySources.put(permissionToken, delegatorToken);
1263 }
1264
1265 Message expireMsg = PooledLambda.obtainMessage(
1266 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1267 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1268
1269 Message forgetMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1272
1273 return permissionToken;
1274 }
1275
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 @Override
1277 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1278 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1280 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 // permission grants) as any app that may launch one of your own activities. So we only
1283 // allow this in two cases:
1284 // 1) The caller is an activity that is part of the core framework, and then only when it
1285 // is running as the system.
1286 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1287 // can only be requested by a system activity, which may then delegate this call to
1288 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 final ActivityRecord sourceRecord;
1290 final int targetUid;
1291 final String targetPackage;
1292 final boolean isResolver;
1293 synchronized (mGlobalLock) {
1294 if (resultTo == null) {
1295 throw new SecurityException("Must be called from an activity");
1296 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001297 final IBinder sourceToken;
1298 if (permissionToken != null) {
1299 // To even attempt to use a permissionToken, an app must also have this signature
1300 // permission.
1301 mAmInternal.enforceCallingPermission(
1302 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1303 "startActivityAsCaller");
1304 // If called with a permissionToken, we want the sourceRecord from the delegator
1305 // activity that requested this token.
1306 sourceToken = mStartActivitySources.remove(permissionToken);
1307 if (sourceToken == null) {
1308 // Invalid permissionToken, check if it recently expired.
1309 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1310 throw new SecurityException("Called with expired permission token: "
1311 + permissionToken);
1312 } else {
1313 throw new SecurityException("Called with invalid permission token: "
1314 + permissionToken);
1315 }
1316 }
1317 } else {
1318 // This method was called directly by the source.
1319 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321
Wale Ogunwaled32da472018-11-16 07:19:28 -08001322 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323 if (sourceRecord == null) {
1324 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 }
1326 if (sourceRecord.app == null) {
1327 throw new SecurityException("Called without a process attached to activity");
1328 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329
1330 // Whether called directly or from a delegate, the source activity must be from the
1331 // android package.
1332 if (!sourceRecord.info.packageName.equals("android")) {
1333 throw new SecurityException("Must be called from an activity that is "
1334 + "declared in the android package");
1335 }
1336
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001337 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 // This is still okay, as long as this activity is running under the
1339 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001342 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 + " must be system uid or original calling uid "
1344 + sourceRecord.launchedFromUid);
1345 }
1346 }
1347 if (ignoreTargetSecurity) {
1348 if (intent.getComponent() == null) {
1349 throw new SecurityException(
1350 "Component must be specified with ignoreTargetSecurity");
1351 }
1352 if (intent.getSelector() != null) {
1353 throw new SecurityException(
1354 "Selector not allowed with ignoreTargetSecurity");
1355 }
1356 }
1357 targetUid = sourceRecord.launchedFromUid;
1358 targetPackage = sourceRecord.launchedFromPackage;
1359 isResolver = sourceRecord.isResolverOrChildActivity();
1360 }
1361
1362 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001363 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 }
1365
1366 // TODO: Switch to user app stacks here.
1367 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001368 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 .setCallingUid(targetUid)
1370 .setCallingPackage(targetPackage)
1371 .setResolvedType(resolvedType)
1372 .setResultTo(resultTo)
1373 .setResultWho(resultWho)
1374 .setRequestCode(requestCode)
1375 .setStartFlags(startFlags)
1376 .setActivityOptions(bOptions)
1377 .setMayWait(userId)
1378 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1379 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001380 // The target may well be in the background, which would normally prevent it
1381 // from starting an activity. Here we definitely want the start to succeed.
1382 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 .execute();
1384 } catch (SecurityException e) {
1385 // XXX need to figure out how to propagate to original app.
1386 // A SecurityException here is generally actually a fault of the original
1387 // calling activity (such as a fairly granting permissions), so propagate it
1388 // back to them.
1389 /*
1390 StringBuilder msg = new StringBuilder();
1391 msg.append("While launching");
1392 msg.append(intent.toString());
1393 msg.append(": ");
1394 msg.append(e.getMessage());
1395 */
1396 throw e;
1397 }
1398 }
1399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1401 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1402 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1403 }
1404
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 @Override
1406 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1407 Intent intent, String resolvedType, IVoiceInteractionSession session,
1408 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1409 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 if (session == null || interactor == null) {
1412 throw new NullPointerException("null session or interactor");
1413 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001416 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 .setCallingUid(callingUid)
1418 .setCallingPackage(callingPackage)
1419 .setResolvedType(resolvedType)
1420 .setVoiceSession(session)
1421 .setVoiceInteractor(interactor)
1422 .setStartFlags(startFlags)
1423 .setProfilerInfo(profilerInfo)
1424 .setActivityOptions(bOptions)
1425 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001426 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .execute();
1428 }
1429
1430 @Override
1431 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1432 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001433 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1434 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001436 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .setCallingUid(callingUid)
1438 .setCallingPackage(callingPackage)
1439 .setResolvedType(resolvedType)
1440 .setActivityOptions(bOptions)
1441 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
Riddle Hsu609a8e22019-06-27 16:46:29 -06001446 /**
1447 * Start the recents activity to perform the recents animation.
1448 *
1449 * @param intent The intent to start the recents activity.
1450 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1451 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001453 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1454 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001457 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 final long origId = Binder.clearCallingIdentity();
1459 try {
1460 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001461 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1462 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001463 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464
1465 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001466 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001467 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001468 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 if (recentsAnimationRunner == null) {
1470 anim.preloadRecentsActivity();
1471 } else {
1472 anim.startRecentsActivity(recentsAnimationRunner);
1473 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 }
1475 } finally {
1476 Binder.restoreCallingIdentity(origId);
1477 }
1478 }
1479
1480 @Override
1481 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 "startActivityFromRecents()");
1484
1485 final int callingPid = Binder.getCallingPid();
1486 final int callingUid = Binder.getCallingUid();
1487 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1488 final long origId = Binder.clearCallingIdentity();
1489 try {
1490 synchronized (mGlobalLock) {
1491 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1492 safeOptions);
1493 }
1494 } finally {
1495 Binder.restoreCallingIdentity(origId);
1496 }
1497 }
1498
1499 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001500 * Public API to check if the client is allowed to start an activity on specified display.
1501 *
1502 * If the target display is private or virtual, some restrictions will apply.
1503 *
1504 * @param displayId Target display id.
1505 * @param intent Intent used to launch the activity.
1506 * @param resolvedType The MIME type of the intent.
1507 * @param userId The id of the user for whom the call is made.
1508 * @return {@code true} if a call to start an activity on the target display should succeed and
1509 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1510 */
1511 @Override
1512 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1513 String resolvedType, int userId) {
1514 final int callingUid = Binder.getCallingUid();
1515 final int callingPid = Binder.getCallingPid();
1516 final long origId = Binder.clearCallingIdentity();
1517
1518 try {
1519 // Collect information about the target of the Intent.
1520 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1521 0 /* startFlags */, null /* profilerInfo */, userId,
1522 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1523 UserHandle.USER_NULL));
1524 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1525
1526 synchronized (mGlobalLock) {
1527 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1528 aInfo);
1529 }
1530 } finally {
1531 Binder.restoreCallingIdentity(origId);
1532 }
1533 }
1534
1535 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001536 * This is the internal entry point for handling Activity.finish().
1537 *
1538 * @param token The Binder token referencing the Activity we want to finish.
1539 * @param resultCode Result code, if any, from this Activity.
1540 * @param resultData Result data (Intent), if any, from this Activity.
1541 * @param finishTask Whether to finish the task associated with this Activity.
1542 *
1543 * @return Returns true if the activity successfully finished, or false if it is still running.
1544 */
1545 @Override
1546 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1547 int finishTask) {
1548 // Refuse possible leaked file descriptors
1549 if (resultData != null && resultData.hasFileDescriptors()) {
1550 throw new IllegalArgumentException("File descriptors passed in Intent");
1551 }
1552
1553 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001554 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 if (r == null) {
1556 return true;
1557 }
1558 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001559 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001560 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 if (rootR == null) {
1562 Slog.w(TAG, "Finishing task with all activities already finished");
1563 }
1564 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1565 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001566 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 return false;
1568 }
1569
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001570 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1571 // We should consolidate.
1572 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001574 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 if (next != null) {
1576 // ask watcher if this is allowed
1577 boolean resumeOK = true;
1578 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001579 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001581 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 Watchdog.getInstance().setActivityController(null);
1583 }
1584
1585 if (!resumeOK) {
1586 Slog.i(TAG, "Not finishing activity because controller resumed");
1587 return false;
1588 }
1589 }
1590 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001591
1592 // note down that the process has finished an activity and is in background activity
1593 // starts grace period
1594 if (r.app != null) {
1595 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1596 }
1597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 final long origId = Binder.clearCallingIdentity();
1599 try {
1600 boolean res;
1601 final boolean finishWithRootActivity =
1602 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1603 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1604 || (finishWithRootActivity && r == rootR)) {
1605 // If requested, remove the task that is associated to this activity only if it
1606 // was the root activity in the task. The result code and data is ignored
1607 // because we don't support returning them across task boundaries. Also, to
1608 // keep backwards compatibility we remove the task from recents when finishing
1609 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001610 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 finishWithRootActivity, "finish-activity");
1612 if (!res) {
1613 Slog.i(TAG, "Removing task failed to finish activity");
1614 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001615 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001616 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 } else {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07001618 r.finishIfPossible(resultCode, resultData, "app-request",
1619 true /* oomAdj */, !PAUSE_IMMEDIATELY);
Andrii Kulian40eda672019-07-30 15:05:57 -07001620 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 if (!res) {
1622 Slog.i(TAG, "Failed to finish by app-request");
1623 }
1624 }
1625 return res;
1626 } finally {
1627 Binder.restoreCallingIdentity(origId);
1628 }
1629 }
1630 }
1631
1632 @Override
1633 public boolean finishActivityAffinity(IBinder token) {
1634 synchronized (mGlobalLock) {
1635 final long origId = Binder.clearCallingIdentity();
1636 try {
1637 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1638 if (r == null) {
1639 return false;
1640 }
1641
1642 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1643 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001644 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 return false;
1646 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001647 r.finishActivityAffinity();
1648 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 } finally {
1650 Binder.restoreCallingIdentity(origId);
1651 }
1652 }
1653 }
1654
1655 @Override
1656 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1657 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001658 try {
1659 WindowProcessController proc = null;
1660 synchronized (mGlobalLock) {
1661 ActivityStack stack = ActivityRecord.getStackLocked(token);
1662 if (stack == null) {
1663 return;
1664 }
1665 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1666 false /* fromTimeout */, false /* processPausingActivities */, config);
1667 if (r != null) {
1668 proc = r.app;
1669 }
1670 if (stopProfiling && proc != null) {
1671 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 }
1673 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001674 } finally {
1675 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 }
1678
1679 @Override
1680 public final void activityResumed(IBinder token) {
1681 final long origId = Binder.clearCallingIdentity();
1682 synchronized (mGlobalLock) {
1683 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001684 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 }
1686 Binder.restoreCallingIdentity(origId);
1687 }
1688
1689 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001690 public final void activityTopResumedStateLost() {
1691 final long origId = Binder.clearCallingIdentity();
1692 synchronized (mGlobalLock) {
1693 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1694 }
1695 Binder.restoreCallingIdentity(origId);
1696 }
1697
1698 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 public final void activityPaused(IBinder token) {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 ActivityStack stack = ActivityRecord.getStackLocked(token);
1703 if (stack != null) {
1704 stack.activityPausedLocked(token, false);
1705 }
1706 }
1707 Binder.restoreCallingIdentity(origId);
1708 }
1709
1710 @Override
1711 public final void activityStopped(IBinder token, Bundle icicle,
1712 PersistableBundle persistentState, CharSequence description) {
1713 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1714
1715 // Refuse possible leaked file descriptors
1716 if (icicle != null && icicle.hasFileDescriptors()) {
1717 throw new IllegalArgumentException("File descriptors passed in Bundle");
1718 }
1719
1720 final long origId = Binder.clearCallingIdentity();
1721
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001722 String restartingName = null;
1723 int restartingUid = 0;
1724 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001728 if (r.attachedToProcess()
1729 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1730 // The activity was requested to restart from
1731 // {@link #restartActivityProcessIfVisible}.
1732 restartingName = r.app.mName;
1733 restartingUid = r.app.mUid;
1734 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 r.activityStoppedLocked(icicle, persistentState, description);
1736 }
1737 }
1738
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001739 if (restartingName != null) {
1740 // In order to let the foreground activity can be restarted with its saved state from
1741 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1742 // until the activity reports stopped with the state. And the activity record will be
1743 // kept because the record state is restarting, then the activity will be restarted
1744 // immediately if it is still the top one.
1745 mStackSupervisor.removeRestartTimeouts(r);
1746 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1747 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001748 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749
1750 Binder.restoreCallingIdentity(origId);
1751 }
1752
1753 @Override
1754 public final void activityDestroyed(IBinder token) {
1755 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1756 synchronized (mGlobalLock) {
1757 ActivityStack stack = ActivityRecord.getStackLocked(token);
1758 if (stack != null) {
1759 stack.activityDestroyedLocked(token, "activityDestroyed");
1760 }
1761 }
1762 }
1763
1764 @Override
1765 public final void activityRelaunched(IBinder token) {
1766 final long origId = Binder.clearCallingIdentity();
1767 synchronized (mGlobalLock) {
1768 mStackSupervisor.activityRelaunchedLocked(token);
1769 }
1770 Binder.restoreCallingIdentity(origId);
1771 }
1772
1773 public final void activitySlept(IBinder token) {
1774 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1775
1776 final long origId = Binder.clearCallingIdentity();
1777
1778 synchronized (mGlobalLock) {
1779 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1780 if (r != null) {
1781 mStackSupervisor.activitySleptLocked(r);
1782 }
1783 }
1784
1785 Binder.restoreCallingIdentity(origId);
1786 }
1787
1788 @Override
1789 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1790 synchronized (mGlobalLock) {
1791 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1792 if (r == null) {
1793 return;
1794 }
1795 final long origId = Binder.clearCallingIdentity();
1796 try {
1797 r.setRequestedOrientation(requestedOrientation);
1798 } finally {
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801 }
1802 }
1803
1804 @Override
1805 public int getRequestedOrientation(IBinder token) {
1806 synchronized (mGlobalLock) {
1807 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1808 if (r == null) {
1809 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1810 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001811 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 }
1814
1815 @Override
1816 public void setImmersive(IBinder token, boolean immersive) {
1817 synchronized (mGlobalLock) {
1818 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1819 if (r == null) {
1820 throw new IllegalArgumentException();
1821 }
1822 r.immersive = immersive;
1823
1824 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001825 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 }
1829 }
1830 }
1831
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001832 void applyUpdateLockStateLocked(ActivityRecord r) {
1833 // Modifications to the UpdateLock state are done on our handler, outside
1834 // the activity manager's locks. The new state is determined based on the
1835 // state *now* of the relevant activity record. The object is passed to
1836 // the handler solely for logging detail, not to be consulted/modified.
1837 final boolean nextState = r != null && r.immersive;
1838 mH.post(() -> {
1839 if (mUpdateLock.isHeld() != nextState) {
1840 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1841 "Applying new update lock state '" + nextState + "' for " + r);
1842 if (nextState) {
1843 mUpdateLock.acquire();
1844 } else {
1845 mUpdateLock.release();
1846 }
1847 }
1848 });
1849 }
1850
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 @Override
1852 public boolean isImmersive(IBinder token) {
1853 synchronized (mGlobalLock) {
1854 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 throw new IllegalArgumentException();
1857 }
1858 return r.immersive;
1859 }
1860 }
1861
1862 @Override
1863 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001864 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001866 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 return (r != null) ? r.immersive : false;
1868 }
1869 }
1870
1871 @Override
1872 public void overridePendingTransition(IBinder token, String packageName,
1873 int enterAnim, int exitAnim) {
1874 synchronized (mGlobalLock) {
1875 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1876 if (self == null) {
1877 return;
1878 }
1879
1880 final long origId = Binder.clearCallingIdentity();
1881
1882 if (self.isState(
1883 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001884 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001885 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 }
1887
1888 Binder.restoreCallingIdentity(origId);
1889 }
1890 }
1891
1892 @Override
1893 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001894 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001896 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001897 if (r == null) {
1898 return ActivityManager.COMPAT_MODE_UNKNOWN;
1899 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001900 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 }
1902 }
1903
1904 @Override
1905 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001908 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001910 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001911 if (r == null) {
1912 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1913 return;
1914 }
1915 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001916 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001917 }
1918 }
1919
1920 @Override
1921 public int getLaunchedFromUid(IBinder activityToken) {
1922 ActivityRecord srec;
1923 synchronized (mGlobalLock) {
1924 srec = ActivityRecord.forTokenLocked(activityToken);
1925 }
1926 if (srec == null) {
1927 return -1;
1928 }
1929 return srec.launchedFromUid;
1930 }
1931
1932 @Override
1933 public String getLaunchedFromPackage(IBinder activityToken) {
1934 ActivityRecord srec;
1935 synchronized (mGlobalLock) {
1936 srec = ActivityRecord.forTokenLocked(activityToken);
1937 }
1938 if (srec == null) {
1939 return null;
1940 }
1941 return srec.launchedFromPackage;
1942 }
1943
1944 @Override
1945 public boolean convertFromTranslucent(IBinder token) {
1946 final long origId = Binder.clearCallingIdentity();
1947 try {
1948 synchronized (mGlobalLock) {
1949 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1950 if (r == null) {
1951 return false;
1952 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001953 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(origId);
1957 }
1958 }
1959
1960 @Override
1961 public boolean convertToTranslucent(IBinder token, Bundle options) {
1962 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1963 final long origId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
1966 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1967 if (r == null) {
1968 return false;
1969 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001970 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 int index = task.mActivities.lastIndexOf(r);
1972 if (index > 0) {
1973 ActivityRecord under = task.mActivities.get(index - 1);
1974 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1975 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001976 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001977 }
1978 } finally {
1979 Binder.restoreCallingIdentity(origId);
1980 }
1981 }
1982
1983 @Override
1984 public void notifyActivityDrawn(IBinder token) {
1985 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1986 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001987 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001989 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001990 }
1991 }
1992 }
1993
1994 @Override
1995 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1996 synchronized (mGlobalLock) {
1997 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1998 if (r == null) {
1999 return;
2000 }
2001 r.reportFullyDrawnLocked(restoredFromBundle);
2002 }
2003 }
2004
2005 @Override
2006 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2007 synchronized (mGlobalLock) {
2008 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2009 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2010 return stack.mDisplayId;
2011 }
2012 return DEFAULT_DISPLAY;
2013 }
2014 }
2015
2016 @Override
2017 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002018 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002019 long ident = Binder.clearCallingIdentity();
2020 try {
2021 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002022 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002024 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 }
2026 return null;
2027 }
2028 } finally {
2029 Binder.restoreCallingIdentity(ident);
2030 }
2031 }
2032
2033 @Override
2034 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002035 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002036 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2037 final long callingId = Binder.clearCallingIdentity();
2038 try {
2039 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002040 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002041 if (stack == null) {
2042 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2043 return;
2044 }
2045 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002046 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002047 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 }
2049 }
2050 } finally {
2051 Binder.restoreCallingIdentity(callingId);
2052 }
2053 }
2054
2055 @Override
2056 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002057 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2059 final long callingId = Binder.clearCallingIdentity();
2060 try {
2061 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002062 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002063 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (task == null) {
2065 return;
2066 }
2067 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002068 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002069 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 }
2071 }
2072 } finally {
2073 Binder.restoreCallingIdentity(callingId);
2074 }
2075 }
2076
2077 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002078 public void restartActivityProcessIfVisible(IBinder activityToken) {
2079 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2080 final long callingId = Binder.clearCallingIdentity();
2081 try {
2082 synchronized (mGlobalLock) {
2083 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2084 if (r == null) {
2085 return;
2086 }
2087 r.restartProcessIfVisible();
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(callingId);
2091 }
2092 }
2093
2094 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002096 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 synchronized (mGlobalLock) {
2098 final long ident = Binder.clearCallingIdentity();
2099 try {
2100 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2101 "remove-task");
2102 } finally {
2103 Binder.restoreCallingIdentity(ident);
2104 }
2105 }
2106 }
2107
2108 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002109 public void removeAllVisibleRecentTasks() {
2110 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2111 synchronized (mGlobalLock) {
2112 final long ident = Binder.clearCallingIdentity();
2113 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002114 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002115 } finally {
2116 Binder.restoreCallingIdentity(ident);
2117 }
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2123 synchronized (mGlobalLock) {
2124 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2125 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002126 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 }
2128 }
2129 return false;
2130 }
2131
2132 @Override
2133 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2134 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002135
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002136 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002137 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2138 if (r != null) {
2139 return r.getActivityStack().navigateUpToLocked(
2140 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002141 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002142 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 }
2144 }
2145
2146 /**
2147 * Attempts to move a task backwards in z-order (the order of activities within the task is
2148 * unchanged).
2149 *
2150 * There are several possible results of this call:
2151 * - if the task is locked, then we will show the lock toast
2152 * - if there is a task behind the provided task, then that task is made visible and resumed as
2153 * this task is moved to the back
2154 * - otherwise, if there are no other tasks in the stack:
2155 * - if this task is in the pinned stack, then we remove the stack completely, which will
2156 * have the effect of moving the task to the top or bottom of the fullscreen stack
2157 * (depending on whether it is visible)
2158 * - otherwise, we simply return home and hide this task
2159 *
2160 * @param token A reference to the activity we wish to move
2161 * @param nonRoot If false then this only works if the activity is the root
2162 * of a task; if true it will work for any activity in a task.
2163 * @return Returns true if the move completed, false if not.
2164 */
2165 @Override
2166 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002167 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 synchronized (mGlobalLock) {
2169 final long origId = Binder.clearCallingIdentity();
2170 try {
2171 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002172 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002173 if (task != null) {
2174 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2175 }
2176 } finally {
2177 Binder.restoreCallingIdentity(origId);
2178 }
2179 }
2180 return false;
2181 }
2182
2183 @Override
2184 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002185 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 long ident = Binder.clearCallingIdentity();
2187 Rect rect = new Rect();
2188 try {
2189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002190 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2192 if (task == null) {
2193 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2194 return rect;
2195 }
2196 if (task.getStack() != null) {
2197 // Return the bounds from window manager since it will be adjusted for various
2198 // things like the presense of a docked stack for tasks that aren't resizeable.
2199 task.getWindowContainerBounds(rect);
2200 } else {
2201 // Task isn't in window manager yet since it isn't associated with a stack.
2202 // Return the persist value from activity manager
2203 if (!task.matchParentBounds()) {
2204 rect.set(task.getBounds());
2205 } else if (task.mLastNonFullscreenBounds != null) {
2206 rect.set(task.mLastNonFullscreenBounds);
2207 }
2208 }
2209 }
2210 } finally {
2211 Binder.restoreCallingIdentity(ident);
2212 }
2213 return rect;
2214 }
2215
2216 @Override
2217 public ActivityManager.TaskDescription getTaskDescription(int id) {
2218 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002219 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002221 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2223 if (tr != null) {
2224 return tr.lastTaskDescription;
2225 }
2226 }
2227 return null;
2228 }
2229
2230 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002231 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2232 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2233 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2234 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2235 return;
2236 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002237 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002238 synchronized (mGlobalLock) {
2239 final long ident = Binder.clearCallingIdentity();
2240 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002241 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002242 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002243 if (task == null) {
2244 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2245 return;
2246 }
2247
2248 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2249 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2250
2251 if (!task.isActivityTypeStandardOrUndefined()) {
2252 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2253 + " non-standard task " + taskId + " to windowing mode="
2254 + windowingMode);
2255 }
2256
2257 final ActivityStack stack = task.getStack();
2258 if (toTop) {
2259 stack.moveToFront("setTaskWindowingMode", task);
2260 }
2261 stack.setWindowingMode(windowingMode);
2262 } finally {
2263 Binder.restoreCallingIdentity(ident);
2264 }
2265 }
2266 }
2267
2268 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002270 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271 ActivityRecord r = getCallingRecordLocked(token);
2272 return r != null ? r.info.packageName : null;
2273 }
2274 }
2275
2276 @Override
2277 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002278 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002279 ActivityRecord r = getCallingRecordLocked(token);
2280 return r != null ? r.intent.getComponent() : null;
2281 }
2282 }
2283
2284 private ActivityRecord getCallingRecordLocked(IBinder token) {
2285 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2286 if (r == null) {
2287 return null;
2288 }
2289 return r.resultTo;
2290 }
2291
2292 @Override
2293 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002294 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295
2296 synchronized (mGlobalLock) {
2297 final long origId = Binder.clearCallingIdentity();
2298 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002299 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 } finally {
2301 Binder.restoreCallingIdentity(origId);
2302 }
2303 }
2304 }
2305
Mark Renouf446251d2019-04-26 10:22:41 -04002306 @Override
2307 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2308 synchronized (mGlobalLock) {
2309 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2310 if (r == null) {
2311 return;
2312 }
2313 ActivityStack stack = r.getActivityStack();
2314 if (stack != null && stack.isSingleTaskInstance()) {
2315 // Single-task stacks are used for activities which are presented in floating
2316 // windows above full screen activities. Instead of directly finishing the
2317 // task, a task change listener is used to notify SystemUI so the action can be
2318 // handled specially.
2319 final TaskRecord task = r.getTaskRecord();
2320 mTaskChangeNotificationController
2321 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2322 } else {
2323 try {
2324 callback.requestFinish();
2325 } catch (RemoteException e) {
2326 Slog.e(TAG, "Failed to invoke request finish callback", e);
2327 }
2328 }
2329 }
2330 }
2331
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002332 /**
2333 * TODO: Add mController hook
2334 */
2335 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002336 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2337 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002338 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339
2340 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2341 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2343 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002344 }
2345 }
2346
Ricky Waiaca8a772019-04-04 16:01:06 +01002347 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2348 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002349 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002350
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 final int callingPid = Binder.getCallingPid();
2352 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002353 if (!isSameApp(callingUid, callingPackage)) {
2354 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2355 + Binder.getCallingPid() + " as package " + callingPackage;
2356 Slog.w(TAG, msg);
2357 throw new SecurityException(msg);
2358 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002359 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 SafeActivityOptions.abort(options);
2361 return;
2362 }
2363 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 WindowProcessController callerApp = null;
2365 if (appThread != null) {
2366 callerApp = getProcessController(appThread);
2367 }
2368 final ActivityStarter starter = getActivityStartController().obtainStarter(
2369 null /* intent */, "moveTaskToFront");
2370 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2371 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002372 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 return;
2374 }
2375 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002377 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 if (task == null) {
2379 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002380 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002381 return;
2382 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002383 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002385 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 return;
2387 }
2388 ActivityOptions realOptions = options != null
2389 ? options.getOptions(mStackSupervisor)
2390 : null;
2391 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2392 false /* forceNonResizable */);
2393
2394 final ActivityRecord topActivity = task.getTopActivity();
2395 if (topActivity != null) {
2396
2397 // We are reshowing a task, use a starting window to hide the initial draw delay
2398 // so the transition can start earlier.
2399 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2400 true /* taskSwitch */, fromRecents);
2401 }
2402 } finally {
2403 Binder.restoreCallingIdentity(origId);
2404 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 }
2406
Ricky Waiaca8a772019-04-04 16:01:06 +01002407 /**
2408 * Return true if callingUid is system, or packageName belongs to that callingUid.
2409 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002410 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002411 try {
2412 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2413 if (packageName == null) {
2414 return false;
2415 }
2416 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2417 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2418 UserHandle.getUserId(callingUid));
2419 return UserHandle.isSameApp(callingUid, uid);
2420 }
2421 } catch (RemoteException e) {
2422 // Should not happen
2423 }
2424 return true;
2425 }
2426
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002427 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2428 int callingPid, int callingUid, String name) {
2429 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2430 return true;
2431 }
2432
2433 if (getRecentTasks().isCallerRecents(sourceUid)) {
2434 return true;
2435 }
2436
2437 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2438 if (perm == PackageManager.PERMISSION_GRANTED) {
2439 return true;
2440 }
2441 if (checkAllowAppSwitchUid(sourceUid)) {
2442 return true;
2443 }
2444
2445 // If the actual IPC caller is different from the logical source, then
2446 // also see if they are allowed to control app switches.
2447 if (callingUid != -1 && callingUid != sourceUid) {
2448 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2449 if (perm == PackageManager.PERMISSION_GRANTED) {
2450 return true;
2451 }
2452 if (checkAllowAppSwitchUid(callingUid)) {
2453 return true;
2454 }
2455 }
2456
2457 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2458 return false;
2459 }
2460
2461 private boolean checkAllowAppSwitchUid(int uid) {
2462 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2463 if (types != null) {
2464 for (int i = types.size() - 1; i >= 0; i--) {
2465 if (types.valueAt(i).intValue() == uid) {
2466 return true;
2467 }
2468 }
2469 }
2470 return false;
2471 }
2472
2473 @Override
2474 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2475 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2476 "setActivityController()");
2477 synchronized (mGlobalLock) {
2478 mController = controller;
2479 mControllerIsAMonkey = imAMonkey;
2480 Watchdog.getInstance().setActivityController(controller);
2481 }
2482 }
2483
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002484 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002485 synchronized (mGlobalLock) {
2486 return mController != null && mControllerIsAMonkey;
2487 }
2488 }
2489
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 @Override
2491 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2492 synchronized (mGlobalLock) {
2493 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2494 }
2495 }
2496
2497 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002498 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2499 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2500 }
2501
2502 @Override
2503 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2504 @WindowConfiguration.ActivityType int ignoreActivityType,
2505 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2506 final int callingUid = Binder.getCallingUid();
2507 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2508
2509 synchronized (mGlobalLock) {
2510 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2511
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002512 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002513 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002514 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 ignoreWindowingMode, callingUid, allowed);
2516 }
2517
2518 return list;
2519 }
2520
2521 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002522 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2523 synchronized (mGlobalLock) {
2524 final long origId = Binder.clearCallingIdentity();
2525 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2526 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002527 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 }
2529 Binder.restoreCallingIdentity(origId);
2530 }
2531 }
2532
2533 @Override
2534 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002535 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 ActivityStack stack = ActivityRecord.getStackLocked(token);
2537 if (stack != null) {
2538 return stack.willActivityBeVisibleLocked(token);
2539 }
2540 return false;
2541 }
2542 }
2543
2544 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002545 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002546 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002547 synchronized (mGlobalLock) {
2548 final long ident = Binder.clearCallingIdentity();
2549 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 if (task == null) {
2552 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2553 return;
2554 }
2555
2556 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2557 + " to stackId=" + stackId + " toTop=" + toTop);
2558
Wale Ogunwaled32da472018-11-16 07:19:28 -08002559 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002560 if (stack == null) {
2561 throw new IllegalStateException(
2562 "moveTaskToStack: No stack for stackId=" + stackId);
2563 }
2564 if (!stack.isActivityTypeStandardOrUndefined()) {
2565 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2566 + taskId + " to stack " + stackId);
2567 }
2568 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002569 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002570 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2571 }
2572 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2573 "moveTaskToStack");
2574 } finally {
2575 Binder.restoreCallingIdentity(ident);
2576 }
2577 }
2578 }
2579
2580 @Override
2581 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2582 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002583 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002584
2585 final long ident = Binder.clearCallingIdentity();
2586 try {
2587 synchronized (mGlobalLock) {
2588 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002589 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 if (stack == null) {
2591 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2592 return;
2593 }
2594 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2595 throw new IllegalArgumentException("Stack: " + stackId
2596 + " doesn't support animated resize.");
2597 }
2598 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2599 animationDuration, false /* fromFullscreen */);
2600 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002601 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 if (stack == null) {
2603 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2604 return;
2605 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002606 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2608 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2609 }
2610 }
2611 } finally {
2612 Binder.restoreCallingIdentity(ident);
2613 }
2614 }
2615
wilsonshih5c4cf522019-01-25 09:03:47 +08002616 @Override
2617 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2618 int animationDuration) {
2619 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2620
2621 final long ident = Binder.clearCallingIdentity();
2622 try {
2623 synchronized (mGlobalLock) {
2624 if (xOffset == 0 && yOffset == 0) {
2625 return;
2626 }
2627 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2628 if (stack == null) {
2629 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2630 return;
2631 }
2632 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2633 throw new IllegalArgumentException("Stack: " + stackId
2634 + " doesn't support animated resize.");
2635 }
2636 final Rect destBounds = new Rect();
2637 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002638 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002639 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2640 return;
2641 }
2642 destBounds.offset(xOffset, yOffset);
2643 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2644 animationDuration, false /* fromFullscreen */);
2645 }
2646 } finally {
2647 Binder.restoreCallingIdentity(ident);
2648 }
2649 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002650 /**
2651 * Moves the specified task to the primary-split-screen stack.
2652 *
2653 * @param taskId Id of task to move.
2654 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2655 * exist already. See
2656 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2657 * and
2658 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2659 * @param toTop If the task and stack should be moved to the top.
2660 * @param animate Whether we should play an animation for the moving the task.
2661 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2662 * stack. Pass {@code null} to use default bounds.
2663 * @param showRecents If the recents activity should be shown on the other side of the task
2664 * going into split-screen mode.
2665 */
2666 @Override
2667 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2668 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002669 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002670 "setTaskWindowingModeSplitScreenPrimary()");
2671 synchronized (mGlobalLock) {
2672 final long ident = Binder.clearCallingIdentity();
2673 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002674 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002675 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 if (task == null) {
2677 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2678 return false;
2679 }
2680 if (DEBUG_STACK) Slog.d(TAG_STACK,
2681 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2682 + " to createMode=" + createMode + " toTop=" + toTop);
2683 if (!task.isActivityTypeStandardOrUndefined()) {
2684 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2685 + " non-standard task " + taskId + " to split-screen windowing mode");
2686 }
2687
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002688 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 final int windowingMode = task.getWindowingMode();
2690 final ActivityStack stack = task.getStack();
2691 if (toTop) {
2692 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2693 }
2694 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002695 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2696 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002697 return windowingMode != task.getWindowingMode();
2698 } finally {
2699 Binder.restoreCallingIdentity(ident);
2700 }
2701 }
2702 }
2703
2704 /**
2705 * Removes stacks in the input windowing modes from the system if they are of activity type
2706 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2707 */
2708 @Override
2709 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 "removeStacksInWindowingModes()");
2712
2713 synchronized (mGlobalLock) {
2714 final long ident = Binder.clearCallingIdentity();
2715 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002716 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 } finally {
2718 Binder.restoreCallingIdentity(ident);
2719 }
2720 }
2721 }
2722
2723 @Override
2724 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002725 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 "removeStacksWithActivityTypes()");
2727
2728 synchronized (mGlobalLock) {
2729 final long ident = Binder.clearCallingIdentity();
2730 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002731 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002737
2738 @Override
2739 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2740 int userId) {
2741 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002742 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2743 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 final boolean detailed = checkGetTasksPermission(
2746 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2747 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 == PackageManager.PERMISSION_GRANTED;
2749
2750 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002751 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 callingUid);
2753 }
2754 }
2755
2756 @Override
2757 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002758 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002759 long ident = Binder.clearCallingIdentity();
2760 try {
2761 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002762 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 }
2764 } finally {
2765 Binder.restoreCallingIdentity(ident);
2766 }
2767 }
2768
2769 @Override
2770 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002771 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 long ident = Binder.clearCallingIdentity();
2773 try {
2774 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002775 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 }
2777 } finally {
2778 Binder.restoreCallingIdentity(ident);
2779 }
2780 }
2781
2782 @Override
2783 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002785 final long callingUid = Binder.getCallingUid();
2786 final long origId = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mGlobalLock) {
2789 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002790 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2792 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2793 }
2794 } finally {
2795 Binder.restoreCallingIdentity(origId);
2796 }
2797 }
2798
2799 @Override
2800 public void startLockTaskModeByToken(IBinder token) {
2801 synchronized (mGlobalLock) {
2802 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2803 if (r == null) {
2804 return;
2805 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002806 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 }
2808 }
2809
2810 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002811 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002812 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 // This makes inner call to look as if it was initiated by system.
2814 long ident = Binder.clearCallingIdentity();
2815 try {
2816 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002817 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002818 MATCH_TASK_IN_STACKS_ONLY);
2819 if (task == null) {
2820 return;
2821 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822
2823 // When starting lock task mode the stack must be in front and focused
2824 task.getStack().moveToFront("startSystemLockTaskMode");
2825 startLockTaskModeLocked(task, true /* isSystemCaller */);
2826 }
2827 } finally {
2828 Binder.restoreCallingIdentity(ident);
2829 }
2830 }
2831
2832 @Override
2833 public void stopLockTaskModeByToken(IBinder token) {
2834 synchronized (mGlobalLock) {
2835 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2836 if (r == null) {
2837 return;
2838 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002839 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840 }
2841 }
2842
2843 /**
2844 * This API should be called by SystemUI only when user perform certain action to dismiss
2845 * lock task mode. We should only dismiss pinned lock task mode in this case.
2846 */
2847 @Override
2848 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002849 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2851 }
2852
2853 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2854 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2855 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2856 return;
2857 }
2858
Wale Ogunwaled32da472018-11-16 07:19:28 -08002859 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 if (stack == null || task != stack.topTask()) {
2861 throw new IllegalArgumentException("Invalid task, not in foreground");
2862 }
2863
2864 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2865 // system or a specific app.
2866 // * System-initiated requests will only start the pinned mode (screen pinning)
2867 // * App-initiated requests
2868 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2869 // - will start the pinned mode, otherwise
2870 final int callingUid = Binder.getCallingUid();
2871 long ident = Binder.clearCallingIdentity();
2872 try {
2873 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002874 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002876 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 } finally {
2878 Binder.restoreCallingIdentity(ident);
2879 }
2880 }
2881
2882 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2883 final int callingUid = Binder.getCallingUid();
2884 long ident = Binder.clearCallingIdentity();
2885 try {
2886 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002887 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 }
2889 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2890 // task and jumping straight into a call in the case of emergency call back.
2891 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2892 if (tm != null) {
2893 tm.showInCallScreen(false);
2894 }
2895 } finally {
2896 Binder.restoreCallingIdentity(ident);
2897 }
2898 }
2899
2900 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002901 public void updateLockTaskPackages(int userId, String[] packages) {
2902 final int callingUid = Binder.getCallingUid();
2903 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2904 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2905 "updateLockTaskPackages()");
2906 }
2907 synchronized (this) {
2908 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2909 + Arrays.toString(packages));
2910 getLockTaskController().updateLockTaskPackages(userId, packages);
2911 }
2912 }
2913
2914 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 public boolean isInLockTaskMode() {
2916 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2917 }
2918
2919 @Override
2920 public int getLockTaskModeState() {
2921 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002922 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 }
2924 }
2925
2926 @Override
2927 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2928 synchronized (mGlobalLock) {
2929 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2930 if (r != null) {
2931 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002932 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002934 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 }
2936 }
2937 }
2938
2939 @Override
2940 public Bundle getActivityOptions(IBinder token) {
2941 final long origId = Binder.clearCallingIdentity();
2942 try {
2943 synchronized (mGlobalLock) {
2944 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2945 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002946 final ActivityOptions activityOptions = r.takeOptionsLocked(
2947 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 return activityOptions == null ? null : activityOptions.toBundle();
2949 }
2950 return null;
2951 }
2952 } finally {
2953 Binder.restoreCallingIdentity(origId);
2954 }
2955 }
2956
2957 @Override
2958 public List<IBinder> getAppTasks(String callingPackage) {
2959 int callingUid = Binder.getCallingUid();
2960 long ident = Binder.clearCallingIdentity();
2961 try {
2962 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002963 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965 } finally {
2966 Binder.restoreCallingIdentity(ident);
2967 }
2968 }
2969
2970 @Override
2971 public void finishVoiceTask(IVoiceInteractionSession session) {
2972 synchronized (mGlobalLock) {
2973 final long origId = Binder.clearCallingIdentity();
2974 try {
2975 // TODO: VI Consider treating local voice interactions and voice tasks
2976 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002977 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 } finally {
2979 Binder.restoreCallingIdentity(origId);
2980 }
2981 }
2982
2983 }
2984
2985 @Override
2986 public boolean isTopOfTask(IBinder token) {
2987 synchronized (mGlobalLock) {
2988 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002989 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 }
2991 }
2992
2993 @Override
2994 public void notifyLaunchTaskBehindComplete(IBinder token) {
2995 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2996 }
2997
2998 @Override
2999 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003000 mH.post(() -> {
3001 synchronized (mGlobalLock) {
3002 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003003 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003004 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003005 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 } catch (RemoteException e) {
3007 }
3008 }
3009 }
3010
3011 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003012 }
3013
3014 /** Called from an app when assist data is ready. */
3015 @Override
3016 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3017 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003018 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003019 synchronized (pae) {
3020 pae.result = extras;
3021 pae.structure = structure;
3022 pae.content = content;
3023 if (referrer != null) {
3024 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3025 }
3026 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003027 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003028 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3029 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 structure.setHomeActivity(pae.isHome);
3031 }
3032 pae.haveResult = true;
3033 pae.notifyAll();
3034 if (pae.intent == null && pae.receiver == null) {
3035 // Caller is just waiting for the result.
3036 return;
3037 }
3038 }
3039 // We are now ready to launch the assist activity.
3040 IAssistDataReceiver sendReceiver = null;
3041 Bundle sendBundle = null;
3042 synchronized (mGlobalLock) {
3043 buildAssistBundleLocked(pae, extras);
3044 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003045 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 if (!exists) {
3047 // Timed out.
3048 return;
3049 }
3050
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 // Caller wants result sent back to them.
3053 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003054 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3055 pae.activity.getTaskRecord().taskId);
3056 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3057 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3059 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3060 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3061 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3062 }
3063 }
3064 if (sendReceiver != null) {
3065 try {
3066 sendReceiver.onHandleAssistData(sendBundle);
3067 } catch (RemoteException e) {
3068 }
3069 return;
3070 }
3071
3072 final long ident = Binder.clearCallingIdentity();
3073 try {
3074 if (TextUtils.equals(pae.intent.getAction(),
3075 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003076 // Start voice interaction through VoiceInteractionManagerService.
3077 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3078 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 } else {
3080 pae.intent.replaceExtras(pae.extras);
3081 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3082 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3083 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003084 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085
3086 try {
3087 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3088 } catch (ActivityNotFoundException e) {
3089 Slog.w(TAG, "No activity to handle assist action.", e);
3090 }
3091 }
3092 } finally {
3093 Binder.restoreCallingIdentity(ident);
3094 }
3095 }
3096
3097 @Override
3098 public int addAppTask(IBinder activityToken, Intent intent,
3099 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3100 final int callingUid = Binder.getCallingUid();
3101 final long callingIdent = Binder.clearCallingIdentity();
3102
3103 try {
3104 synchronized (mGlobalLock) {
3105 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3106 if (r == null) {
3107 throw new IllegalArgumentException("Activity does not exist; token="
3108 + activityToken);
3109 }
3110 ComponentName comp = intent.getComponent();
3111 if (comp == null) {
3112 throw new IllegalArgumentException("Intent " + intent
3113 + " must specify explicit component");
3114 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003115 if (thumbnail.getWidth() != mThumbnailWidth
3116 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 throw new IllegalArgumentException("Bad thumbnail size: got "
3118 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003119 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003120 }
3121 if (intent.getSelector() != null) {
3122 intent.setSelector(null);
3123 }
3124 if (intent.getSourceBounds() != null) {
3125 intent.setSourceBounds(null);
3126 }
3127 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3128 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3129 // The caller has added this as an auto-remove task... that makes no
3130 // sense, so turn off auto-remove.
3131 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3132 }
3133 }
3134 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3135 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3136 if (ainfo.applicationInfo.uid != callingUid) {
3137 throw new SecurityException(
3138 "Can't add task for another application: target uid="
3139 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3140 }
3141
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003142 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003144 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003146 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 // The app has too many tasks already and we can't add any more
3148 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3149 return INVALID_TASK_ID;
3150 }
3151 task.lastTaskDescription.copyFrom(description);
3152
3153 // TODO: Send the thumbnail to WM to store it.
3154
3155 return task.taskId;
3156 }
3157 } finally {
3158 Binder.restoreCallingIdentity(callingIdent);
3159 }
3160 }
3161
3162 @Override
3163 public Point getAppTaskThumbnailSize() {
3164 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003165 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 }
3167 }
3168
3169 @Override
3170 public void setTaskResizeable(int taskId, int resizeableMode) {
3171 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003172 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3174 if (task == null) {
3175 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3176 return;
3177 }
3178 task.setResizeMode(resizeableMode);
3179 }
3180 }
3181
3182 @Override
3183 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 long ident = Binder.clearCallingIdentity();
3186 try {
3187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003188 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003189 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003190 if (task == null) {
3191 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3192 return;
3193 }
3194 // Place the task in the right stack if it isn't there already based on
3195 // the requested bounds.
3196 // The stack transition logic is:
3197 // - a null bounds on a freeform task moves that task to fullscreen
3198 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3199 // that task to freeform
3200 // - otherwise the task is not moved
3201 ActivityStack stack = task.getStack();
3202 if (!task.getWindowConfiguration().canResizeTask()) {
3203 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3204 }
3205 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3206 stack = stack.getDisplay().getOrCreateStack(
3207 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3208 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3209 stack = stack.getDisplay().getOrCreateStack(
3210 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3211 }
3212
3213 // Reparent the task to the right stack if necessary
3214 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3215 if (stack != task.getStack()) {
3216 // Defer resume until the task is resized below
3217 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3218 DEFER_RESUME, "resizeTask");
3219 preserveWindow = false;
3220 }
3221
3222 // After reparenting (which only resizes the task to the stack bounds), resize the
3223 // task to the actual bounds provided
3224 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3225 }
3226 } finally {
3227 Binder.restoreCallingIdentity(ident);
3228 }
3229 }
3230
3231 @Override
3232 public boolean releaseActivityInstance(IBinder token) {
3233 synchronized (mGlobalLock) {
3234 final long origId = Binder.clearCallingIdentity();
3235 try {
3236 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3237 if (r == null) {
3238 return false;
3239 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003240 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 } finally {
3242 Binder.restoreCallingIdentity(origId);
3243 }
3244 }
3245 }
3246
3247 @Override
3248 public void releaseSomeActivities(IApplicationThread appInt) {
3249 synchronized (mGlobalLock) {
3250 final long origId = Binder.clearCallingIdentity();
3251 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003252 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003253 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 } finally {
3255 Binder.restoreCallingIdentity(origId);
3256 }
3257 }
3258 }
3259
3260 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003261 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003262 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003263 != PackageManager.PERMISSION_GRANTED) {
3264 throw new SecurityException("Requires permission "
3265 + android.Manifest.permission.DEVICE_POWER);
3266 }
3267
3268 synchronized (mGlobalLock) {
3269 long ident = Binder.clearCallingIdentity();
3270 if (mKeyguardShown != keyguardShowing) {
3271 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003272 final Message msg = PooledLambda.obtainMessage(
3273 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3274 keyguardShowing);
3275 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 }
3277 try {
wilsonshih177261f2019-02-22 12:02:18 +08003278 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 } finally {
3280 Binder.restoreCallingIdentity(ident);
3281 }
3282 }
3283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003284 mH.post(() -> {
3285 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3286 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3287 }
3288 });
3289 }
3290
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003291 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 mH.post(() -> {
3293 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3294 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3295 }
3296 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 }
3298
3299 @Override
3300 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3302 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003303
3304 final File passedIconFile = new File(filePath);
3305 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3306 passedIconFile.getName());
3307 if (!legitIconFile.getPath().equals(filePath)
3308 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3309 throw new IllegalArgumentException("Bad file path: " + filePath
3310 + " passed for userId " + userId);
3311 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003312 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 }
3314
3315 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003316 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3318 final ActivityOptions activityOptions = safeOptions != null
3319 ? safeOptions.getOptions(mStackSupervisor)
3320 : null;
3321 if (activityOptions == null
3322 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3323 || activityOptions.getCustomInPlaceResId() == 0) {
3324 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3325 "with valid animation");
3326 }
lumark588a3e82018-07-20 18:53:54 +08003327 // Get top display of front most application.
3328 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3329 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003330 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3331 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3332 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003333 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003334 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003335 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 }
3337
3338 @Override
3339 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 synchronized (mGlobalLock) {
3342 final long ident = Binder.clearCallingIdentity();
3343 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003344 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 if (stack == null) {
3346 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3347 return;
3348 }
3349 if (!stack.isActivityTypeStandardOrUndefined()) {
3350 throw new IllegalArgumentException(
3351 "Removing non-standard stack is not allowed.");
3352 }
3353 mStackSupervisor.removeStack(stack);
3354 } finally {
3355 Binder.restoreCallingIdentity(ident);
3356 }
3357 }
3358 }
3359
3360 @Override
3361 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003362 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363
3364 synchronized (mGlobalLock) {
3365 final long ident = Binder.clearCallingIdentity();
3366 try {
3367 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3368 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003369 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 } finally {
3371 Binder.restoreCallingIdentity(ident);
3372 }
3373 }
3374 }
3375
3376 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003377 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 synchronized (mGlobalLock) {
3379 long ident = Binder.clearCallingIdentity();
3380 try {
3381 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3382 if (r == null) {
3383 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003384 "toggleFreeformWindowingMode: No activity record matching token="
3385 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 }
3387
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003388 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003389 if (stack == null) {
3390 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3391 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003392 }
3393
Yunfan Chend967af82019-01-17 18:30:18 +09003394 if (!stack.inFreeformWindowingMode()
3395 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3396 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3397 + "toggle between fullscreen and freeform.");
3398 }
3399
3400 if (stack.inFreeformWindowingMode()) {
3401 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003402 } else if (stack.getParent().inFreeformWindowingMode()) {
3403 // If the window is on a freeform display, set it to undefined. It will be
3404 // resolved to freeform and it can adjust windowing mode when the display mode
3405 // changes in runtime.
3406 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003407 } else {
3408 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3409 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 } finally {
3411 Binder.restoreCallingIdentity(ident);
3412 }
3413 }
3414 }
3415
3416 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3417 @Override
3418 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003421 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423
3424 /** Unregister a task stack listener so that it stops receiving callbacks. */
3425 @Override
3426 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003427 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003429 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 }
3431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 @Override
3433 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3434 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3435 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3436 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3437 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3438 }
3439
3440 @Override
3441 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3442 IBinder activityToken, int flags) {
3443 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3444 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3445 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3446 }
3447
3448 @Override
3449 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3450 Bundle args) {
3451 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3452 true /* focused */, true /* newSessionId */, userHandle, args,
3453 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3454 }
3455
3456 @Override
3457 public Bundle getAssistContextExtras(int requestType) {
3458 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3459 null, null, true /* focused */, true /* newSessionId */,
3460 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3461 if (pae == null) {
3462 return null;
3463 }
3464 synchronized (pae) {
3465 while (!pae.haveResult) {
3466 try {
3467 pae.wait();
3468 } catch (InterruptedException e) {
3469 }
3470 }
3471 }
3472 synchronized (mGlobalLock) {
3473 buildAssistBundleLocked(pae, pae.result);
3474 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003475 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477 return pae.extras;
3478 }
3479
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003480 /**
3481 * Binder IPC calls go through the public entry point.
3482 * This can be called with or without the global lock held.
3483 */
3484 private static int checkCallingPermission(String permission) {
3485 return checkPermission(
3486 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3487 }
3488
3489 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003490 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003491 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3492 mAmInternal.enforceCallingPermission(permission, func);
3493 }
3494 }
3495
3496 @VisibleForTesting
3497 int checkGetTasksPermission(String permission, int pid, int uid) {
3498 return checkPermission(permission, pid, uid);
3499 }
3500
3501 static int checkPermission(String permission, int pid, int uid) {
3502 if (permission == null) {
3503 return PackageManager.PERMISSION_DENIED;
3504 }
3505 return checkComponentPermission(permission, pid, uid, -1, true);
3506 }
3507
Wale Ogunwale214f3482018-10-04 11:00:47 -07003508 public static int checkComponentPermission(String permission, int pid, int uid,
3509 int owningUid, boolean exported) {
3510 return ActivityManagerService.checkComponentPermission(
3511 permission, pid, uid, owningUid, exported);
3512 }
3513
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3515 if (getRecentTasks().isCallerRecents(callingUid)) {
3516 // Always allow the recents component to get tasks
3517 return true;
3518 }
3519
3520 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3521 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3522 if (!allowed) {
3523 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3524 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3525 // Temporary compatibility: some existing apps on the system image may
3526 // still be requesting the old permission and not switched to the new
3527 // one; if so, we'll still allow them full access. This means we need
3528 // to see if they are holding the old permission and are a system app.
3529 try {
3530 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3531 allowed = true;
3532 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3533 + " is using old GET_TASKS but privileged; allowing");
3534 }
3535 } catch (RemoteException e) {
3536 }
3537 }
3538 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3539 + " does not hold REAL_GET_TASKS; limiting output");
3540 }
3541 return allowed;
3542 }
3543
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3545 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3546 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3547 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003548 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003549 "enqueueAssistContext()");
3550
3551 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003552 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003553 if (activity == null) {
3554 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3555 return null;
3556 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003557 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3559 return null;
3560 }
3561 if (focused) {
3562 if (activityToken != null) {
3563 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3564 if (activity != caller) {
3565 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3566 + " is not current top " + activity);
3567 return null;
3568 }
3569 }
3570 } else {
3571 activity = ActivityRecord.forTokenLocked(activityToken);
3572 if (activity == null) {
3573 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3574 + " couldn't be found");
3575 return null;
3576 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003577 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3579 return null;
3580 }
3581 }
3582
3583 PendingAssistExtras pae;
3584 Bundle extras = new Bundle();
3585 if (args != null) {
3586 extras.putAll(args);
3587 }
3588 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003589 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590
3591 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3592 userHandle);
3593 pae.isHome = activity.isActivityTypeHome();
3594
3595 // Increment the sessionId if necessary
3596 if (newSessionId) {
3597 mViSessionId++;
3598 }
3599 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003600 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3601 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003602 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003603 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003604 } catch (RemoteException e) {
3605 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3606 return null;
3607 }
3608 return pae;
3609 }
3610 }
3611
3612 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3613 if (result != null) {
3614 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3615 }
3616 if (pae.hint != null) {
3617 pae.extras.putBoolean(pae.hint, true);
3618 }
3619 }
3620
3621 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3622 IAssistDataReceiver receiver;
3623 synchronized (mGlobalLock) {
3624 mPendingAssistExtras.remove(pae);
3625 receiver = pae.receiver;
3626 }
3627 if (receiver != null) {
3628 // Caller wants result sent back to them.
3629 Bundle sendBundle = new Bundle();
3630 // At least return the receiver extras
3631 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3632 try {
3633 pae.receiver.onHandleAssistData(sendBundle);
3634 } catch (RemoteException e) {
3635 }
3636 }
3637 }
3638
3639 public class PendingAssistExtras extends Binder implements Runnable {
3640 public final ActivityRecord activity;
3641 public boolean isHome;
3642 public final Bundle extras;
3643 public final Intent intent;
3644 public final String hint;
3645 public final IAssistDataReceiver receiver;
3646 public final int userHandle;
3647 public boolean haveResult = false;
3648 public Bundle result = null;
3649 public AssistStructure structure = null;
3650 public AssistContent content = null;
3651 public Bundle receiverExtras;
3652
3653 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3654 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3655 int _userHandle) {
3656 activity = _activity;
3657 extras = _extras;
3658 intent = _intent;
3659 hint = _hint;
3660 receiver = _receiver;
3661 receiverExtras = _receiverExtras;
3662 userHandle = _userHandle;
3663 }
3664
3665 @Override
3666 public void run() {
3667 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3668 synchronized (this) {
3669 haveResult = true;
3670 notifyAll();
3671 }
3672 pendingAssistExtrasTimedOut(this);
3673 }
3674 }
3675
3676 @Override
3677 public boolean isAssistDataAllowedOnCurrentActivity() {
3678 int userId;
3679 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003680 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3682 return false;
3683 }
3684
3685 final ActivityRecord activity = focusedStack.getTopActivity();
3686 if (activity == null) {
3687 return false;
3688 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003689 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003690 }
3691 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3692 }
3693
3694 @Override
3695 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3696 long ident = Binder.clearCallingIdentity();
3697 try {
3698 synchronized (mGlobalLock) {
3699 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003700 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003701 if (top != caller) {
3702 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3703 + " is not current top " + top);
3704 return false;
3705 }
3706 if (!top.nowVisible) {
3707 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3708 + " is not visible");
3709 return false;
3710 }
3711 }
3712 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3713 token);
3714 } finally {
3715 Binder.restoreCallingIdentity(ident);
3716 }
3717 }
3718
3719 @Override
3720 public boolean isRootVoiceInteraction(IBinder token) {
3721 synchronized (mGlobalLock) {
3722 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3723 if (r == null) {
3724 return false;
3725 }
3726 return r.rootVoiceInteraction;
3727 }
3728 }
3729
Wale Ogunwalef6733932018-06-27 05:14:34 -07003730 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3731 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3732 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3733 if (activityToCallback == null) return;
3734 activityToCallback.setVoiceSessionLocked(voiceSession);
3735
3736 // Inform the activity
3737 try {
3738 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3739 voiceInteractor);
3740 long token = Binder.clearCallingIdentity();
3741 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003742 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003743 } finally {
3744 Binder.restoreCallingIdentity(token);
3745 }
3746 // TODO: VI Should we cache the activity so that it's easier to find later
3747 // rather than scan through all the stacks and activities?
3748 } catch (RemoteException re) {
3749 activityToCallback.clearVoiceSessionLocked();
3750 // TODO: VI Should this terminate the voice session?
3751 }
3752 }
3753
3754 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3755 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3756 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3757 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3758 boolean wasRunningVoice = mRunningVoice != null;
3759 mRunningVoice = session;
3760 if (!wasRunningVoice) {
3761 mVoiceWakeLock.acquire();
3762 updateSleepIfNeededLocked();
3763 }
3764 }
3765 }
3766
3767 void finishRunningVoiceLocked() {
3768 if (mRunningVoice != null) {
3769 mRunningVoice = null;
3770 mVoiceWakeLock.release();
3771 updateSleepIfNeededLocked();
3772 }
3773 }
3774
3775 @Override
3776 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3777 synchronized (mGlobalLock) {
3778 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3779 if (keepAwake) {
3780 mVoiceWakeLock.acquire();
3781 } else {
3782 mVoiceWakeLock.release();
3783 }
3784 }
3785 }
3786 }
3787
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003788 @Override
3789 public ComponentName getActivityClassForToken(IBinder token) {
3790 synchronized (mGlobalLock) {
3791 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3792 if (r == null) {
3793 return null;
3794 }
3795 return r.intent.getComponent();
3796 }
3797 }
3798
3799 @Override
3800 public String getPackageForToken(IBinder token) {
3801 synchronized (mGlobalLock) {
3802 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3803 if (r == null) {
3804 return null;
3805 }
3806 return r.packageName;
3807 }
3808 }
3809
3810 @Override
3811 public void showLockTaskEscapeMessage(IBinder token) {
3812 synchronized (mGlobalLock) {
3813 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3814 if (r == null) {
3815 return;
3816 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003817 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 }
3819 }
3820
3821 @Override
3822 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003823 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003824 final long token = Binder.clearCallingIdentity();
3825 try {
3826 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003827 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 }
3829 } finally {
3830 Binder.restoreCallingIdentity(token);
3831 }
3832 }
3833
3834 /**
3835 * Try to place task to provided position. The final position might be different depending on
3836 * current user and stacks state. The task will be moved to target stack if it's currently in
3837 * different stack.
3838 */
3839 @Override
3840 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003841 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 synchronized (mGlobalLock) {
3843 long ident = Binder.clearCallingIdentity();
3844 try {
3845 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3846 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003847 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 if (task == null) {
3849 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3850 + taskId);
3851 }
3852
Wale Ogunwaled32da472018-11-16 07:19:28 -08003853 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854
3855 if (stack == null) {
3856 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3857 + stackId);
3858 }
3859 if (!stack.isActivityTypeStandardOrUndefined()) {
3860 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3861 + " the position of task " + taskId + " in/to non-standard stack");
3862 }
3863
3864 // TODO: Have the callers of this API call a separate reparent method if that is
3865 // what they intended to do vs. having this method also do reparenting.
3866 if (task.getStack() == stack) {
3867 // Change position in current stack.
3868 stack.positionChildAt(task, position);
3869 } else {
3870 // Reparent to new stack.
3871 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3872 !DEFER_RESUME, "positionTaskInStack");
3873 }
3874 } finally {
3875 Binder.restoreCallingIdentity(ident);
3876 }
3877 }
3878 }
3879
3880 @Override
3881 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3882 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3883 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003884 + Arrays.toString(horizontalSizeConfiguration) + " "
3885 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886 synchronized (mGlobalLock) {
3887 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3888 if (record == null) {
3889 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3890 + "found for: " + token);
3891 }
3892 record.setSizeConfigurations(horizontalSizeConfiguration,
3893 verticalSizeConfigurations, smallestSizeConfigurations);
3894 }
3895 }
3896
3897 /**
3898 * Dismisses split-screen multi-window mode.
3899 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3900 */
3901 @Override
3902 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003903 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003904 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3905 final long ident = Binder.clearCallingIdentity();
3906 try {
3907 synchronized (mGlobalLock) {
3908 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003909 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 if (stack == null) {
3911 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3912 return;
3913 }
3914
3915 if (toTop) {
3916 // Caller wants the current split-screen primary stack to be the top stack after
3917 // it goes fullscreen, so move it to the front.
3918 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003919 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003921 // stack after it goes fullscreen, so we move the focus to the top-most
3922 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3924 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3925 if (otherStack != null) {
3926 otherStack.moveToFront("dismissSplitScreenMode_other");
3927 }
3928 }
3929
Evan Rosky10475742018-09-05 19:02:48 -07003930 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 }
3932 } finally {
3933 Binder.restoreCallingIdentity(ident);
3934 }
3935 }
3936
3937 /**
3938 * Dismisses Pip
3939 * @param animate True if the dismissal should be animated.
3940 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3941 * default animation duration should be used.
3942 */
3943 @Override
3944 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003945 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 final long ident = Binder.clearCallingIdentity();
3947 try {
3948 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003949 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003950 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 if (stack == null) {
3952 Slog.w(TAG, "dismissPip: pinned stack not found.");
3953 return;
3954 }
3955 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3956 throw new IllegalArgumentException("Stack: " + stack
3957 + " doesn't support animated resize.");
3958 }
3959 if (animate) {
3960 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3961 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3962 } else {
3963 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3964 }
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(ident);
3968 }
3969 }
3970
3971 @Override
3972 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 synchronized (mGlobalLock) {
3975 mSuppressResizeConfigChanges = suppress;
3976 }
3977 }
3978
3979 /**
3980 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3981 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3982 * activity and clearing the task at the same time.
3983 */
3984 @Override
3985 // TODO: API should just be about changing windowing modes...
3986 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 "moveTasksToFullscreenStack()");
3989 synchronized (mGlobalLock) {
3990 final long origId = Binder.clearCallingIdentity();
3991 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003992 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 if (stack != null){
3994 if (!stack.isActivityTypeStandardOrUndefined()) {
3995 throw new IllegalArgumentException(
3996 "You can't move tasks from non-standard stacks.");
3997 }
3998 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3999 }
4000 } finally {
4001 Binder.restoreCallingIdentity(origId);
4002 }
4003 }
4004 }
4005
4006 /**
4007 * Moves the top activity in the input stackId to the pinned stack.
4008 *
4009 * @param stackId Id of stack to move the top activity to pinned stack.
4010 * @param bounds Bounds to use for pinned stack.
4011 *
4012 * @return True if the top activity of the input stack was successfully moved to the pinned
4013 * stack.
4014 */
4015 @Override
4016 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004017 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 "moveTopActivityToPinnedStack()");
4019 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004020 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4022 + "Device doesn't support picture-in-picture mode");
4023 }
4024
4025 long ident = Binder.clearCallingIdentity();
4026 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004027 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 } finally {
4029 Binder.restoreCallingIdentity(ident);
4030 }
4031 }
4032 }
4033
4034 @Override
4035 public boolean isInMultiWindowMode(IBinder token) {
4036 final long origId = Binder.clearCallingIdentity();
4037 try {
4038 synchronized (mGlobalLock) {
4039 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4040 if (r == null) {
4041 return false;
4042 }
4043 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4044 return r.inMultiWindowMode();
4045 }
4046 } finally {
4047 Binder.restoreCallingIdentity(origId);
4048 }
4049 }
4050
4051 @Override
4052 public boolean isInPictureInPictureMode(IBinder token) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
4055 synchronized (mGlobalLock) {
4056 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4057 }
4058 } finally {
4059 Binder.restoreCallingIdentity(origId);
4060 }
4061 }
4062
4063 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004064 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4065 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066 return false;
4067 }
4068
4069 // If we are animating to fullscreen then we have already dispatched the PIP mode
4070 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004071 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4072 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 }
4074
4075 @Override
4076 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4077 final long origId = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4081 "enterPictureInPictureMode", token, params);
4082
4083 // If the activity is already in picture in picture mode, then just return early
4084 if (isInPictureInPictureMode(r)) {
4085 return true;
4086 }
4087
4088 // Activity supports picture-in-picture, now check that we can enter PiP at this
4089 // point, if it is
4090 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4091 false /* beforeStopping */)) {
4092 return false;
4093 }
4094
4095 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004096 synchronized (mGlobalLock) {
4097 // Only update the saved args from the args that are set
4098 r.pictureInPictureArgs.copyOnlySet(params);
4099 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4100 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4101 // Adjust the source bounds by the insets for the transition down
4102 final Rect sourceBounds = new Rect(
4103 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004104 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004105 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004106 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004107 stack.setPictureInPictureAspectRatio(aspectRatio);
4108 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004109 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4110 r.info.applicationInfo.uid, r.shortComponentName,
4111 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004112 logPictureInPictureArgs(params);
4113 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 };
4115
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004116 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 // If the keyguard is showing or occluded, then try and dismiss it before
4118 // entering picture-in-picture (this will prompt the user to authenticate if the
4119 // device is currently locked).
4120 dismissKeyguard(token, new KeyguardDismissCallback() {
4121 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004122 public void onDismissSucceeded() {
4123 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 }
4125 }, null /* message */);
4126 } else {
4127 // Enter picture in picture immediately otherwise
4128 enterPipRunnable.run();
4129 }
4130 return true;
4131 }
4132 } finally {
4133 Binder.restoreCallingIdentity(origId);
4134 }
4135 }
4136
4137 @Override
4138 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4139 final long origId = Binder.clearCallingIdentity();
4140 try {
4141 synchronized (mGlobalLock) {
4142 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4143 "setPictureInPictureParams", token, params);
4144
4145 // Only update the saved args from the args that are set
4146 r.pictureInPictureArgs.copyOnlySet(params);
4147 if (r.inPinnedWindowingMode()) {
4148 // If the activity is already in picture-in-picture, update the pinned stack now
4149 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4150 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004151 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 if (!stack.isAnimatingBoundsToFullscreen()) {
4153 stack.setPictureInPictureAspectRatio(
4154 r.pictureInPictureArgs.getAspectRatio());
4155 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4156 }
4157 }
4158 logPictureInPictureArgs(params);
4159 }
4160 } finally {
4161 Binder.restoreCallingIdentity(origId);
4162 }
4163 }
4164
4165 @Override
4166 public int getMaxNumPictureInPictureActions(IBinder token) {
4167 // Currently, this is a static constant, but later, we may change this to be dependent on
4168 // the context of the activity
4169 return 3;
4170 }
4171
4172 private void logPictureInPictureArgs(PictureInPictureParams params) {
4173 if (params.hasSetActions()) {
4174 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4175 params.getActions().size());
4176 }
4177 if (params.hasSetAspectRatio()) {
4178 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4179 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4180 MetricsLogger.action(lm);
4181 }
4182 }
4183
4184 /**
4185 * Checks the state of the system and the activity associated with the given {@param token} to
4186 * verify that picture-in-picture is supported for that activity.
4187 *
4188 * @return the activity record for the given {@param token} if all the checks pass.
4189 */
4190 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4191 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 throw new IllegalStateException(caller
4194 + ": Device doesn't support picture-in-picture mode.");
4195 }
4196
4197 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4198 if (r == null) {
4199 throw new IllegalStateException(caller
4200 + ": Can't find activity for token=" + token);
4201 }
4202
4203 if (!r.supportsPictureInPicture()) {
4204 throw new IllegalStateException(caller
4205 + ": Current activity does not support picture-in-picture.");
4206 }
4207
4208 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004209 && !mWindowManager.isValidPictureInPictureAspectRatio(
4210 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 final float minAspectRatio = mContext.getResources().getFloat(
4212 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4213 final float maxAspectRatio = mContext.getResources().getFloat(
4214 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4215 throw new IllegalArgumentException(String.format(caller
4216 + ": Aspect ratio is too extreme (must be between %f and %f).",
4217 minAspectRatio, maxAspectRatio));
4218 }
4219
4220 // Truncate the number of actions if necessary
4221 params.truncateActions(getMaxNumPictureInPictureActions(token));
4222
4223 return r;
4224 }
4225
4226 @Override
4227 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 synchronized (mGlobalLock) {
4230 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4231 if (r == null) {
4232 throw new IllegalArgumentException("Activity does not exist; token="
4233 + activityToken);
4234 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004235 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 }
4237 }
4238
4239 @Override
4240 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4241 Rect tempDockedTaskInsetBounds,
4242 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004243 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 long ident = Binder.clearCallingIdentity();
4245 try {
4246 synchronized (mGlobalLock) {
4247 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4248 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4249 PRESERVE_WINDOWS);
4250 }
4251 } finally {
4252 Binder.restoreCallingIdentity(ident);
4253 }
4254 }
4255
4256 @Override
4257 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 final long ident = Binder.clearCallingIdentity();
4260 try {
4261 synchronized (mGlobalLock) {
4262 mStackSupervisor.setSplitScreenResizing(resizing);
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(ident);
4266 }
4267 }
4268
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004269 /**
4270 * Check that we have the features required for VR-related API calls, and throw an exception if
4271 * not.
4272 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004273 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 if (!mContext.getPackageManager().hasSystemFeature(
4275 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4276 throw new UnsupportedOperationException("VR mode not supported on this device!");
4277 }
4278 }
4279
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 @Override
4281 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283
4284 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4285
4286 ActivityRecord r;
4287 synchronized (mGlobalLock) {
4288 r = ActivityRecord.isInStackLocked(token);
4289 }
4290
4291 if (r == null) {
4292 throw new IllegalArgumentException();
4293 }
4294
4295 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004296 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297 VrManagerInternal.NO_ERROR) {
4298 return err;
4299 }
4300
4301 // Clear the binder calling uid since this path may call moveToTask().
4302 final long callingId = Binder.clearCallingIdentity();
4303 try {
4304 synchronized (mGlobalLock) {
4305 r.requestedVrComponent = (enabled) ? packageName : null;
4306
4307 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004308 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004309 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 }
4311 return 0;
4312 }
4313 } finally {
4314 Binder.restoreCallingIdentity(callingId);
4315 }
4316 }
4317
4318 @Override
4319 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4320 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4321 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004322 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4324 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4325 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004326 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 || activity.voiceSession != null) {
4328 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4329 return;
4330 }
4331 if (activity.pendingVoiceInteractionStart) {
4332 Slog.w(TAG, "Pending start of voice interaction already.");
4333 return;
4334 }
4335 activity.pendingVoiceInteractionStart = true;
4336 }
4337 LocalServices.getService(VoiceInteractionManagerInternal.class)
4338 .startLocalVoiceInteraction(callingActivity, options);
4339 }
4340
4341 @Override
4342 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4343 LocalServices.getService(VoiceInteractionManagerInternal.class)
4344 .stopLocalVoiceInteraction(callingActivity);
4345 }
4346
4347 @Override
4348 public boolean supportsLocalVoiceInteraction() {
4349 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4350 .supportsLocalVoiceInteraction();
4351 }
4352
4353 /** Notifies all listeners when the pinned stack animation starts. */
4354 @Override
4355 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004356 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004357 }
4358
4359 /** Notifies all listeners when the pinned stack animation ends. */
4360 @Override
4361 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004362 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 }
4364
4365 @Override
4366 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 final long ident = Binder.clearCallingIdentity();
4369 try {
4370 synchronized (mGlobalLock) {
4371 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4372 }
4373 } finally {
4374 Binder.restoreCallingIdentity(ident);
4375 }
4376 }
4377
4378 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381
4382 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004383 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 }
4387
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004389 final Message msg = PooledLambda.obtainMessage(
4390 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4391 DEFAULT_DISPLAY);
4392 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394
4395 final long origId = Binder.clearCallingIdentity();
4396 try {
4397 if (values != null) {
4398 Settings.System.clearConfiguration(values);
4399 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 UserHandle.USER_NULL, false /* deferResume */,
4402 mTmpUpdateConfigurationResult);
4403 return mTmpUpdateConfigurationResult.changes != 0;
4404 } finally {
4405 Binder.restoreCallingIdentity(origId);
4406 }
4407 }
4408 }
4409
4410 @Override
4411 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4412 CharSequence message) {
4413 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4416 }
4417 final long callingId = Binder.clearCallingIdentity();
4418 try {
4419 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004420 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 }
4422 } finally {
4423 Binder.restoreCallingIdentity(callingId);
4424 }
4425 }
4426
4427 @Override
4428 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 "cancelTaskWindowTransition()");
4431 final long ident = Binder.clearCallingIdentity();
4432 try {
4433 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004434 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 MATCH_TASK_IN_STACKS_ONLY);
4436 if (task == null) {
4437 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4438 return;
4439 }
4440 task.cancelWindowTransition();
4441 }
4442 } finally {
4443 Binder.restoreCallingIdentity(ident);
4444 }
4445 }
4446
4447 @Override
4448 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004449 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 final long ident = Binder.clearCallingIdentity();
4451 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004452 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 } finally {
4454 Binder.restoreCallingIdentity(ident);
4455 }
4456 }
4457
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004458 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4459 boolean restoreFromDisk) {
4460 final TaskRecord task;
4461 synchronized (mGlobalLock) {
4462 task = mRootActivityContainer.anyTaskForId(taskId,
4463 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4464 if (task == null) {
4465 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4466 return null;
4467 }
4468 }
4469 // Don't call this while holding the lock as this operation might hit the disk.
4470 return task.getSnapshot(reducedResolution, restoreFromDisk);
4471 }
4472
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 @Override
4474 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4475 synchronized (mGlobalLock) {
4476 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4477 if (r == null) {
4478 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4479 + token);
4480 return;
4481 }
4482 final long origId = Binder.clearCallingIdentity();
4483 try {
4484 r.setDisablePreviewScreenshots(disable);
4485 } finally {
4486 Binder.restoreCallingIdentity(origId);
4487 }
4488 }
4489 }
4490
4491 /** Return the user id of the last resumed activity. */
4492 @Override
4493 public @UserIdInt
4494 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4497 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004498 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004501 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 }
4503 }
4504
4505 @Override
4506 public void updateLockTaskFeatures(int userId, int flags) {
4507 final int callingUid = Binder.getCallingUid();
4508 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004509 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 "updateLockTaskFeatures()");
4511 }
4512 synchronized (mGlobalLock) {
4513 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4514 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004515 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 }
4517 }
4518
4519 @Override
4520 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4521 synchronized (mGlobalLock) {
4522 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4523 if (r == null) {
4524 return;
4525 }
4526 final long origId = Binder.clearCallingIdentity();
4527 try {
4528 r.setShowWhenLocked(showWhenLocked);
4529 } finally {
4530 Binder.restoreCallingIdentity(origId);
4531 }
4532 }
4533 }
4534
4535 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004536 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4537 synchronized (mGlobalLock) {
4538 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4539 if (r == null) {
4540 return;
4541 }
4542 final long origId = Binder.clearCallingIdentity();
4543 try {
4544 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4545 } finally {
4546 Binder.restoreCallingIdentity(origId);
4547 }
4548 }
4549 }
4550
4551 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4553 synchronized (mGlobalLock) {
4554 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4555 if (r == null) {
4556 return;
4557 }
4558 final long origId = Binder.clearCallingIdentity();
4559 try {
4560 r.setTurnScreenOn(turnScreenOn);
4561 } finally {
4562 Binder.restoreCallingIdentity(origId);
4563 }
4564 }
4565 }
4566
4567 @Override
4568 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004569 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004570 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004571 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 synchronized (mGlobalLock) {
4573 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4574 if (r == null) {
4575 return;
4576 }
4577 final long origId = Binder.clearCallingIdentity();
4578 try {
4579 r.registerRemoteAnimations(definition);
4580 } finally {
4581 Binder.restoreCallingIdentity(origId);
4582 }
4583 }
4584 }
4585
4586 @Override
4587 public void registerRemoteAnimationForNextActivityStart(String packageName,
4588 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004589 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004591 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 synchronized (mGlobalLock) {
4593 final long origId = Binder.clearCallingIdentity();
4594 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004595 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 packageName, adapter);
4597 } finally {
4598 Binder.restoreCallingIdentity(origId);
4599 }
4600 }
4601 }
4602
Evan Rosky966759f2019-01-15 10:33:58 -08004603 @Override
4604 public void registerRemoteAnimationsForDisplay(int displayId,
4605 RemoteAnimationDefinition definition) {
4606 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4607 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004608 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004609 synchronized (mGlobalLock) {
4610 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4611 if (display == null) {
4612 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 display.mDisplayContent.registerRemoteAnimations(definition);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4625 @Override
4626 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4627 synchronized (mGlobalLock) {
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004630 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004636
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004637 @Override
4638 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004639 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004640 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004641 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004642 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004643 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 }
4645 }
4646
4647 @Override
4648 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 != PERMISSION_GRANTED) {
4651 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4652 + Binder.getCallingPid()
4653 + ", uid=" + Binder.getCallingUid()
4654 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4655 Slog.w(TAG, msg);
4656 throw new SecurityException(msg);
4657 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004660 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004661 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004662 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 }
4664 }
4665
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004666 @Override
4667 public void stopAppSwitches() {
4668 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4669 synchronized (mGlobalLock) {
4670 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004671 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004672 mDidAppSwitch = false;
4673 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4674 }
4675 }
4676
4677 @Override
4678 public void resumeAppSwitches() {
4679 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4680 synchronized (mGlobalLock) {
4681 // Note that we don't execute any pending app switches... we will
4682 // let those wait until either the timeout, or the next start
4683 // activity request.
4684 mAppSwitchesAllowedTime = 0;
4685 }
4686 }
4687
Ricky Wai906af482019-06-03 17:25:28 +01004688 long getLastStopAppSwitchesTime() {
4689 return mLastStopAppSwitchesTime;
4690 }
4691
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004692 void onStartActivitySetDidAppSwitch() {
4693 if (mDidAppSwitch) {
4694 // This is the second allowed switch since we stopped switches, so now just generally
4695 // allow switches. Use case:
4696 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4697 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4698 // anyone to switch again).
4699 mAppSwitchesAllowedTime = 0;
4700 } else {
4701 mDidAppSwitch = true;
4702 }
4703 }
4704
4705 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 boolean shouldDisableNonVrUiLocked() {
4707 return mVrController.shouldDisableNonVrUiLocked();
4708 }
4709
Wale Ogunwale53783742018-09-16 10:21:51 -07004710 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 // 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 +00004712 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004714 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4715 + " to main display for VR");
4716 mRootActivityContainer.moveStackToDisplay(
4717 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 }
4719 mH.post(() -> {
4720 if (!mVrController.onVrModeChanged(r)) {
4721 return;
4722 }
4723 synchronized (mGlobalLock) {
4724 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4725 mWindowManager.disableNonVrUi(disableNonVrUi);
4726 if (disableNonVrUi) {
4727 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4728 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004729 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 }
4731 }
4732 });
4733 }
4734
Wale Ogunwale53783742018-09-16 10:21:51 -07004735 @Override
4736 public int getPackageScreenCompatMode(String packageName) {
4737 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4738 synchronized (mGlobalLock) {
4739 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4740 }
4741 }
4742
4743 @Override
4744 public void setPackageScreenCompatMode(String packageName, int mode) {
4745 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4746 "setPackageScreenCompatMode");
4747 synchronized (mGlobalLock) {
4748 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4749 }
4750 }
4751
4752 @Override
4753 public boolean getPackageAskScreenCompat(String packageName) {
4754 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4755 synchronized (mGlobalLock) {
4756 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4757 }
4758 }
4759
4760 @Override
4761 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4762 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4763 "setPackageAskScreenCompat");
4764 synchronized (mGlobalLock) {
4765 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4766 }
4767 }
4768
Wale Ogunwale64258362018-10-16 15:13:37 -07004769 public static String relaunchReasonToString(int relaunchReason) {
4770 switch (relaunchReason) {
4771 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4772 return "window_resize";
4773 case RELAUNCH_REASON_FREE_RESIZE:
4774 return "free_resize";
4775 default:
4776 return null;
4777 }
4778 }
4779
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004780 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004781 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004782 }
4783
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004784 /** Pokes the task persister. */
4785 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4786 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4787 }
4788
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004789 boolean isKeyguardLocked() {
4790 return mKeyguardController.isKeyguardLocked();
4791 }
4792
Garfield Tan01548632018-11-27 10:15:48 -08004793 /**
4794 * Clears launch params for the given package.
4795 * @param packageNames the names of the packages of which the launch params are to be cleared
4796 */
4797 @Override
4798 public void clearLaunchParamsForPackages(List<String> packageNames) {
4799 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4800 "clearLaunchParamsForPackages");
4801 synchronized (mGlobalLock) {
4802 for (int i = 0; i < packageNames.size(); ++i) {
4803 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4804 }
4805 }
4806 }
4807
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004808 /**
4809 * Makes the display with the given id a single task instance display. I.e the display can only
4810 * contain one task.
4811 */
4812 @Override
4813 public void setDisplayToSingleTaskInstance(int displayId) {
4814 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4815 "setDisplayToSingleTaskInstance");
4816 final long origId = Binder.clearCallingIdentity();
4817 try {
4818 final ActivityDisplay display =
4819 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4820 if (display != null) {
4821 display.setDisplayToSingleTaskInstance();
4822 }
4823 } finally {
4824 Binder.restoreCallingIdentity(origId);
4825 }
4826 }
4827
Wale Ogunwale31913b52018-10-13 08:29:31 -07004828 void dumpLastANRLocked(PrintWriter pw) {
4829 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4830 if (mLastANRState == null) {
4831 pw.println(" <no ANR has occurred since boot>");
4832 } else {
4833 pw.println(mLastANRState);
4834 }
4835 }
4836
4837 void dumpLastANRTracesLocked(PrintWriter pw) {
4838 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4839
4840 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4841 if (ArrayUtils.isEmpty(files)) {
4842 pw.println(" <no ANR has occurred since boot>");
4843 return;
4844 }
4845 // Find the latest file.
4846 File latest = null;
4847 for (File f : files) {
4848 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4849 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004850 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004851 }
4852 pw.print("File: ");
4853 pw.print(latest.getName());
4854 pw.println();
4855 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4856 String line;
4857 while ((line = in.readLine()) != null) {
4858 pw.println(line);
4859 }
4860 } catch (IOException e) {
4861 pw.print("Unable to read: ");
4862 pw.print(e);
4863 pw.println();
4864 }
4865 }
4866
4867 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4868 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4869 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4870 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4871 }
4872
4873 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4874 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4875 pw.println(header);
4876
Wale Ogunwaled32da472018-11-16 07:19:28 -08004877 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004878 dumpPackage);
4879 boolean needSep = printedAnything;
4880
4881 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004882 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004883 " ResumedActivity: ");
4884 if (printed) {
4885 printedAnything = true;
4886 needSep = false;
4887 }
4888
4889 if (dumpPackage == null) {
4890 if (needSep) {
4891 pw.println();
4892 }
4893 printedAnything = true;
4894 mStackSupervisor.dump(pw, " ");
4895 }
4896
4897 if (!printedAnything) {
4898 pw.println(" (nothing)");
4899 }
4900 }
4901
4902 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004903 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004904 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004905 pw.println(" ");
4906 }
4907
4908 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4909 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4910 getActivityStartController().dump(pw, "", dumpPackage);
4911 }
4912
4913 /**
4914 * There are three things that cmd can be:
4915 * - a flattened component name that matches an existing activity
4916 * - the cmd arg isn't the flattened component name of an existing activity:
4917 * dump all activity whose component contains the cmd as a substring
4918 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004919 * <p>
4920 * The caller should not hold lock when calling this method because it will wait for the
4921 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004922 *
4923 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4924 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4925 */
4926 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4927 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4928 ArrayList<ActivityRecord> activities;
4929
4930 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004931 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004932 dumpFocusedStackOnly);
4933 }
4934
4935 if (activities.size() <= 0) {
4936 return false;
4937 }
4938
4939 String[] newArgs = new String[args.length - opti];
4940 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4941
4942 TaskRecord lastTask = null;
4943 boolean needSep = false;
4944 for (int i = activities.size() - 1; i >= 0; i--) {
4945 ActivityRecord r = activities.get(i);
4946 if (needSep) {
4947 pw.println();
4948 }
4949 needSep = true;
4950 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004951 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004952 if (lastTask != task) {
4953 lastTask = task;
4954 pw.print("TASK "); pw.print(lastTask.affinity);
4955 pw.print(" id="); pw.print(lastTask.taskId);
4956 pw.print(" userId="); pw.println(lastTask.userId);
4957 if (dumpAll) {
4958 lastTask.dump(pw, " ");
4959 }
4960 }
4961 }
4962 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4963 }
4964 return true;
4965 }
4966
4967 /**
4968 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4969 * there is a thread associated with the activity.
4970 */
4971 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4972 final ActivityRecord r, String[] args, boolean dumpAll) {
4973 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004974 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004975 synchronized (mGlobalLock) {
4976 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4977 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4978 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004979 if (r.hasProcess()) {
4980 pw.println(r.app.getPid());
4981 appThread = r.app.getThread();
4982 } else {
4983 pw.println("(not running)");
4984 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004985 if (dumpAll) {
4986 r.dump(pw, innerPrefix);
4987 }
4988 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004989 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 // flush anything that is already in the PrintWriter since the thread is going
4991 // to write to the file descriptor directly
4992 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004993 try (TransferPipe tp = new TransferPipe()) {
4994 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4995 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004996 } catch (IOException e) {
4997 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4998 } catch (RemoteException e) {
4999 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5000 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005002 }
5003
sanryhuang498e77e2018-12-06 14:57:01 +08005004 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5005 boolean testPssMode) {
5006 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5007 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5008 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005009 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005010 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5011 st.toString());
5012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005013 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5015 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005016 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5017 testPssMode);
5018 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005019 }
5020
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005021 int getCurrentUserId() {
5022 return mAmInternal.getCurrentUserId();
5023 }
5024
5025 private void enforceNotIsolatedCaller(String caller) {
5026 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5027 throw new SecurityException("Isolated process not allowed to call " + caller);
5028 }
5029 }
5030
Wale Ogunwalef6733932018-06-27 05:14:34 -07005031 public Configuration getConfiguration() {
5032 Configuration ci;
5033 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005034 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005035 ci.userSetLocale = false;
5036 }
5037 return ci;
5038 }
5039
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040 /**
5041 * Current global configuration information. Contains general settings for the entire system,
5042 * also corresponds to the merged configuration of the default display.
5043 */
5044 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005045 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046 }
5047
5048 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5049 boolean initLocale) {
5050 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5051 }
5052
5053 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5054 boolean initLocale, boolean deferResume) {
5055 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5056 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5057 UserHandle.USER_NULL, deferResume);
5058 }
5059
Wale Ogunwale59507092018-10-29 09:00:30 -07005060 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 final long origId = Binder.clearCallingIdentity();
5062 try {
5063 synchronized (mGlobalLock) {
5064 updateConfigurationLocked(values, null, false, true, userId,
5065 false /* deferResume */);
5066 }
5067 } finally {
5068 Binder.restoreCallingIdentity(origId);
5069 }
5070 }
5071
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5073 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5074 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5075 deferResume, null /* result */);
5076 }
5077
5078 /**
5079 * Do either or both things: (1) change the current configuration, and (2)
5080 * make sure the given activity is running with the (now) current
5081 * configuration. Returns true if the activity has been left running, or
5082 * false if <var>starting</var> is being destroyed to match the new
5083 * configuration.
5084 *
5085 * @param userId is only used when persistent parameter is set to true to persist configuration
5086 * for that particular user
5087 */
5088 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5089 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5090 ActivityTaskManagerService.UpdateConfigurationResult result) {
5091 int changes = 0;
5092 boolean kept = true;
5093
5094 if (mWindowManager != null) {
5095 mWindowManager.deferSurfaceLayout();
5096 }
5097 try {
5098 if (values != null) {
5099 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5100 deferResume);
5101 }
5102
5103 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5104 } finally {
5105 if (mWindowManager != null) {
5106 mWindowManager.continueSurfaceLayout();
5107 }
5108 }
5109
5110 if (result != null) {
5111 result.changes = changes;
5112 result.activityRelaunched = !kept;
5113 }
5114 return kept;
5115 }
5116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005117 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005118 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005120
5121 final ActivityDisplay defaultDisplay =
5122 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 mTempConfig.setTo(getGlobalConfiguration());
5125 final int changes = mTempConfig.updateFrom(values);
5126 if (changes == 0) {
5127 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5128 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5129 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5130 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005131 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132 return 0;
5133 }
5134
5135 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5136 "Updating global configuration to: " + values);
5137
5138 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5139 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5140 values.colorMode,
5141 values.densityDpi,
5142 values.fontScale,
5143 values.hardKeyboardHidden,
5144 values.keyboard,
5145 values.keyboardHidden,
5146 values.mcc,
5147 values.mnc,
5148 values.navigation,
5149 values.navigationHidden,
5150 values.orientation,
5151 values.screenHeightDp,
5152 values.screenLayout,
5153 values.screenWidthDp,
5154 values.smallestScreenWidthDp,
5155 values.touchscreen,
5156 values.uiMode);
5157
5158
5159 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5160 final LocaleList locales = values.getLocales();
5161 int bestLocaleIndex = 0;
5162 if (locales.size() > 1) {
5163 if (mSupportedSystemLocales == null) {
5164 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5165 }
5166 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5167 }
5168 SystemProperties.set("persist.sys.locale",
5169 locales.get(bestLocaleIndex).toLanguageTag());
5170 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005171
5172 final Message m = PooledLambda.obtainMessage(
5173 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5174 locales.get(bestLocaleIndex));
5175 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005176 }
5177
Yunfan Chen75157d72018-07-27 14:47:21 +09005178 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179
5180 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005181 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182
5183 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5184 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005185 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186
5187 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005188 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189
5190 AttributeCache ac = AttributeCache.instance();
5191 if (ac != null) {
5192 ac.updateConfiguration(mTempConfig);
5193 }
5194
5195 // Make sure all resources in our process are updated right now, so that anyone who is going
5196 // to retrieve resource values after we return will be sure to get the new ones. This is
5197 // especially important during boot, where the first config change needs to guarantee all
5198 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005199 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005200
5201 // We need another copy of global config because we're scheduling some calls instead of
5202 // running them in place. We need to be sure that object we send will be handled unchanged.
5203 final Configuration configCopy = new Configuration(mTempConfig);
5204 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005205 final Message msg = PooledLambda.obtainMessage(
5206 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5207 this, userId, configCopy);
5208 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209 }
5210
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005211 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5212 for (int i = pidMap.size() - 1; i >= 0; i--) {
5213 final int pid = pidMap.keyAt(i);
5214 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005215 if (DEBUG_CONFIGURATION) {
5216 Slog.v(TAG_CONFIGURATION, "Update process config of "
5217 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005219 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005222 final Message msg = PooledLambda.obtainMessage(
5223 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5224 mAmInternal, changes, initLocale);
5225 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226
5227 // Override configuration of the default display duplicates global config, so we need to
5228 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005229 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5230 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231
5232 return changes;
5233 }
5234
Wale Ogunwalef6733932018-06-27 05:14:34 -07005235 private void updateEventDispatchingLocked(boolean booted) {
5236 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5237 }
5238
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005239 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5240 final ContentResolver resolver = mContext.getContentResolver();
5241 Settings.System.putConfigurationForUser(resolver, config, userId);
5242 }
5243
5244 private void sendLocaleToMountDaemonMsg(Locale l) {
5245 try {
5246 IBinder service = ServiceManager.getService("mount");
5247 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5248 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5249 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5250 } catch (RemoteException e) {
5251 Log.e(TAG, "Error storing locale for decryption UI", e);
5252 }
5253 }
5254
Alison Cichowlas3e340502018-08-07 17:15:01 -04005255 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5256 mStartActivitySources.remove(permissionToken);
5257 mExpiredStartAsCallerTokens.add(permissionToken);
5258 }
5259
5260 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5261 mExpiredStartAsCallerTokens.remove(permissionToken);
5262 }
5263
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005264 boolean isActivityStartsLoggingEnabled() {
5265 return mAmInternal.isActivityStartsLoggingEnabled();
5266 }
5267
Michal Karpinski8596ded2018-11-14 14:43:48 +00005268 boolean isBackgroundActivityStartsEnabled() {
5269 return mAmInternal.isBackgroundActivityStartsEnabled();
5270 }
5271
Wale Ogunwalef6733932018-06-27 05:14:34 -07005272 void enableScreenAfterBoot(boolean booted) {
5273 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5274 SystemClock.uptimeMillis());
5275 mWindowManager.enableScreenAfterBoot();
5276
5277 synchronized (mGlobalLock) {
5278 updateEventDispatchingLocked(booted);
5279 }
5280 }
5281
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005282 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5283 if (r == null || !r.hasProcess()) {
5284 return KEY_DISPATCHING_TIMEOUT_MS;
5285 }
5286 return getInputDispatchingTimeoutLocked(r.app);
5287 }
5288
5289 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005290 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005291 }
5292
Wale Ogunwalef6733932018-06-27 05:14:34 -07005293 /**
5294 * Decide based on the configuration whether we should show the ANR,
5295 * crash, etc dialogs. The idea is that if there is no affordance to
5296 * press the on-screen buttons, or the user experience would be more
5297 * greatly impacted than the crash itself, we shouldn't show the dialog.
5298 *
5299 * A thought: SystemUI might also want to get told about this, the Power
5300 * dialog / global actions also might want different behaviors.
5301 */
5302 private void updateShouldShowDialogsLocked(Configuration config) {
5303 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5304 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5305 && config.navigation == Configuration.NAVIGATION_NONAV);
5306 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5307 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5308 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5309 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5310 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5311 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5312 HIDE_ERROR_DIALOGS, 0) != 0;
5313 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5314 }
5315
5316 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5317 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5318 FONT_SCALE, 1.0f, userId);
5319
5320 synchronized (this) {
5321 if (getGlobalConfiguration().fontScale == scaleFactor) {
5322 return;
5323 }
5324
5325 final Configuration configuration
5326 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5327 configuration.fontScale = scaleFactor;
5328 updatePersistentConfiguration(configuration, userId);
5329 }
5330 }
5331
5332 // Actually is sleeping or shutting down or whatever else in the future
5333 // is an inactive state.
5334 boolean isSleepingOrShuttingDownLocked() {
5335 return isSleepingLocked() || mShuttingDown;
5336 }
5337
5338 boolean isSleepingLocked() {
5339 return mSleeping;
5340 }
5341
Riddle Hsu16567132018-08-16 21:37:47 +08005342 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005344 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005345 if (task.isActivityTypeStandard()) {
5346 if (mCurAppTimeTracker != r.appTimeTracker) {
5347 // We are switching app tracking. Complete the current one.
5348 if (mCurAppTimeTracker != null) {
5349 mCurAppTimeTracker.stop();
5350 mH.obtainMessage(
5351 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005352 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 mCurAppTimeTracker = null;
5354 }
5355 if (r.appTimeTracker != null) {
5356 mCurAppTimeTracker = r.appTimeTracker;
5357 startTimeTrackingFocusedActivityLocked();
5358 }
5359 } else {
5360 startTimeTrackingFocusedActivityLocked();
5361 }
5362 } else {
5363 r.appTimeTracker = null;
5364 }
5365 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5366 // TODO: Probably not, because we don't want to resume voice on switching
5367 // back to this activity
5368 if (task.voiceInteractor != null) {
5369 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5370 } else {
5371 finishRunningVoiceLocked();
5372
5373 if (mLastResumedActivity != null) {
5374 final IVoiceInteractionSession session;
5375
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005376 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005377 if (lastResumedActivityTask != null
5378 && lastResumedActivityTask.voiceSession != null) {
5379 session = lastResumedActivityTask.voiceSession;
5380 } else {
5381 session = mLastResumedActivity.voiceSession;
5382 }
5383
5384 if (session != null) {
5385 // We had been in a voice interaction session, but now focused has
5386 // move to something different. Just finish the session, we can't
5387 // return to it and retain the proper state and synchronization with
5388 // the voice interaction service.
5389 finishVoiceTask(session);
5390 }
5391 }
5392 }
5393
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005394 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5395 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005396 }
5397 updateResumedAppTrace(r);
5398 mLastResumedActivity = r;
5399
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005400 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005401
5402 applyUpdateLockStateLocked(r);
5403 applyUpdateVrModeLocked(r);
5404
5405 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005406 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005407 r == null ? "NULL" : r.shortComponentName,
5408 reason);
5409 }
5410
5411 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5412 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005413 final ActivityTaskManagerInternal.SleepToken token =
5414 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 updateSleepIfNeededLocked();
5416 return token;
5417 }
5418 }
5419
5420 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005421 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 final boolean wasSleeping = mSleeping;
5423 boolean updateOomAdj = false;
5424
5425 if (!shouldSleep) {
5426 // If wasSleeping is true, we need to wake up activity manager state from when
5427 // we started sleeping. In either case, we need to apply the sleep tokens, which
5428 // will wake up stacks or put them to sleep as appropriate.
5429 if (wasSleeping) {
5430 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005431 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5432 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 startTimeTrackingFocusedActivityLocked();
5434 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005435 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5437 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005438 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005439 if (wasSleeping) {
5440 updateOomAdj = true;
5441 }
5442 } else if (!mSleeping && shouldSleep) {
5443 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005444 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5445 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 if (mCurAppTimeTracker != null) {
5447 mCurAppTimeTracker.stop();
5448 }
5449 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005450 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 mStackSupervisor.goingToSleepLocked();
5452 updateResumedAppTrace(null /* resumed */);
5453 updateOomAdj = true;
5454 }
5455 if (updateOomAdj) {
5456 mH.post(mAmInternal::updateOomAdj);
5457 }
5458 }
5459
5460 void updateOomAdj() {
5461 mH.post(mAmInternal::updateOomAdj);
5462 }
5463
Wale Ogunwale53783742018-09-16 10:21:51 -07005464 void updateCpuStats() {
5465 mH.post(mAmInternal::updateCpuStats);
5466 }
5467
Hui Yu03d12402018-12-06 18:00:37 -08005468 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5469 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005470 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5471 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005472 mH.sendMessage(m);
5473 }
5474
Hui Yu03d12402018-12-06 18:00:37 -08005475 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005476 ComponentName taskRoot = null;
5477 final TaskRecord task = activity.getTaskRecord();
5478 if (task != null) {
5479 final ActivityRecord rootActivity = task.getRootActivity();
5480 if (rootActivity != null) {
5481 taskRoot = rootActivity.mActivityComponent;
5482 }
5483 }
5484
Hui Yu03d12402018-12-06 18:00:37 -08005485 final Message m = PooledLambda.obtainMessage(
5486 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005487 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005488 mH.sendMessage(m);
5489 }
5490
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005491 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5492 String hostingType) {
5493 try {
5494 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5495 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5496 + activity.processName);
5497 }
5498 // Post message to start process to avoid possible deadlock of calling into AMS with the
5499 // ATMS lock held.
5500 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5501 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5502 isTop, hostingType, activity.intent.getComponent());
5503 mH.sendMessage(m);
5504 } finally {
5505 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5506 }
5507 }
5508
Wale Ogunwale53783742018-09-16 10:21:51 -07005509 void setBooting(boolean booting) {
5510 mAmInternal.setBooting(booting);
5511 }
5512
5513 boolean isBooting() {
5514 return mAmInternal.isBooting();
5515 }
5516
5517 void setBooted(boolean booted) {
5518 mAmInternal.setBooted(booted);
5519 }
5520
5521 boolean isBooted() {
5522 return mAmInternal.isBooted();
5523 }
5524
5525 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5526 mH.post(() -> {
5527 if (finishBooting) {
5528 mAmInternal.finishBooting();
5529 }
5530 if (enableScreen) {
5531 mInternal.enableScreenAfterBoot(isBooted());
5532 }
5533 });
5534 }
5535
5536 void setHeavyWeightProcess(ActivityRecord root) {
5537 mHeavyWeightProcess = root.app;
5538 final Message m = PooledLambda.obtainMessage(
5539 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005540 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005541 mH.sendMessage(m);
5542 }
5543
5544 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5545 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5546 return;
5547 }
5548
5549 mHeavyWeightProcess = null;
5550 final Message m = PooledLambda.obtainMessage(
5551 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5552 proc.mUserId);
5553 mH.sendMessage(m);
5554 }
5555
5556 private void cancelHeavyWeightProcessNotification(int userId) {
5557 final INotificationManager inm = NotificationManager.getService();
5558 if (inm == null) {
5559 return;
5560 }
5561 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005562 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005563 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5564 } catch (RuntimeException e) {
5565 Slog.w(TAG, "Error canceling notification for service", e);
5566 } catch (RemoteException e) {
5567 }
5568
5569 }
5570
5571 private void postHeavyWeightProcessNotification(
5572 WindowProcessController proc, Intent intent, int userId) {
5573 if (proc == null) {
5574 return;
5575 }
5576
5577 final INotificationManager inm = NotificationManager.getService();
5578 if (inm == null) {
5579 return;
5580 }
5581
5582 try {
5583 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5584 String text = mContext.getString(R.string.heavy_weight_notification,
5585 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5586 Notification notification =
5587 new Notification.Builder(context,
5588 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5589 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5590 .setWhen(0)
5591 .setOngoing(true)
5592 .setTicker(text)
5593 .setColor(mContext.getColor(
5594 com.android.internal.R.color.system_notification_accent_color))
5595 .setContentTitle(text)
5596 .setContentText(
5597 mContext.getText(R.string.heavy_weight_notification_detail))
5598 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5599 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5600 new UserHandle(userId)))
5601 .build();
5602 try {
5603 inm.enqueueNotificationWithTag("android", "android", null,
5604 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5605 } catch (RuntimeException e) {
5606 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5607 } catch (RemoteException e) {
5608 }
5609 } catch (PackageManager.NameNotFoundException e) {
5610 Slog.w(TAG, "Unable to create context for heavy notification", e);
5611 }
5612
5613 }
5614
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005615 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5616 IBinder token, String resultWho, int requestCode, Intent[] intents,
5617 String[] resolvedTypes, int flags, Bundle bOptions) {
5618
5619 ActivityRecord activity = null;
5620 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5621 activity = ActivityRecord.isInStackLocked(token);
5622 if (activity == null) {
5623 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5624 return null;
5625 }
5626 if (activity.finishing) {
5627 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5628 return null;
5629 }
5630 }
5631
5632 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5633 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5634 bOptions);
5635 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5636 if (noCreate) {
5637 return rec;
5638 }
5639 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5640 if (activity.pendingResults == null) {
5641 activity.pendingResults = new HashSet<>();
5642 }
5643 activity.pendingResults.add(rec.ref);
5644 }
5645 return rec;
5646 }
5647
Andrii Kulian52d255c2018-07-13 11:32:19 -07005648 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005649 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005650 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005651 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5652 mCurAppTimeTracker.start(resumedActivity.packageName);
5653 }
5654 }
5655
5656 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5657 if (mTracedResumedActivity != null) {
5658 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5659 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5660 }
5661 if (resumed != null) {
5662 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5663 constructResumedTraceName(resumed.packageName), 0);
5664 }
5665 mTracedResumedActivity = resumed;
5666 }
5667
5668 private String constructResumedTraceName(String packageName) {
5669 return "focused app: " + packageName;
5670 }
5671
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005672 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005673 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005674 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005675 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005676 // mainStack is null during startup.
5677 if (mainStack != null) {
5678 if (changes != 0 && starting == null) {
5679 // If the configuration changed, and the caller is not already
5680 // in the process of starting an activity, then find the top
5681 // activity to check if its configuration needs to change.
5682 starting = mainStack.topRunningActivityLocked();
5683 }
5684
5685 if (starting != null) {
5686 kept = starting.ensureActivityConfiguration(changes,
5687 false /* preserveWindow */);
5688 // And we need to make sure at this point that all other activities
5689 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005690 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005691 !PRESERVE_WINDOWS);
5692 }
5693 }
5694
5695 return kept;
5696 }
5697
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005698 void scheduleAppGcsLocked() {
5699 mH.post(() -> mAmInternal.scheduleAppGcs());
5700 }
5701
Wale Ogunwale53783742018-09-16 10:21:51 -07005702 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5703 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5704 }
5705
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005706 /**
5707 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5708 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5709 * on demand.
5710 */
5711 IPackageManager getPackageManager() {
5712 return AppGlobals.getPackageManager();
5713 }
5714
5715 PackageManagerInternal getPackageManagerInternalLocked() {
5716 if (mPmInternal == null) {
5717 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5718 }
5719 return mPmInternal;
5720 }
5721
Hai Zhangf4da9be2019-05-01 13:46:06 +08005722 PermissionPolicyInternal getPermissionPolicyInternal() {
5723 if (mPermissionPolicyInternal == null) {
5724 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5725 }
5726 return mPermissionPolicyInternal;
5727 }
5728
Wale Ogunwale008163e2018-07-23 23:11:08 -07005729 AppWarnings getAppWarningsLocked() {
5730 return mAppWarnings;
5731 }
5732
Wale Ogunwale214f3482018-10-04 11:00:47 -07005733 Intent getHomeIntent() {
5734 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5735 intent.setComponent(mTopComponent);
5736 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5737 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5738 intent.addCategory(Intent.CATEGORY_HOME);
5739 }
5740 return intent;
5741 }
5742
Chilun2ef71f72018-11-16 17:57:15 +08005743 /**
5744 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5745 * activities.
5746 *
5747 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5748 * component defined in config_secondaryHomeComponent.
5749 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5750 */
5751 Intent getSecondaryHomeIntent(String preferredPackage) {
5752 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005753 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5754 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5755 if (preferredPackage == null || useSystemProvidedLauncher) {
5756 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005757 final String secondaryHomeComponent = mContext.getResources().getString(
5758 com.android.internal.R.string.config_secondaryHomeComponent);
5759 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5760 } else {
5761 intent.setPackage(preferredPackage);
5762 }
5763 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5764 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5765 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5766 }
5767 return intent;
5768 }
5769
Wale Ogunwale214f3482018-10-04 11:00:47 -07005770 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5771 if (info == null) return null;
5772 ApplicationInfo newInfo = new ApplicationInfo(info);
5773 newInfo.initForUser(userId);
5774 return newInfo;
5775 }
5776
Wale Ogunwale9c103022018-10-18 07:44:54 -07005777 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005778 if (uid == SYSTEM_UID) {
5779 // The system gets to run in any process. If there are multiple processes with the same
5780 // uid, just pick the first (this should never happen).
5781 final SparseArray<WindowProcessController> procs =
5782 mProcessNames.getMap().get(processName);
5783 if (procs == null) return null;
5784 final int procCount = procs.size();
5785 for (int i = 0; i < procCount; i++) {
5786 final int procUid = procs.keyAt(i);
5787 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5788 // Don't use an app process or different user process for system component.
5789 continue;
5790 }
5791 return procs.valueAt(i);
5792 }
5793 }
5794
5795 return mProcessNames.get(processName, uid);
5796 }
5797
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005798 WindowProcessController getProcessController(IApplicationThread thread) {
5799 if (thread == null) {
5800 return null;
5801 }
5802
5803 final IBinder threadBinder = thread.asBinder();
5804 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5805 for (int i = pmap.size()-1; i >= 0; i--) {
5806 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5807 for (int j = procs.size() - 1; j >= 0; j--) {
5808 final WindowProcessController proc = procs.valueAt(j);
5809 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5810 return proc;
5811 }
5812 }
5813 }
5814
5815 return null;
5816 }
5817
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005818 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005819 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005820 if (proc == null) return null;
5821 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5822 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005823 }
5824 return null;
5825 }
5826
Riddle Hsua0536432019-02-16 00:38:59 +08005827 int getUidState(int uid) {
5828 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005829 }
5830
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005831 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005832 // A uid is considered to be foreground if it has a visible non-toast window.
5833 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005834 }
5835
Ricky Wai96f5c352019-04-10 18:40:17 +01005836 boolean isDeviceOwner(int uid) {
5837 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005838 }
5839
Ricky Wai96f5c352019-04-10 18:40:17 +01005840 void setDeviceOwnerUid(int uid) {
5841 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005842 }
5843
Wale Ogunwale9de19442018-10-18 19:05:03 -07005844 /**
5845 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5846 * the whitelist
5847 */
5848 String getPendingTempWhitelistTagForUidLocked(int uid) {
5849 return mPendingTempWhitelist.get(uid);
5850 }
5851
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005852 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5853 if (true || Build.IS_USER) {
5854 return;
5855 }
5856
5857 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5858 StrictMode.allowThreadDiskWrites();
5859 try {
5860 File tracesDir = new File("/data/anr");
5861 File tracesFile = null;
5862 try {
5863 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5864
5865 StringBuilder sb = new StringBuilder();
5866 Time tobj = new Time();
5867 tobj.set(System.currentTimeMillis());
5868 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5869 sb.append(": ");
5870 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5871 sb.append(" since ");
5872 sb.append(msg);
5873 FileOutputStream fos = new FileOutputStream(tracesFile);
5874 fos.write(sb.toString().getBytes());
5875 if (app == null) {
5876 fos.write("\n*** No application process!".getBytes());
5877 }
5878 fos.close();
5879 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5880 } catch (IOException e) {
5881 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5882 return;
5883 }
5884
5885 if (app != null && app.getPid() > 0) {
5886 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5887 firstPids.add(app.getPid());
5888 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5889 }
5890
5891 File lastTracesFile = null;
5892 File curTracesFile = null;
5893 for (int i=9; i>=0; i--) {
5894 String name = String.format(Locale.US, "slow%02d.txt", i);
5895 curTracesFile = new File(tracesDir, name);
5896 if (curTracesFile.exists()) {
5897 if (lastTracesFile != null) {
5898 curTracesFile.renameTo(lastTracesFile);
5899 } else {
5900 curTracesFile.delete();
5901 }
5902 }
5903 lastTracesFile = curTracesFile;
5904 }
5905 tracesFile.renameTo(curTracesFile);
5906 } finally {
5907 StrictMode.setThreadPolicy(oldPolicy);
5908 }
5909 }
5910
Michal Karpinskida34cd42019-04-02 19:46:52 +01005911 boolean isAssociatedCompanionApp(int userId, int uid) {
5912 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5913 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005914 return false;
5915 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005916 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005917 }
5918
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005919 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005920 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005921
5922
Wale Ogunwale98875612018-10-12 07:53:02 -07005923 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5924 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005925
Riddle Hsud93a6c42018-11-29 21:50:06 +08005926 H(Looper looper) {
5927 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005928 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005929
5930 @Override
5931 public void handleMessage(Message msg) {
5932 switch (msg.what) {
5933 case REPORT_TIME_TRACKER_MSG: {
5934 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5935 tracker.deliverResult(mContext);
5936 } break;
5937 }
5938 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005939 }
5940
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005941 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005942 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005943
5944 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005945 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005946 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005947
5948 @Override
5949 public void handleMessage(Message msg) {
5950 switch (msg.what) {
5951 case DISMISS_DIALOG_UI_MSG: {
5952 final Dialog d = (Dialog) msg.obj;
5953 d.dismiss();
5954 break;
5955 }
5956 }
5957 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005958 }
5959
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005960 final class LocalService extends ActivityTaskManagerInternal {
5961 @Override
5962 public SleepToken acquireSleepToken(String tag, int displayId) {
5963 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005964 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 }
5966
5967 @Override
5968 public ComponentName getHomeActivityForUser(int userId) {
5969 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005970 final ActivityRecord homeActivity =
5971 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005972 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 }
5974 }
5975
5976 @Override
5977 public void onLocalVoiceInteractionStarted(IBinder activity,
5978 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5979 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005980 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005981 }
5982 }
5983
5984 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005985 public void notifyAppTransitionStarting(SparseIntArray reasons,
5986 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005987 synchronized (mGlobalLock) {
5988 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5989 reasons, timestamp);
5990 }
5991 }
5992
5993 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005994 public void notifySingleTaskDisplayDrawn(int displayId) {
5995 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
5996 }
5997
5998 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005999 public void notifyAppTransitionFinished() {
6000 synchronized (mGlobalLock) {
6001 mStackSupervisor.notifyAppTransitionDone();
6002 }
6003 }
6004
6005 @Override
6006 public void notifyAppTransitionCancelled() {
6007 synchronized (mGlobalLock) {
6008 mStackSupervisor.notifyAppTransitionDone();
6009 }
6010 }
6011
6012 @Override
6013 public List<IBinder> getTopVisibleActivities() {
6014 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006015 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006016 }
6017 }
6018
6019 @Override
6020 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6021 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006022 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006023 }
6024 }
6025
6026 @Override
6027 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6028 Bundle bOptions) {
6029 Preconditions.checkNotNull(intents, "intents");
6030 final String[] resolvedTypes = new String[intents.length];
6031
6032 // UID of the package on user userId.
6033 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6034 // packageUid may not be initialized.
6035 int packageUid = 0;
6036 final long ident = Binder.clearCallingIdentity();
6037
6038 try {
6039 for (int i = 0; i < intents.length; i++) {
6040 resolvedTypes[i] =
6041 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6042 }
6043
6044 packageUid = AppGlobals.getPackageManager().getPackageUid(
6045 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6046 } catch (RemoteException e) {
6047 // Shouldn't happen.
6048 } finally {
6049 Binder.restoreCallingIdentity(ident);
6050 }
6051
Riddle Hsu591bf612019-02-14 17:55:31 +08006052 return getActivityStartController().startActivitiesInPackage(
6053 packageUid, packageName,
6054 intents, resolvedTypes, null /* resultTo */,
6055 SafeActivityOptions.fromBundle(bOptions), userId,
6056 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6057 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006058 }
6059
6060 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006061 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6062 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6063 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6064 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006065 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006066 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006067 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6068 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6069 userId, validateIncomingUser, originatingPendingIntent,
6070 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006071 }
6072 }
6073
6074 @Override
6075 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6076 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6077 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6078 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006079 PendingIntentRecord originatingPendingIntent,
6080 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006081 synchronized (mGlobalLock) {
6082 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6083 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6084 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006085 validateIncomingUser, originatingPendingIntent,
6086 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006087 }
6088 }
6089
6090 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6092 Intent intent, Bundle options, int userId) {
6093 return ActivityTaskManagerService.this.startActivityAsUser(
6094 caller, callerPacakge, intent,
6095 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6096 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6097 false /*validateIncomingUser*/);
6098 }
6099
6100 @Override
lumark588a3e82018-07-20 18:53:54 +08006101 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006102 synchronized (mGlobalLock) {
6103
6104 // We might change the visibilities here, so prepare an empty app transition which
6105 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006106 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006107 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006108 if (activityDisplay == null) {
6109 return;
6110 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006111 final DisplayContent dc = activityDisplay.mDisplayContent;
6112 final boolean wasTransitionSet =
6113 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006115 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006117 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006118
6119 // If there was a transition set already we don't want to interfere with it as we
6120 // might be starting it too early.
6121 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006122 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 }
6124 }
6125 if (callback != null) {
6126 callback.run();
6127 }
6128 }
6129
6130 @Override
6131 public void notifyKeyguardTrustedChanged() {
6132 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006133 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006134 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137 }
6138
6139 /**
6140 * Called after virtual display Id is updated by
6141 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6142 * {@param vrVr2dDisplayId}.
6143 */
6144 @Override
6145 public void setVr2dDisplayId(int vr2dDisplayId) {
6146 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6147 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006148 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006149 }
6150 }
6151
6152 @Override
6153 public void setFocusedActivity(IBinder token) {
6154 synchronized (mGlobalLock) {
6155 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6156 if (r == null) {
6157 throw new IllegalArgumentException(
6158 "setFocusedActivity: No activity record matching token=" + token);
6159 }
Louis Chang19443452018-10-09 12:10:21 +08006160 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006161 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 }
6163 }
6164 }
6165
6166 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006168 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 }
6170
6171 @Override
6172 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006173 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175
6176 @Override
6177 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006178 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
6180
6181 @Override
6182 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6183 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6184 }
6185
6186 @Override
6187 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006188 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006190
6191 @Override
6192 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6193 synchronized (mGlobalLock) {
6194 mActiveVoiceInteractionServiceComponent = component;
6195 }
6196 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006197
6198 @Override
6199 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6200 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6201 return;
6202 }
6203 synchronized (mGlobalLock) {
6204 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6205 if (types == null) {
6206 if (uid < 0) {
6207 return;
6208 }
6209 types = new ArrayMap<>();
6210 mAllowAppSwitchUids.put(userId, types);
6211 }
6212 if (uid < 0) {
6213 types.remove(type);
6214 } else {
6215 types.put(type, uid);
6216 }
6217 }
6218 }
6219
6220 @Override
6221 public void onUserStopped(int userId) {
6222 synchronized (mGlobalLock) {
6223 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6224 mAllowAppSwitchUids.remove(userId);
6225 }
6226 }
6227
6228 @Override
6229 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6230 synchronized (mGlobalLock) {
6231 return ActivityTaskManagerService.this.isGetTasksAllowed(
6232 caller, callingPid, callingUid);
6233 }
6234 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006235
Riddle Hsua0536432019-02-16 00:38:59 +08006236 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006237 @Override
6238 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006239 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006240 mProcessNames.put(proc.mName, proc.mUid, proc);
6241 }
6242 }
6243
Riddle Hsua0536432019-02-16 00:38:59 +08006244 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006245 @Override
6246 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006247 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006248 mProcessNames.remove(name, uid);
6249 }
6250 }
6251
Riddle Hsua0536432019-02-16 00:38:59 +08006252 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006253 @Override
6254 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006255 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006256 if (proc == mHomeProcess) {
6257 mHomeProcess = null;
6258 }
6259 if (proc == mPreviousProcess) {
6260 mPreviousProcess = null;
6261 }
6262 }
6263 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006264
Riddle Hsua0536432019-02-16 00:38:59 +08006265 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006266 @Override
6267 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006268 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006269 return mTopProcessState;
6270 }
6271 }
6272
Riddle Hsua0536432019-02-16 00:38:59 +08006273 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006274 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006275 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006277 return proc == mHeavyWeightProcess;
6278 }
6279 }
6280
Riddle Hsua0536432019-02-16 00:38:59 +08006281 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006282 @Override
6283 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006284 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006285 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6286 }
6287 }
6288
6289 @Override
6290 public void finishHeavyWeightApp() {
6291 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006292 if (mHeavyWeightProcess != null) {
6293 mHeavyWeightProcess.finishActivities();
6294 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006295 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6296 mHeavyWeightProcess);
6297 }
6298 }
6299
Riddle Hsua0536432019-02-16 00:38:59 +08006300 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006301 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006302 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006303 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006304 return isSleepingLocked();
6305 }
6306 }
6307
6308 @Override
6309 public boolean isShuttingDown() {
6310 synchronized (mGlobalLock) {
6311 return mShuttingDown;
6312 }
6313 }
6314
6315 @Override
6316 public boolean shuttingDown(boolean booted, int timeout) {
6317 synchronized (mGlobalLock) {
6318 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006319 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006320 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006321 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006322 return mStackSupervisor.shutdownLocked(timeout);
6323 }
6324 }
6325
6326 @Override
6327 public void enableScreenAfterBoot(boolean booted) {
6328 synchronized (mGlobalLock) {
6329 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6330 SystemClock.uptimeMillis());
6331 mWindowManager.enableScreenAfterBoot();
6332 updateEventDispatchingLocked(booted);
6333 }
6334 }
6335
6336 @Override
6337 public boolean showStrictModeViolationDialog() {
6338 synchronized (mGlobalLock) {
6339 return mShowDialogs && !mSleeping && !mShuttingDown;
6340 }
6341 }
6342
6343 @Override
6344 public void showSystemReadyErrorDialogsIfNeeded() {
6345 synchronized (mGlobalLock) {
6346 try {
6347 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6348 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6349 + " data partition or your device will be unstable.");
6350 mUiHandler.post(() -> {
6351 if (mShowDialogs) {
6352 AlertDialog d = new BaseErrorDialog(mUiContext);
6353 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6354 d.setCancelable(false);
6355 d.setTitle(mUiContext.getText(R.string.android_system_label));
6356 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6357 d.setButton(DialogInterface.BUTTON_POSITIVE,
6358 mUiContext.getText(R.string.ok),
6359 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6360 d.show();
6361 }
6362 });
6363 }
6364 } catch (RemoteException e) {
6365 }
6366
6367 if (!Build.isBuildConsistent()) {
6368 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6369 mUiHandler.post(() -> {
6370 if (mShowDialogs) {
6371 AlertDialog d = new BaseErrorDialog(mUiContext);
6372 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6373 d.setCancelable(false);
6374 d.setTitle(mUiContext.getText(R.string.android_system_label));
6375 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6376 d.setButton(DialogInterface.BUTTON_POSITIVE,
6377 mUiContext.getText(R.string.ok),
6378 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6379 d.show();
6380 }
6381 });
6382 }
6383 }
6384 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006385
6386 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006387 public void onProcessMapped(int pid, WindowProcessController proc) {
6388 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006389 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006390 }
6391 }
6392
6393 @Override
6394 public void onProcessUnMapped(int pid) {
6395 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006396 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006397 }
6398 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006399
6400 @Override
6401 public void onPackageDataCleared(String name) {
6402 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006403 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006404 mAppWarnings.onPackageDataCleared(name);
6405 }
6406 }
6407
6408 @Override
6409 public void onPackageUninstalled(String name) {
6410 synchronized (mGlobalLock) {
6411 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006412 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006413 }
6414 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006415
6416 @Override
6417 public void onPackageAdded(String name, boolean replacing) {
6418 synchronized (mGlobalLock) {
6419 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6420 }
6421 }
6422
6423 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006424 public void onPackageReplaced(ApplicationInfo aInfo) {
6425 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006426 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006427 }
6428 }
6429
6430 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006431 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6432 synchronized (mGlobalLock) {
6433 return compatibilityInfoForPackageLocked(ai);
6434 }
6435 }
6436
Yunfan Chen75157d72018-07-27 14:47:21 +09006437 /**
6438 * Set the corresponding display information for the process global configuration. To be
6439 * called when we need to show IME on a different display.
6440 *
6441 * @param pid The process id associated with the IME window.
6442 * @param displayId The ID of the display showing the IME.
6443 */
6444 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006445 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006446 // Don't update process-level configuration for Multi-Client IME process since other
6447 // IMEs on other displays will also receive this configuration change due to IME
6448 // services use the same application config/context.
6449 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006450
Yunfan Chen75157d72018-07-27 14:47:21 +09006451 if (pid == MY_PID || pid < 0) {
6452 if (DEBUG_CONFIGURATION) {
6453 Slog.w(TAG,
6454 "Trying to update display configuration for system/invalid process.");
6455 }
6456 return;
6457 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006458 synchronized (mGlobalLock) {
6459 final ActivityDisplay activityDisplay =
6460 mRootActivityContainer.getActivityDisplay(displayId);
6461 if (activityDisplay == null) {
6462 // Call might come when display is not yet added or has been removed.
6463 if (DEBUG_CONFIGURATION) {
6464 Slog.w(TAG, "Trying to update display configuration for non-existing "
6465 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006466 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006467 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006468 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006469 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006470 if (process == null) {
6471 if (DEBUG_CONFIGURATION) {
6472 Slog.w(TAG, "Trying to update display configuration for invalid "
6473 + "process, pid=" + pid);
6474 }
6475 return;
6476 }
lumarkddc77fb2019-06-27 22:22:23 +08006477 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006478 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6479 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006480 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006481
6482 @Override
6483 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006484 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006485 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006486 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6487 if (r != null && r.getActivityStack() != null) {
6488 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6489 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006490 }
6491 }
6492 }
6493
6494 @Override
6495 public void clearPendingResultForActivity(IBinder activityToken,
6496 WeakReference<PendingIntentRecord> pir) {
6497 synchronized (mGlobalLock) {
6498 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6499 if (r != null && r.pendingResults != null) {
6500 r.pendingResults.remove(pir);
6501 }
6502 }
6503 }
6504
6505 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006506 public ActivityTokens getTopActivityForTask(int taskId) {
6507 synchronized (mGlobalLock) {
6508 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6509 if (taskRecord == null) {
6510 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6511 + " Requested task not found");
6512 return null;
6513 }
6514 final ActivityRecord activity = taskRecord.getTopActivity();
6515 if (activity == null) {
6516 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6517 + " Requested activity not found");
6518 return null;
6519 }
6520 if (!activity.attachedToProcess()) {
6521 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6522 + activity);
6523 return null;
6524 }
6525 return new ActivityTokens(activity.appToken, activity.assistToken,
6526 activity.app.getThread());
6527 }
6528 }
6529
6530 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006531 public IIntentSender getIntentSender(int type, String packageName,
6532 int callingUid, int userId, IBinder token, String resultWho,
6533 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6534 Bundle bOptions) {
6535 synchronized (mGlobalLock) {
6536 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6537 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6538 }
6539 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006540
6541 @Override
6542 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6543 synchronized (mGlobalLock) {
6544 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6545 if (r == null) {
6546 return null;
6547 }
6548 if (r.mServiceConnectionsHolder == null) {
6549 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6550 ActivityTaskManagerService.this, r);
6551 }
6552
6553 return r.mServiceConnectionsHolder;
6554 }
6555 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006556
6557 @Override
6558 public Intent getHomeIntent() {
6559 synchronized (mGlobalLock) {
6560 return ActivityTaskManagerService.this.getHomeIntent();
6561 }
6562 }
6563
6564 @Override
6565 public boolean startHomeActivity(int userId, String reason) {
6566 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006567 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006568 }
6569 }
6570
6571 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006572 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006573 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006574 synchronized (mGlobalLock) {
6575 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006576 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006577 }
Chilun8b1f1be2019-03-13 17:14:36 +08006578 }
6579
6580 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006581 public boolean startHomeOnAllDisplays(int userId, String reason) {
6582 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006583 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006584 }
6585 }
6586
Riddle Hsua0536432019-02-16 00:38:59 +08006587 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006588 @Override
6589 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006590 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006591 if (mFactoryTest == FACTORY_TEST_OFF) {
6592 return false;
6593 }
6594 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6595 && wpc.mName.equals(mTopComponent.getPackageName())) {
6596 return true;
6597 }
6598 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6599 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6600 }
6601 }
6602
6603 @Override
6604 public void updateTopComponentForFactoryTest() {
6605 synchronized (mGlobalLock) {
6606 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6607 return;
6608 }
6609 final ResolveInfo ri = mContext.getPackageManager()
6610 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6611 final CharSequence errorMsg;
6612 if (ri != null) {
6613 final ActivityInfo ai = ri.activityInfo;
6614 final ApplicationInfo app = ai.applicationInfo;
6615 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6616 mTopAction = Intent.ACTION_FACTORY_TEST;
6617 mTopData = null;
6618 mTopComponent = new ComponentName(app.packageName, ai.name);
6619 errorMsg = null;
6620 } else {
6621 errorMsg = mContext.getResources().getText(
6622 com.android.internal.R.string.factorytest_not_system);
6623 }
6624 } else {
6625 errorMsg = mContext.getResources().getText(
6626 com.android.internal.R.string.factorytest_no_action);
6627 }
6628 if (errorMsg == null) {
6629 return;
6630 }
6631
6632 mTopAction = null;
6633 mTopData = null;
6634 mTopComponent = null;
6635 mUiHandler.post(() -> {
6636 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6637 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006638 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006639 });
6640 }
6641 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006642
Riddle Hsua0536432019-02-16 00:38:59 +08006643 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006644 @Override
6645 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6646 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006647 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006648 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006649 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006650
6651 wpc.clearRecentTasks();
6652 wpc.clearActivities();
6653
6654 if (wpc.isInstrumenting()) {
6655 finishInstrumentationCallback.run();
6656 }
6657
Jorim Jaggid0752812018-10-16 16:07:20 +02006658 if (!restarting && hasVisibleActivities) {
6659 mWindowManager.deferSurfaceLayout();
6660 try {
6661 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6662 // If there was nothing to resume, and we are not already restarting
6663 // this process, but there is a visible activity that is hosted by the
6664 // process...then make sure all visible activities are running, taking
6665 // care of restarting this process.
6666 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6667 !PRESERVE_WINDOWS);
6668 }
6669 } finally {
6670 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006671 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006672 }
6673 }
6674 }
6675
6676 @Override
6677 public void closeSystemDialogs(String reason) {
6678 enforceNotIsolatedCaller("closeSystemDialogs");
6679
6680 final int pid = Binder.getCallingPid();
6681 final int uid = Binder.getCallingUid();
6682 final long origId = Binder.clearCallingIdentity();
6683 try {
6684 synchronized (mGlobalLock) {
6685 // Only allow this from foreground processes, so that background
6686 // applications can't abuse it to prevent system UI from being shown.
6687 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006688 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689 if (!proc.isPerceptible()) {
6690 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6691 + " from background process " + proc);
6692 return;
6693 }
6694 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 mWindowManager.closeSystemDialogs(reason);
6696
Wale Ogunwaled32da472018-11-16 07:19:28 -08006697 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006698 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006699 // Call into AM outside the synchronized block.
6700 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 } finally {
6702 Binder.restoreCallingIdentity(origId);
6703 }
6704 }
6705
6706 @Override
6707 public void cleanupDisabledPackageComponents(
6708 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6709 synchronized (mGlobalLock) {
6710 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006711 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006713 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714 mStackSupervisor.scheduleIdleLocked();
6715 }
6716
6717 // Clean-up disabled tasks
6718 getRecentTasks().cleanupDisabledPackageTasksLocked(
6719 packageName, disabledClasses, userId);
6720 }
6721 }
6722
6723 @Override
6724 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6725 int userId) {
6726 synchronized (mGlobalLock) {
6727
6728 boolean didSomething =
6729 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006730 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 null, doit, evenPersistent, userId);
6732 return didSomething;
6733 }
6734 }
6735
6736 @Override
6737 public void resumeTopActivities(boolean scheduleIdle) {
6738 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 if (scheduleIdle) {
6741 mStackSupervisor.scheduleIdleLocked();
6742 }
6743 }
6744 }
6745
Riddle Hsua0536432019-02-16 00:38:59 +08006746 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006747 @Override
6748 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006749 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6751 }
6752 }
6753
Riddle Hsua0536432019-02-16 00:38:59 +08006754 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 @Override
6756 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006757 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006758 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 }
6760 }
6761
6762 @Override
6763 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6764 try {
6765 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6766 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6767 }
6768 } catch (RemoteException ex) {
6769 throw new SecurityException("Fail to check is caller a privileged app", ex);
6770 }
6771
6772 synchronized (mGlobalLock) {
6773 final long ident = Binder.clearCallingIdentity();
6774 try {
6775 if (mAmInternal.shouldConfirmCredentials(userId)) {
6776 if (mKeyguardController.isKeyguardLocked()) {
6777 // Showing launcher to avoid user entering credential twice.
6778 startHomeActivity(currentUserId, "notifyLockedProfile");
6779 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006780 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 }
6782 } finally {
6783 Binder.restoreCallingIdentity(ident);
6784 }
6785 }
6786 }
6787
6788 @Override
6789 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6790 mAmInternal.enforceCallingPermission(
6791 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6792
6793 synchronized (mGlobalLock) {
6794 final long ident = Binder.clearCallingIdentity();
6795 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006796 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6797 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6800 UserHandle.CURRENT);
6801 } finally {
6802 Binder.restoreCallingIdentity(ident);
6803 }
6804 }
6805 }
6806
6807 @Override
6808 public void writeActivitiesToProto(ProtoOutputStream proto) {
6809 synchronized (mGlobalLock) {
6810 // The output proto of "activity --proto activities"
6811 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006813 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6814 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 }
6816 }
6817
6818 @Override
6819 public void saveANRState(String reason) {
6820 synchronized (mGlobalLock) {
6821 final StringWriter sw = new StringWriter();
6822 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6823 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6824 if (reason != null) {
6825 pw.println(" Reason: " + reason);
6826 }
6827 pw.println();
6828 getActivityStartController().dump(pw, " ", null);
6829 pw.println();
6830 pw.println("-------------------------------------------------------------------------------");
6831 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6832 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6833 "" /* header */);
6834 pw.println();
6835 pw.close();
6836
6837 mLastANRState = sw.toString();
6838 }
6839 }
6840
6841 @Override
6842 public void clearSavedANRState() {
6843 synchronized (mGlobalLock) {
6844 mLastANRState = null;
6845 }
6846 }
6847
6848 @Override
6849 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6850 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6851 synchronized (mGlobalLock) {
6852 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6853 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6854 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6855 dumpLastANRLocked(pw);
6856 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6857 dumpLastANRTracesLocked(pw);
6858 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6859 dumpActivityStarterLocked(pw, dumpPackage);
6860 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6861 dumpActivityContainersLocked(pw);
6862 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6863 if (getRecentTasks() != null) {
6864 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6865 }
6866 }
6867 }
6868 }
6869
6870 @Override
6871 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6872 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6873 int wakefulness) {
6874 synchronized (mGlobalLock) {
6875 if (mHomeProcess != null && (dumpPackage == null
6876 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6877 if (needSep) {
6878 pw.println();
6879 needSep = false;
6880 }
6881 pw.println(" mHomeProcess: " + mHomeProcess);
6882 }
6883 if (mPreviousProcess != null && (dumpPackage == null
6884 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6885 if (needSep) {
6886 pw.println();
6887 needSep = false;
6888 }
6889 pw.println(" mPreviousProcess: " + mPreviousProcess);
6890 }
6891 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6892 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6893 StringBuilder sb = new StringBuilder(128);
6894 sb.append(" mPreviousProcessVisibleTime: ");
6895 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6896 pw.println(sb);
6897 }
6898 if (mHeavyWeightProcess != null && (dumpPackage == null
6899 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6900 if (needSep) {
6901 pw.println();
6902 needSep = false;
6903 }
6904 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6905 }
6906 if (dumpPackage == null) {
6907 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006908 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 }
6910 if (dumpAll) {
6911 if (dumpPackage == null) {
6912 pw.println(" mConfigWillChange: "
6913 + getTopDisplayFocusedStack().mConfigWillChange);
6914 }
6915 if (mCompatModePackages.getPackages().size() > 0) {
6916 boolean printed = false;
6917 for (Map.Entry<String, Integer> entry
6918 : mCompatModePackages.getPackages().entrySet()) {
6919 String pkg = entry.getKey();
6920 int mode = entry.getValue();
6921 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6922 continue;
6923 }
6924 if (!printed) {
6925 pw.println(" mScreenCompatPackages:");
6926 printed = true;
6927 }
6928 pw.println(" " + pkg + ": " + mode);
6929 }
6930 }
6931 }
6932
6933 if (dumpPackage == null) {
6934 pw.println(" mWakefulness="
6935 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006936 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 if (mRunningVoice != null) {
6938 pw.println(" mRunningVoice=" + mRunningVoice);
6939 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6940 }
6941 pw.println(" mSleeping=" + mSleeping);
6942 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6943 pw.println(" mVrController=" + mVrController);
6944 }
6945 if (mCurAppTimeTracker != null) {
6946 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6947 }
6948 if (mAllowAppSwitchUids.size() > 0) {
6949 boolean printed = false;
6950 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6951 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6952 for (int j = 0; j < types.size(); j++) {
6953 if (dumpPackage == null ||
6954 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6955 if (needSep) {
6956 pw.println();
6957 needSep = false;
6958 }
6959 if (!printed) {
6960 pw.println(" mAllowAppSwitchUids:");
6961 printed = true;
6962 }
6963 pw.print(" User ");
6964 pw.print(mAllowAppSwitchUids.keyAt(i));
6965 pw.print(": Type ");
6966 pw.print(types.keyAt(j));
6967 pw.print(" = ");
6968 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6969 pw.println();
6970 }
6971 }
6972 }
6973 }
6974 if (dumpPackage == null) {
6975 if (mController != null) {
6976 pw.println(" mController=" + mController
6977 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6978 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006979 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6980 pw.println(" mLaunchingActivityWakeLock="
6981 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 }
6983
6984 return needSep;
6985 }
6986 }
6987
6988 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006989 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6990 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006991 synchronized (mGlobalLock) {
6992 if (dumpPackage == null) {
6993 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6994 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006995 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6996 if (mRunningVoice != null) {
6997 final long vrToken = proto.start(
6998 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6999 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7000 mRunningVoice.toString());
7001 mVoiceWakeLock.writeToProto(
7002 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7003 proto.end(vrToken);
7004 }
7005 mVrController.writeToProto(proto,
7006 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 if (mController != null) {
7008 final long token = proto.start(CONTROLLER);
7009 proto.write(CONTROLLER, mController.toString());
7010 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7011 proto.end(token);
7012 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007013 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7014 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7015 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007016 }
7017
7018 if (mHomeProcess != null && (dumpPackage == null
7019 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007020 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007021 }
7022
7023 if (mPreviousProcess != null && (dumpPackage == null
7024 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007025 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7027 }
7028
7029 if (mHeavyWeightProcess != null && (dumpPackage == null
7030 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007031 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007032 }
7033
7034 for (Map.Entry<String, Integer> entry
7035 : mCompatModePackages.getPackages().entrySet()) {
7036 String pkg = entry.getKey();
7037 int mode = entry.getValue();
7038 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7039 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7040 proto.write(PACKAGE, pkg);
7041 proto.write(MODE, mode);
7042 proto.end(compatToken);
7043 }
7044 }
7045
7046 if (mCurAppTimeTracker != null) {
7047 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7048 }
7049
7050 }
7051 }
7052
7053 @Override
7054 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7055 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7056 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007057 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7058 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007059 }
7060
7061 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007062 public void dumpForOom(PrintWriter pw) {
7063 synchronized (mGlobalLock) {
7064 pw.println(" mHomeProcess: " + mHomeProcess);
7065 pw.println(" mPreviousProcess: " + mPreviousProcess);
7066 if (mHeavyWeightProcess != null) {
7067 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7068 }
7069 }
7070 }
7071
7072 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 public boolean canGcNow() {
7074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007075 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 }
7077 }
7078
Riddle Hsua0536432019-02-16 00:38:59 +08007079 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 @Override
7081 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007082 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007083 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 return top != null ? top.app : null;
7085 }
7086 }
7087
Riddle Hsua0536432019-02-16 00:38:59 +08007088 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 @Override
7090 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007091 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007092 if (mRootActivityContainer != null) {
7093 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 }
7095 }
7096 }
7097
7098 @Override
7099 public void scheduleDestroyAllActivities(String reason) {
7100 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007101 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 }
7103 }
7104
7105 @Override
7106 public void removeUser(int userId) {
7107 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007108 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 }
7110 }
7111
7112 @Override
7113 public boolean switchUser(int userId, UserState userState) {
7114 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007115 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007116 }
7117 }
7118
7119 @Override
7120 public void onHandleAppCrash(WindowProcessController wpc) {
7121 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007122 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007123 }
7124 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007125
7126 @Override
7127 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7128 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007129 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007130 }
7131 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007132
Riddle Hsua0536432019-02-16 00:38:59 +08007133 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007134 @Override
7135 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007136 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007137 }
7138
Riddle Hsua0536432019-02-16 00:38:59 +08007139 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007140 @Override
7141 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007142 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007143 }
7144
Riddle Hsua0536432019-02-16 00:38:59 +08007145 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007146 @Override
7147 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007148 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007149 }
7150
Riddle Hsua0536432019-02-16 00:38:59 +08007151 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152 @Override
7153 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007154 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007155 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007156
7157 @Override
7158 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007159 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007160 mPendingTempWhitelist.put(uid, tag);
7161 }
7162 }
7163
7164 @Override
7165 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007166 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007167 mPendingTempWhitelist.remove(uid);
7168 }
7169 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007170
7171 @Override
7172 public boolean handleAppCrashInActivityController(String processName, int pid,
7173 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7174 Runnable killCrashingAppCallback) {
7175 synchronized (mGlobalLock) {
7176 if (mController == null) {
7177 return false;
7178 }
7179
7180 try {
7181 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7182 stackTrace)) {
7183 killCrashingAppCallback.run();
7184 return true;
7185 }
7186 } catch (RemoteException e) {
7187 mController = null;
7188 Watchdog.getInstance().setActivityController(null);
7189 }
7190 return false;
7191 }
7192 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007193
7194 @Override
7195 public void removeRecentTasksByPackageName(String packageName, int userId) {
7196 synchronized (mGlobalLock) {
7197 mRecentTasks.removeTasksByPackageName(packageName, userId);
7198 }
7199 }
7200
7201 @Override
7202 public void cleanupRecentTasksForUser(int userId) {
7203 synchronized (mGlobalLock) {
7204 mRecentTasks.cleanupLocked(userId);
7205 }
7206 }
7207
7208 @Override
7209 public void loadRecentTasksForUser(int userId) {
7210 synchronized (mGlobalLock) {
7211 mRecentTasks.loadUserRecentsLocked(userId);
7212 }
7213 }
7214
7215 @Override
7216 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7217 synchronized (mGlobalLock) {
7218 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7219 }
7220 }
7221
7222 @Override
7223 public void flushRecentTasks() {
7224 mRecentTasks.flush();
7225 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007226
7227 @Override
7228 public WindowProcessController getHomeProcess() {
7229 synchronized (mGlobalLock) {
7230 return mHomeProcess;
7231 }
7232 }
7233
7234 @Override
7235 public WindowProcessController getPreviousProcess() {
7236 synchronized (mGlobalLock) {
7237 return mPreviousProcess;
7238 }
7239 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007240
7241 @Override
7242 public void clearLockedTasks(String reason) {
7243 synchronized (mGlobalLock) {
7244 getLockTaskController().clearLockedTasks(reason);
7245 }
7246 }
7247
7248 @Override
7249 public void updateUserConfiguration() {
7250 synchronized (mGlobalLock) {
7251 final Configuration configuration = new Configuration(getGlobalConfiguration());
7252 final int currentUserId = mAmInternal.getCurrentUserId();
7253 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7254 configuration, currentUserId, Settings.System.canWrite(mContext));
7255 updateConfigurationLocked(configuration, null /* starting */,
7256 false /* initLocale */, false /* persistent */, currentUserId,
7257 false /* deferResume */);
7258 }
7259 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007260
7261 @Override
7262 public boolean canShowErrorDialogs() {
7263 synchronized (mGlobalLock) {
7264 return mShowDialogs && !mSleeping && !mShuttingDown
7265 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7266 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7267 mAmInternal.getCurrentUserId())
7268 && !(UserManager.isDeviceInDemoMode(mContext)
7269 && mAmInternal.getCurrentUser().isDemo());
7270 }
7271 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007272
7273 @Override
7274 public void setProfileApp(String profileApp) {
7275 synchronized (mGlobalLock) {
7276 mProfileApp = profileApp;
7277 }
7278 }
7279
7280 @Override
7281 public void setProfileProc(WindowProcessController wpc) {
7282 synchronized (mGlobalLock) {
7283 mProfileProc = wpc;
7284 }
7285 }
7286
7287 @Override
7288 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7289 synchronized (mGlobalLock) {
7290 mProfilerInfo = profilerInfo;
7291 }
7292 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007293
7294 @Override
7295 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7296 synchronized (mGlobalLock) {
7297 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7298 }
7299 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007300
7301 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007302 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7303 boolean reducedResolution) {
7304 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7305 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007306 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007307
7308 @Override
7309 public boolean isUidForeground(int uid) {
7310 synchronized (mGlobalLock) {
7311 return ActivityTaskManagerService.this.isUidForeground(uid);
7312 }
7313 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007314
7315 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007316 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007317 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007318 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007319 }
7320 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007321
7322 @Override
7323 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007324 // Translate package names into UIDs
7325 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007326 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007327 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7328 if (uid >= 0) {
7329 result.add(uid);
7330 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007331 }
7332 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007333 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007334 }
7335 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007336 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007337}