blob: 765c9d0a586473603290441739a63dcb2c53874d [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;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import 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;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100314 // How long we permit background activity starts after an activity in the process
315 // started or finished.
316 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317
Wale Ogunwale98875612018-10-12 07:53:02 -0700318 /** Used to indicate that an app transition should be animated. */
319 static final boolean ANIMATE = true;
320
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700321 /** Hardware-reported OpenGLES version. */
322 final int GL_ES_VERSION;
323
Wale Ogunwale31913b52018-10-13 08:29:31 -0700324 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
325 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
326 public static final String DUMP_LASTANR_CMD = "lastanr" ;
327 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
328 public static final String DUMP_STARTER_CMD = "starter" ;
329 public static final String DUMP_CONTAINERS_CMD = "containers" ;
330 public static final String DUMP_RECENTS_CMD = "recents" ;
331 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
332
Wale Ogunwale64258362018-10-16 15:13:37 -0700333 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
334 public static final int RELAUNCH_REASON_NONE = 0;
335 /** This activity is being relaunched due to windowing mode change. */
336 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
337 /** This activity is being relaunched due to a free-resize operation. */
338 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
339
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700340 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700341
Wale Ogunwalef6733932018-06-27 05:14:34 -0700342 /**
343 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
344 * change at runtime. Use mContext for non-UI purposes.
345 */
346 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700348 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700351 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700352 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800353 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800354 @VisibleForTesting
355 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 PowerManagerInternal mPowerManagerInternal;
357 private UsageStatsManagerInternal mUsageStatsInternal;
358
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700359 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 IntentFirewall mIntentFirewall;
361
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700362 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800363 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 /**
365 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
366 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
367 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
368 *
369 * @see WindowManagerThreadPriorityBooster
370 */
371 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800373 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700374 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700375 private UserManagerService mUserManager;
376 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700377 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800378 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700379 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** All processes currently running that might have a window organized by name. */
381 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100382 /** All processes we currently have running mapped by pid and uid */
383 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** This is the process holding what we currently consider to be the "home" activity. */
385 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700386 /** The currently running heavy-weight process, if any. */
387 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700388 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /**
390 * This is the process holding the activity the user last visited that is in a different process
391 * from the one they are currently in.
392 */
393 WindowProcessController mPreviousProcess;
394 /** The time at which the previous process was last visible. */
395 long mPreviousProcessVisibleTime;
396
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700397 /** List of intents that were used to start the most recent tasks. */
398 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700399 /** State of external calls telling us if the device is awake or asleep. */
400 private boolean mKeyguardShown = false;
401
402 // Wrapper around VoiceInteractionServiceManager
403 private AssistUtils mAssistUtils;
404
405 // VoiceInteraction session ID that changes for each new request except when
406 // being called for multi-window assist in a single session.
407 private int mViSessionId = 1000;
408
409 // How long to wait in getAssistContextExtras for the activity and foreground services
410 // to respond with the result.
411 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
412
413 // How long top wait when going through the modern assist (which doesn't need to block
414 // on getting this result before starting to launch its UI).
415 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
416
417 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
418 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
419
Alison Cichowlas3e340502018-08-07 17:15:01 -0400420 // Permission tokens are used to temporarily granted a trusted app the ability to call
421 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
422 // showing any appropriate error messages to the user.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
424 10 * MINUTE_IN_MILLIS;
425
426 // How long before the service actually expires a token. This is slightly longer than
427 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
428 // expiration exception.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
430 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
431
432 // How long the service will remember expired tokens, for the purpose of providing error
433 // messaging when a client uses an expired token.
434 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
435 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
436
Marvin Ramin830d4e32019-03-12 13:16:58 +0100437 // How long to whitelist the Services for when requested.
438 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
439
Alison Cichowlas3e340502018-08-07 17:15:01 -0400440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
466 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
511 IActivityController mController = null;
512 boolean mControllerIsAMonkey = false;
513
Wale Ogunwale214f3482018-10-04 11:00:47 -0700514 final int mFactoryTest;
515
516 /** Used to control how we initialize the service. */
517 ComponentName mTopComponent;
518 String mTopAction = Intent.ACTION_MAIN;
519 String mTopData;
520
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800521 /** Profiling app information. */
522 String mProfileApp = null;
523 WindowProcessController mProfileProc = null;
524 ProfilerInfo mProfilerInfo = null;
525
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700526 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700527 * Dump of the activity state at the time of the last ANR. Cleared after
528 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
529 */
530 String mLastANRState;
531
532 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 * Used to retain an update lock when the foreground activity is in
534 * immersive mode.
535 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700536 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537
538 /**
539 * Packages that are being allowed to perform unrestricted app switches. Mapping is
540 * User -> Type -> uid.
541 */
542 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
543
544 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700545 private int mThumbnailWidth;
546 private int mThumbnailHeight;
547 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700548
549 /**
550 * Flag that indicates if multi-window is enabled.
551 *
552 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
553 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
554 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
555 * At least one of the forms of multi-window must be enabled in order for this flag to be
556 * initialized to 'true'.
557 *
558 * @see #mSupportsSplitScreenMultiWindow
559 * @see #mSupportsFreeformWindowManagement
560 * @see #mSupportsPictureInPicture
561 * @see #mSupportsMultiDisplay
562 */
563 boolean mSupportsMultiWindow;
564 boolean mSupportsSplitScreenMultiWindow;
565 boolean mSupportsFreeformWindowManagement;
566 boolean mSupportsPictureInPicture;
567 boolean mSupportsMultiDisplay;
568 boolean mForceResizableActivities;
569
570 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
571
572 // VR Vr2d Display Id.
573 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700574
Wale Ogunwalef6733932018-06-27 05:14:34 -0700575 /**
576 * Set while we are wanting to sleep, to prevent any
577 * activities from being started/resumed.
578 *
579 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
580 *
581 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
582 * while in the sleep state until there is a pending transition out of sleep, in which case
583 * mSleeping is set to false, and remains false while awake.
584 *
585 * Whether mSleeping can quickly toggled between true/false without the device actually
586 * display changing states is undefined.
587 */
588 private boolean mSleeping = false;
589
590 /**
591 * The process state used for processes that are running the top activities.
592 * This changes between TOP and TOP_SLEEPING to following mSleeping.
593 */
594 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
595
596 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
597 // automatically. Important for devices without direct input devices.
598 private boolean mShowDialogs = true;
599
600 /** Set if we are shutting down the system, similar to sleeping. */
601 boolean mShuttingDown = false;
602
603 /**
604 * We want to hold a wake lock while running a voice interaction session, since
605 * this may happen with the screen off and we need to keep the CPU running to
606 * be able to continue to interact with the user.
607 */
608 PowerManager.WakeLock mVoiceWakeLock;
609
610 /**
611 * Set while we are running a voice interaction. This overrides sleeping while it is active.
612 */
613 IVoiceInteractionSession mRunningVoice;
614
615 /**
616 * The last resumed activity. This is identical to the current resumed activity most
617 * of the time but could be different when we're pausing one activity before we resume
618 * another activity.
619 */
620 ActivityRecord mLastResumedActivity;
621
622 /**
623 * The activity that is currently being traced as the active resumed activity.
624 *
625 * @see #updateResumedAppTrace
626 */
627 private @Nullable ActivityRecord mTracedResumedActivity;
628
629 /** If non-null, we are tracking the time the user spends in the currently focused app. */
630 AppTimeTracker mCurAppTimeTracker;
631
Wale Ogunwale008163e2018-07-23 23:11:08 -0700632 private AppWarnings mAppWarnings;
633
Wale Ogunwale53783742018-09-16 10:21:51 -0700634 /**
635 * Packages that the user has asked to have run in screen size
636 * compatibility mode instead of filling the screen.
637 */
638 CompatModePackages mCompatModePackages;
639
Wale Ogunwalef6733932018-06-27 05:14:34 -0700640 private FontScaleSettingObserver mFontScaleSettingObserver;
641
Ricky Wai96f5c352019-04-10 18:40:17 +0100642 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000643
Wale Ogunwalef6733932018-06-27 05:14:34 -0700644 private final class FontScaleSettingObserver extends ContentObserver {
645 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
646 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
647
648 public FontScaleSettingObserver() {
649 super(mH);
650 final ContentResolver resolver = mContext.getContentResolver();
651 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
652 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
653 UserHandle.USER_ALL);
654 }
655
656 @Override
657 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
658 if (mFontScaleUri.equals(uri)) {
659 updateFontScaleIfNeeded(userId);
660 } else if (mHideErrorDialogsUri.equals(uri)) {
661 synchronized (mGlobalLock) {
662 updateShouldShowDialogsLocked(getGlobalConfiguration());
663 }
664 }
665 }
666 }
667
Riddle Hsua0536432019-02-16 00:38:59 +0800668 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
669 @Target(ElementType.METHOD)
670 @Retention(RetentionPolicy.SOURCE)
671 @interface HotPath {
672 int NONE = 0;
673 int OOM_ADJUSTMENT = 1;
674 int LRU_UPDATE = 2;
675 int PROCESS_CHANGE = 3;
676 int caller() default NONE;
677 }
678
Charles Chen8d98dd22018-12-26 17:36:54 +0800679 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
680 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700681 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700682 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700683 mSystemThread = ActivityThread.currentActivityThread();
684 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700685 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800686 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700687 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700688 }
689
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700690 public void onSystemReady() {
691 synchronized (mGlobalLock) {
692 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
693 PackageManager.FEATURE_CANT_SAVE_STATE);
694 mAssistUtils = new AssistUtils(mContext);
695 mVrController.onSystemReady();
696 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700697 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700698 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700699 }
700
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700701 public void onInitPowerManagement() {
702 synchronized (mGlobalLock) {
703 mStackSupervisor.initPowerManagement();
704 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
705 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
706 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
707 mVoiceWakeLock.setReferenceCounted(false);
708 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700709 }
710
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700711 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700712 mFontScaleSettingObserver = new FontScaleSettingObserver();
713 }
714
Wale Ogunwale59507092018-10-29 09:00:30 -0700715 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700716 final boolean freeformWindowManagement =
717 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
718 || Settings.Global.getInt(
719 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
720
721 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
722 final boolean supportsPictureInPicture = supportsMultiWindow &&
723 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
724 final boolean supportsSplitScreenMultiWindow =
725 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
726 final boolean supportsMultiDisplay = mContext.getPackageManager()
727 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
729 final boolean forceResizable = Settings.Global.getInt(
730 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700731 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732
733 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900734 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735
736 final Configuration configuration = new Configuration();
737 Settings.System.getConfiguration(resolver, configuration);
738 if (forceRtl) {
739 // This will take care of setting the correct layout direction flags
740 configuration.setLayoutDirection(configuration.locale);
741 }
742
743 synchronized (mGlobalLock) {
744 mForceResizableActivities = forceResizable;
745 final boolean multiWindowFormEnabled = freeformWindowManagement
746 || supportsSplitScreenMultiWindow
747 || supportsPictureInPicture
748 || supportsMultiDisplay;
749 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
750 mSupportsMultiWindow = true;
751 mSupportsFreeformWindowManagement = freeformWindowManagement;
752 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
753 mSupportsPictureInPicture = supportsPictureInPicture;
754 mSupportsMultiDisplay = supportsMultiDisplay;
755 } else {
756 mSupportsMultiWindow = false;
757 mSupportsFreeformWindowManagement = false;
758 mSupportsSplitScreenMultiWindow = false;
759 mSupportsPictureInPicture = false;
760 mSupportsMultiDisplay = false;
761 }
762 mWindowManager.setForceResizableTasks(mForceResizableActivities);
763 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700764 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
765 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700766 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767 // This happens before any activities are started, so we can change global configuration
768 // in-place.
769 updateConfigurationLocked(configuration, null, true);
770 final Configuration globalConfig = getGlobalConfiguration();
771 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
772
773 // Load resources only after the current configuration has been set.
774 final Resources res = mContext.getResources();
775 mThumbnailWidth = res.getDimensionPixelSize(
776 com.android.internal.R.dimen.thumbnail_width);
777 mThumbnailHeight = res.getDimensionPixelSize(
778 com.android.internal.R.dimen.thumbnail_height);
779
780 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
781 mFullscreenThumbnailScale = (float) res
782 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
783 (float) globalConfig.screenWidthDp;
784 } else {
785 mFullscreenThumbnailScale = res.getFraction(
786 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
787 }
788 }
789 }
790
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800791 public WindowManagerGlobalLock getGlobalLock() {
792 return mGlobalLock;
793 }
794
Yunfan Chen585f2932019-01-29 16:04:45 +0900795 /** For test purpose only. */
796 @VisibleForTesting
797 public ActivityTaskManagerInternal getAtmInternal() {
798 return mInternal;
799 }
800
Riddle Hsud93a6c42018-11-29 21:50:06 +0800801 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
802 Looper looper) {
803 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700804 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700806 final File systemDir = SystemServiceManager.ensureSystemDir();
807 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
808 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700809 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700810
811 mTempConfig.setToDefaults();
812 mTempConfig.setLocales(LocaleList.getDefault());
813 mConfigurationSeq = mTempConfig.seq = 1;
814 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer = new RootActivityContainer(this);
816 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700818 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700819 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700820 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700821 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700822 mRecentTasks = createRecentTasks();
823 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700824 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700825 mKeyguardController = mStackSupervisor.getKeyguardController();
826 }
827
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700828 public void onActivityManagerInternalAdded() {
829 synchronized (mGlobalLock) {
830 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
831 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
832 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700833 }
834
Yunfan Chen75157d72018-07-27 14:47:21 +0900835 int increaseConfigurationSeqLocked() {
836 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
837 return mConfigurationSeq;
838 }
839
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840 protected ActivityStackSupervisor createStackSupervisor() {
841 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
842 supervisor.initialize();
843 return supervisor;
844 }
845
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700846 public void setWindowManager(WindowManagerService wm) {
847 synchronized (mGlobalLock) {
848 mWindowManager = wm;
849 mLockTaskController.setWindowManager(wm);
850 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800851 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700853 }
854
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700855 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
856 synchronized (mGlobalLock) {
857 mUsageStatsInternal = usageStatsManager;
858 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700859 }
860
Wale Ogunwalef6733932018-06-27 05:14:34 -0700861 UserManagerService getUserManager() {
862 if (mUserManager == null) {
863 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
864 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
865 }
866 return mUserManager;
867 }
868
869 AppOpsService getAppOpsService() {
870 if (mAppOpsService == null) {
871 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
872 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
873 }
874 return mAppOpsService;
875 }
876
877 boolean hasUserRestriction(String restriction, int userId) {
878 return getUserManager().hasUserRestriction(restriction, userId);
879 }
880
Michal Karpinski15486842019-04-25 17:33:42 +0100881 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
882 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
883 callingUid, callingPackage);
884 if (mode == AppOpsManager.MODE_DEFAULT) {
885 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
886 == PERMISSION_GRANTED;
887 }
888 return mode == AppOpsManager.MODE_ALLOWED;
889 }
890
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700891 protected RecentTasks createRecentTasks() {
892 return new RecentTasks(this, mStackSupervisor);
893 }
894
895 RecentTasks getRecentTasks() {
896 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700897 }
898
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700899 ClientLifecycleManager getLifecycleManager() {
900 return mLifecycleManager;
901 }
902
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700903 ActivityStartController getActivityStartController() {
904 return mActivityStartController;
905 }
906
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700907 TaskChangeNotificationController getTaskChangeNotificationController() {
908 return mTaskChangeNotificationController;
909 }
910
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700911 LockTaskController getLockTaskController() {
912 return mLockTaskController;
913 }
914
Yunfan Chen75157d72018-07-27 14:47:21 +0900915 /**
916 * Return the global configuration used by the process corresponding to the input pid. This is
917 * usually the global configuration with some overrides specific to that process.
918 */
919 Configuration getGlobalConfigurationForCallingPid() {
920 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800921 return getGlobalConfigurationForPid(pid);
922 }
923
924 /**
925 * Return the global configuration used by the process corresponding to the given pid.
926 */
927 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900928 if (pid == MY_PID || pid < 0) {
929 return getGlobalConfiguration();
930 }
931 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100932 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900933 return app != null ? app.getConfiguration() : getGlobalConfiguration();
934 }
935 }
936
937 /**
938 * Return the device configuration info used by the process corresponding to the input pid.
939 * The value is consistent with the global configuration for the process.
940 */
941 @Override
942 public ConfigurationInfo getDeviceConfigurationInfo() {
943 ConfigurationInfo config = new ConfigurationInfo();
944 synchronized (mGlobalLock) {
945 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
946 config.reqTouchScreen = globalConfig.touchscreen;
947 config.reqKeyboardType = globalConfig.keyboard;
948 config.reqNavigation = globalConfig.navigation;
949 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
950 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
951 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
952 }
953 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
954 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
955 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
956 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700957 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 }
959 return config;
960 }
961
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700962 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700963 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 }
965
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700966 public static final class Lifecycle extends SystemService {
967 private final ActivityTaskManagerService mService;
968
969 public Lifecycle(Context context) {
970 super(context);
971 mService = new ActivityTaskManagerService(context);
972 }
973
974 @Override
975 public void onStart() {
976 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700977 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700978 }
979
Garfield Tan891146c2018-10-09 12:14:00 -0700980 @Override
981 public void onUnlockUser(int userId) {
982 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800983 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700984 }
985 }
986
987 @Override
988 public void onCleanupUser(int userId) {
989 synchronized (mService.getGlobalLock()) {
990 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
991 }
992 }
993
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700994 public ActivityTaskManagerService getService() {
995 return mService;
996 }
997 }
998
999 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001000 public final int startActivity(IApplicationThread caller, String callingPackage,
1001 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1002 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1003 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1004 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1005 UserHandle.getCallingUserId());
1006 }
1007
1008 @Override
1009 public final int startActivities(IApplicationThread caller, String callingPackage,
1010 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1011 int userId) {
1012 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 enforceNotIsolatedCaller(reason);
1014 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001016 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1017 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1018 reason, null /* originatingPendingIntent */,
1019 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 }
1021
1022 @Override
1023 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1024 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1025 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1026 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1027 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1028 true /*validateIncomingUser*/);
1029 }
1030
1031 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1032 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1033 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1034 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001037 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1039
1040 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001041 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 .setCaller(caller)
1043 .setCallingPackage(callingPackage)
1044 .setResolvedType(resolvedType)
1045 .setResultTo(resultTo)
1046 .setResultWho(resultWho)
1047 .setRequestCode(requestCode)
1048 .setStartFlags(startFlags)
1049 .setProfilerInfo(profilerInfo)
1050 .setActivityOptions(bOptions)
1051 .setMayWait(userId)
1052 .execute();
1053
1054 }
1055
1056 @Override
1057 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1058 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1060 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 // Refuse possible leaked file descriptors
1062 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1063 throw new IllegalArgumentException("File descriptors passed in Intent");
1064 }
1065
1066 if (!(target instanceof PendingIntentRecord)) {
1067 throw new IllegalArgumentException("Bad PendingIntent object");
1068 }
1069
1070 PendingIntentRecord pir = (PendingIntentRecord)target;
1071
1072 synchronized (mGlobalLock) {
1073 // If this is coming from the currently resumed activity, it is
1074 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001075 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 if (stack.mResumedActivity != null &&
1077 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 }
1080 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001081 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 }
1084
1085 @Override
1086 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1087 Bundle bOptions) {
1088 // Refuse possible leaked file descriptors
1089 if (intent != null && intent.hasFileDescriptors()) {
1090 throw new IllegalArgumentException("File descriptors passed in Intent");
1091 }
1092 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1093
1094 synchronized (mGlobalLock) {
1095 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1096 if (r == null) {
1097 SafeActivityOptions.abort(options);
1098 return false;
1099 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001100 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001101 // The caller is not running... d'oh!
1102 SafeActivityOptions.abort(options);
1103 return false;
1104 }
1105 intent = new Intent(intent);
1106 // The caller is not allowed to change the data.
1107 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1108 // And we are resetting to find the next component...
1109 intent.setComponent(null);
1110
1111 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1112
1113 ActivityInfo aInfo = null;
1114 try {
1115 List<ResolveInfo> resolves =
1116 AppGlobals.getPackageManager().queryIntentActivities(
1117 intent, r.resolvedType,
1118 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1119 UserHandle.getCallingUserId()).getList();
1120
1121 // Look for the original activity in the list...
1122 final int N = resolves != null ? resolves.size() : 0;
1123 for (int i=0; i<N; i++) {
1124 ResolveInfo rInfo = resolves.get(i);
1125 if (rInfo.activityInfo.packageName.equals(r.packageName)
1126 && rInfo.activityInfo.name.equals(r.info.name)) {
1127 // We found the current one... the next matching is
1128 // after it.
1129 i++;
1130 if (i<N) {
1131 aInfo = resolves.get(i).activityInfo;
1132 }
1133 if (debug) {
1134 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1135 + "/" + r.info.name);
1136 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1137 ? "null" : aInfo.packageName + "/" + aInfo.name));
1138 }
1139 break;
1140 }
1141 }
1142 } catch (RemoteException e) {
1143 }
1144
1145 if (aInfo == null) {
1146 // Nobody who is next!
1147 SafeActivityOptions.abort(options);
1148 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1149 return false;
1150 }
1151
1152 intent.setComponent(new ComponentName(
1153 aInfo.applicationInfo.packageName, aInfo.name));
1154 intent.setFlags(intent.getFlags()&~(
1155 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1156 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1157 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1158 FLAG_ACTIVITY_NEW_TASK));
1159
1160 // Okay now we need to start the new activity, replacing the currently running activity.
1161 // This is a little tricky because we want to start the new one as if the current one is
1162 // finished, but not finish the current one first so that there is no flicker.
1163 // And thus...
1164 final boolean wasFinishing = r.finishing;
1165 r.finishing = true;
1166
1167 // Propagate reply information over to the new activity.
1168 final ActivityRecord resultTo = r.resultTo;
1169 final String resultWho = r.resultWho;
1170 final int requestCode = r.requestCode;
1171 r.resultTo = null;
1172 if (resultTo != null) {
1173 resultTo.removeResultsLocked(r, resultWho, requestCode);
1174 }
1175
1176 final long origId = Binder.clearCallingIdentity();
1177 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001178 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001179 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001180 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 .setResolvedType(r.resolvedType)
1182 .setActivityInfo(aInfo)
1183 .setResultTo(resultTo != null ? resultTo.appToken : null)
1184 .setResultWho(resultWho)
1185 .setRequestCode(requestCode)
1186 .setCallingPid(-1)
1187 .setCallingUid(r.launchedFromUid)
1188 .setCallingPackage(r.launchedFromPackage)
1189 .setRealCallingPid(-1)
1190 .setRealCallingUid(r.launchedFromUid)
1191 .setActivityOptions(options)
1192 .execute();
1193 Binder.restoreCallingIdentity(origId);
1194
1195 r.finishing = wasFinishing;
1196 if (res != ActivityManager.START_SUCCESS) {
1197 return false;
1198 }
1199 return true;
1200 }
1201 }
1202
1203 @Override
1204 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1205 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1206 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1207 final WaitResult res = new WaitResult();
1208 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001209 enforceNotIsolatedCaller("startActivityAndWait");
1210 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1211 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001213 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 .setCaller(caller)
1215 .setCallingPackage(callingPackage)
1216 .setResolvedType(resolvedType)
1217 .setResultTo(resultTo)
1218 .setResultWho(resultWho)
1219 .setRequestCode(requestCode)
1220 .setStartFlags(startFlags)
1221 .setActivityOptions(bOptions)
1222 .setMayWait(userId)
1223 .setProfilerInfo(profilerInfo)
1224 .setWaitResult(res)
1225 .execute();
1226 }
1227 return res;
1228 }
1229
1230 @Override
1231 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1232 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1233 int startFlags, Configuration config, Bundle bOptions, int userId) {
1234 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001235 enforceNotIsolatedCaller("startActivityWithConfig");
1236 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1237 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001239 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001240 .setCaller(caller)
1241 .setCallingPackage(callingPackage)
1242 .setResolvedType(resolvedType)
1243 .setResultTo(resultTo)
1244 .setResultWho(resultWho)
1245 .setRequestCode(requestCode)
1246 .setStartFlags(startFlags)
1247 .setGlobalConfiguration(config)
1248 .setActivityOptions(bOptions)
1249 .setMayWait(userId)
1250 .execute();
1251 }
1252 }
1253
Alison Cichowlas3e340502018-08-07 17:15:01 -04001254
1255 @Override
1256 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1257 int callingUid = Binder.getCallingUid();
1258 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1259 throw new SecurityException("Only the system process can request a permission token, "
1260 + "received request from uid: " + callingUid);
1261 }
1262 IBinder permissionToken = new Binder();
1263 synchronized (mGlobalLock) {
1264 mStartActivitySources.put(permissionToken, delegatorToken);
1265 }
1266
1267 Message expireMsg = PooledLambda.obtainMessage(
1268 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1269 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1270
1271 Message forgetMsg = PooledLambda.obtainMessage(
1272 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1273 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1274
1275 return permissionToken;
1276 }
1277
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 @Override
1279 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1280 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1282 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001283 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001284 // permission grants) as any app that may launch one of your own activities. So we only
1285 // allow this in two cases:
1286 // 1) The caller is an activity that is part of the core framework, and then only when it
1287 // is running as the system.
1288 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1289 // can only be requested by a system activity, which may then delegate this call to
1290 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 final ActivityRecord sourceRecord;
1292 final int targetUid;
1293 final String targetPackage;
1294 final boolean isResolver;
1295 synchronized (mGlobalLock) {
1296 if (resultTo == null) {
1297 throw new SecurityException("Must be called from an activity");
1298 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 final IBinder sourceToken;
1300 if (permissionToken != null) {
1301 // To even attempt to use a permissionToken, an app must also have this signature
1302 // permission.
1303 mAmInternal.enforceCallingPermission(
1304 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1305 "startActivityAsCaller");
1306 // If called with a permissionToken, we want the sourceRecord from the delegator
1307 // activity that requested this token.
1308 sourceToken = mStartActivitySources.remove(permissionToken);
1309 if (sourceToken == null) {
1310 // Invalid permissionToken, check if it recently expired.
1311 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1312 throw new SecurityException("Called with expired permission token: "
1313 + permissionToken);
1314 } else {
1315 throw new SecurityException("Called with invalid permission token: "
1316 + permissionToken);
1317 }
1318 }
1319 } else {
1320 // This method was called directly by the source.
1321 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323
Wale Ogunwaled32da472018-11-16 07:19:28 -08001324 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325 if (sourceRecord == null) {
1326 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 }
1328 if (sourceRecord.app == null) {
1329 throw new SecurityException("Called without a process attached to activity");
1330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331
1332 // Whether called directly or from a delegate, the source activity must be from the
1333 // android package.
1334 if (!sourceRecord.info.packageName.equals("android")) {
1335 throw new SecurityException("Must be called from an activity that is "
1336 + "declared in the android package");
1337 }
1338
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 // This is still okay, as long as this activity is running under the
1341 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001342 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 + " must be system uid or original calling uid "
1346 + sourceRecord.launchedFromUid);
1347 }
1348 }
1349 if (ignoreTargetSecurity) {
1350 if (intent.getComponent() == null) {
1351 throw new SecurityException(
1352 "Component must be specified with ignoreTargetSecurity");
1353 }
1354 if (intent.getSelector() != null) {
1355 throw new SecurityException(
1356 "Selector not allowed with ignoreTargetSecurity");
1357 }
1358 }
1359 targetUid = sourceRecord.launchedFromUid;
1360 targetPackage = sourceRecord.launchedFromPackage;
1361 isResolver = sourceRecord.isResolverOrChildActivity();
1362 }
1363
1364 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 }
1367
1368 // TODO: Switch to user app stacks here.
1369 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001370 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 .setCallingUid(targetUid)
1372 .setCallingPackage(targetPackage)
1373 .setResolvedType(resolvedType)
1374 .setResultTo(resultTo)
1375 .setResultWho(resultWho)
1376 .setRequestCode(requestCode)
1377 .setStartFlags(startFlags)
1378 .setActivityOptions(bOptions)
1379 .setMayWait(userId)
1380 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1381 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001382 // The target may well be in the background, which would normally prevent it
1383 // from starting an activity. Here we definitely want the start to succeed.
1384 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 .execute();
1386 } catch (SecurityException e) {
1387 // XXX need to figure out how to propagate to original app.
1388 // A SecurityException here is generally actually a fault of the original
1389 // calling activity (such as a fairly granting permissions), so propagate it
1390 // back to them.
1391 /*
1392 StringBuilder msg = new StringBuilder();
1393 msg.append("While launching");
1394 msg.append(intent.toString());
1395 msg.append(": ");
1396 msg.append(e.getMessage());
1397 */
1398 throw e;
1399 }
1400 }
1401
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1403 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1404 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1405 }
1406
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 @Override
1408 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1409 Intent intent, String resolvedType, IVoiceInteractionSession session,
1410 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1411 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001412 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 if (session == null || interactor == null) {
1414 throw new NullPointerException("null session or interactor");
1415 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001418 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .setCallingUid(callingUid)
1420 .setCallingPackage(callingPackage)
1421 .setResolvedType(resolvedType)
1422 .setVoiceSession(session)
1423 .setVoiceInteractor(interactor)
1424 .setStartFlags(startFlags)
1425 .setProfilerInfo(profilerInfo)
1426 .setActivityOptions(bOptions)
1427 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001428 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 .execute();
1430 }
1431
1432 @Override
1433 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1434 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1436 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(callingUid)
1440 .setCallingPackage(callingPackage)
1441 .setResolvedType(resolvedType)
1442 .setActivityOptions(bOptions)
1443 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001444 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 .execute();
1446 }
1447
1448 @Override
1449 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1450 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001451 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 final int callingPid = Binder.getCallingPid();
1453 final long origId = Binder.clearCallingIdentity();
1454 try {
1455 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001456 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1457 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458
1459 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001460 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1461 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1463 recentsUid, assistDataReceiver);
1464 }
1465 } finally {
1466 Binder.restoreCallingIdentity(origId);
1467 }
1468 }
1469
1470 @Override
1471 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001472 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 "startActivityFromRecents()");
1474
1475 final int callingPid = Binder.getCallingPid();
1476 final int callingUid = Binder.getCallingUid();
1477 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1478 final long origId = Binder.clearCallingIdentity();
1479 try {
1480 synchronized (mGlobalLock) {
1481 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1482 safeOptions);
1483 }
1484 } finally {
1485 Binder.restoreCallingIdentity(origId);
1486 }
1487 }
1488
1489 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001490 * Public API to check if the client is allowed to start an activity on specified display.
1491 *
1492 * If the target display is private or virtual, some restrictions will apply.
1493 *
1494 * @param displayId Target display id.
1495 * @param intent Intent used to launch the activity.
1496 * @param resolvedType The MIME type of the intent.
1497 * @param userId The id of the user for whom the call is made.
1498 * @return {@code true} if a call to start an activity on the target display should succeed and
1499 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1500 */
1501 @Override
1502 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1503 String resolvedType, int userId) {
1504 final int callingUid = Binder.getCallingUid();
1505 final int callingPid = Binder.getCallingPid();
1506 final long origId = Binder.clearCallingIdentity();
1507
1508 try {
1509 // Collect information about the target of the Intent.
1510 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1511 0 /* startFlags */, null /* profilerInfo */, userId,
1512 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1513 UserHandle.USER_NULL));
1514 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1515
1516 synchronized (mGlobalLock) {
1517 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1518 aInfo);
1519 }
1520 } finally {
1521 Binder.restoreCallingIdentity(origId);
1522 }
1523 }
1524
1525 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001526 * This is the internal entry point for handling Activity.finish().
1527 *
1528 * @param token The Binder token referencing the Activity we want to finish.
1529 * @param resultCode Result code, if any, from this Activity.
1530 * @param resultData Result data (Intent), if any, from this Activity.
1531 * @param finishTask Whether to finish the task associated with this Activity.
1532 *
1533 * @return Returns true if the activity successfully finished, or false if it is still running.
1534 */
1535 @Override
1536 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1537 int finishTask) {
1538 // Refuse possible leaked file descriptors
1539 if (resultData != null && resultData.hasFileDescriptors()) {
1540 throw new IllegalArgumentException("File descriptors passed in Intent");
1541 }
1542
1543 synchronized (mGlobalLock) {
1544 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1545 if (r == null) {
1546 return true;
1547 }
1548 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001549 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 ActivityRecord rootR = tr.getRootActivity();
1551 if (rootR == null) {
1552 Slog.w(TAG, "Finishing task with all activities already finished");
1553 }
1554 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1555 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001556 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 return false;
1558 }
1559
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001560 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1561 // We should consolidate.
1562 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001564 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 if (next != null) {
1566 // ask watcher if this is allowed
1567 boolean resumeOK = true;
1568 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001571 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 Watchdog.getInstance().setActivityController(null);
1573 }
1574
1575 if (!resumeOK) {
1576 Slog.i(TAG, "Not finishing activity because controller resumed");
1577 return false;
1578 }
1579 }
1580 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001581
1582 // note down that the process has finished an activity and is in background activity
1583 // starts grace period
1584 if (r.app != null) {
1585 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1586 }
1587
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 final long origId = Binder.clearCallingIdentity();
1589 try {
1590 boolean res;
1591 final boolean finishWithRootActivity =
1592 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1593 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1594 || (finishWithRootActivity && r == rootR)) {
1595 // If requested, remove the task that is associated to this activity only if it
1596 // was the root activity in the task. The result code and data is ignored
1597 // because we don't support returning them across task boundaries. Also, to
1598 // keep backwards compatibility we remove the task from recents when finishing
1599 // task with root activity.
1600 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1601 finishWithRootActivity, "finish-activity");
1602 if (!res) {
1603 Slog.i(TAG, "Removing task failed to finish activity");
1604 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001605 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001606 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001607 } else {
1608 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1609 resultData, "app-request", true);
1610 if (!res) {
1611 Slog.i(TAG, "Failed to finish by app-request");
1612 }
1613 }
1614 return res;
1615 } finally {
1616 Binder.restoreCallingIdentity(origId);
1617 }
1618 }
1619 }
1620
1621 @Override
1622 public boolean finishActivityAffinity(IBinder token) {
1623 synchronized (mGlobalLock) {
1624 final long origId = Binder.clearCallingIdentity();
1625 try {
1626 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1627 if (r == null) {
1628 return false;
1629 }
1630
1631 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1632 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001633 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001634 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 return false;
1636 }
1637 return task.getStack().finishActivityAffinityLocked(r);
1638 } finally {
1639 Binder.restoreCallingIdentity(origId);
1640 }
1641 }
1642 }
1643
1644 @Override
1645 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1646 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001647 try {
1648 WindowProcessController proc = null;
1649 synchronized (mGlobalLock) {
1650 ActivityStack stack = ActivityRecord.getStackLocked(token);
1651 if (stack == null) {
1652 return;
1653 }
1654 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1655 false /* fromTimeout */, false /* processPausingActivities */, config);
1656 if (r != null) {
1657 proc = r.app;
1658 }
1659 if (stopProfiling && proc != null) {
1660 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 }
1662 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001663 } finally {
1664 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 }
1667
1668 @Override
1669 public final void activityResumed(IBinder token) {
1670 final long origId = Binder.clearCallingIdentity();
1671 synchronized (mGlobalLock) {
1672 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001673 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001679 public final void activityTopResumedStateLost() {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1683 }
1684 Binder.restoreCallingIdentity(origId);
1685 }
1686
1687 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001688 public final void activityPaused(IBinder token) {
1689 final long origId = Binder.clearCallingIdentity();
1690 synchronized (mGlobalLock) {
1691 ActivityStack stack = ActivityRecord.getStackLocked(token);
1692 if (stack != null) {
1693 stack.activityPausedLocked(token, false);
1694 }
1695 }
1696 Binder.restoreCallingIdentity(origId);
1697 }
1698
1699 @Override
1700 public final void activityStopped(IBinder token, Bundle icicle,
1701 PersistableBundle persistentState, CharSequence description) {
1702 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1703
1704 // Refuse possible leaked file descriptors
1705 if (icicle != null && icicle.hasFileDescriptors()) {
1706 throw new IllegalArgumentException("File descriptors passed in Bundle");
1707 }
1708
1709 final long origId = Binder.clearCallingIdentity();
1710
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001711 String restartingName = null;
1712 int restartingUid = 0;
1713 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001715 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001717 if (r.attachedToProcess()
1718 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1719 // The activity was requested to restart from
1720 // {@link #restartActivityProcessIfVisible}.
1721 restartingName = r.app.mName;
1722 restartingUid = r.app.mUid;
1723 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 r.activityStoppedLocked(icicle, persistentState, description);
1725 }
1726 }
1727
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001728 if (restartingName != null) {
1729 // In order to let the foreground activity can be restarted with its saved state from
1730 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1731 // until the activity reports stopped with the state. And the activity record will be
1732 // kept because the record state is restarting, then the activity will be restarted
1733 // immediately if it is still the top one.
1734 mStackSupervisor.removeRestartTimeouts(r);
1735 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1736 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738
1739 Binder.restoreCallingIdentity(origId);
1740 }
1741
1742 @Override
1743 public final void activityDestroyed(IBinder token) {
1744 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1745 synchronized (mGlobalLock) {
1746 ActivityStack stack = ActivityRecord.getStackLocked(token);
1747 if (stack != null) {
1748 stack.activityDestroyedLocked(token, "activityDestroyed");
1749 }
1750 }
1751 }
1752
1753 @Override
1754 public final void activityRelaunched(IBinder token) {
1755 final long origId = Binder.clearCallingIdentity();
1756 synchronized (mGlobalLock) {
1757 mStackSupervisor.activityRelaunchedLocked(token);
1758 }
1759 Binder.restoreCallingIdentity(origId);
1760 }
1761
1762 public final void activitySlept(IBinder token) {
1763 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1764
1765 final long origId = Binder.clearCallingIdentity();
1766
1767 synchronized (mGlobalLock) {
1768 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1769 if (r != null) {
1770 mStackSupervisor.activitySleptLocked(r);
1771 }
1772 }
1773
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776
1777 @Override
1778 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1779 synchronized (mGlobalLock) {
1780 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1781 if (r == null) {
1782 return;
1783 }
1784 final long origId = Binder.clearCallingIdentity();
1785 try {
1786 r.setRequestedOrientation(requestedOrientation);
1787 } finally {
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790 }
1791 }
1792
1793 @Override
1794 public int getRequestedOrientation(IBinder token) {
1795 synchronized (mGlobalLock) {
1796 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1797 if (r == null) {
1798 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1799 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001800 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 }
1802 }
1803
1804 @Override
1805 public void setImmersive(IBinder token, boolean immersive) {
1806 synchronized (mGlobalLock) {
1807 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1808 if (r == null) {
1809 throw new IllegalArgumentException();
1810 }
1811 r.immersive = immersive;
1812
1813 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001814 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001815 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 }
1818 }
1819 }
1820
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001821 void applyUpdateLockStateLocked(ActivityRecord r) {
1822 // Modifications to the UpdateLock state are done on our handler, outside
1823 // the activity manager's locks. The new state is determined based on the
1824 // state *now* of the relevant activity record. The object is passed to
1825 // the handler solely for logging detail, not to be consulted/modified.
1826 final boolean nextState = r != null && r.immersive;
1827 mH.post(() -> {
1828 if (mUpdateLock.isHeld() != nextState) {
1829 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1830 "Applying new update lock state '" + nextState + "' for " + r);
1831 if (nextState) {
1832 mUpdateLock.acquire();
1833 } else {
1834 mUpdateLock.release();
1835 }
1836 }
1837 });
1838 }
1839
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 @Override
1841 public boolean isImmersive(IBinder token) {
1842 synchronized (mGlobalLock) {
1843 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1844 if (r == null) {
1845 throw new IllegalArgumentException();
1846 }
1847 return r.immersive;
1848 }
1849 }
1850
1851 @Override
1852 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001855 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 return (r != null) ? r.immersive : false;
1857 }
1858 }
1859
1860 @Override
1861 public void overridePendingTransition(IBinder token, String packageName,
1862 int enterAnim, int exitAnim) {
1863 synchronized (mGlobalLock) {
1864 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1865 if (self == null) {
1866 return;
1867 }
1868
1869 final long origId = Binder.clearCallingIdentity();
1870
1871 if (self.isState(
1872 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001873 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001874 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
1876
1877 Binder.restoreCallingIdentity(origId);
1878 }
1879 }
1880
1881 @Override
1882 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001883 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001885 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 if (r == null) {
1887 return ActivityManager.COMPAT_MODE_UNKNOWN;
1888 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001889 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 }
1891 }
1892
1893 @Override
1894 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001895 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001897 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001899 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001900 if (r == null) {
1901 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1902 return;
1903 }
1904 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001905 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908
1909 @Override
1910 public int getLaunchedFromUid(IBinder activityToken) {
1911 ActivityRecord srec;
1912 synchronized (mGlobalLock) {
1913 srec = ActivityRecord.forTokenLocked(activityToken);
1914 }
1915 if (srec == null) {
1916 return -1;
1917 }
1918 return srec.launchedFromUid;
1919 }
1920
1921 @Override
1922 public String getLaunchedFromPackage(IBinder activityToken) {
1923 ActivityRecord srec;
1924 synchronized (mGlobalLock) {
1925 srec = ActivityRecord.forTokenLocked(activityToken);
1926 }
1927 if (srec == null) {
1928 return null;
1929 }
1930 return srec.launchedFromPackage;
1931 }
1932
1933 @Override
1934 public boolean convertFromTranslucent(IBinder token) {
1935 final long origId = Binder.clearCallingIdentity();
1936 try {
1937 synchronized (mGlobalLock) {
1938 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1939 if (r == null) {
1940 return false;
1941 }
1942 final boolean translucentChanged = r.changeWindowTranslucency(true);
1943 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001944 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 return translucentChanged;
1948 }
1949 } finally {
1950 Binder.restoreCallingIdentity(origId);
1951 }
1952 }
1953
1954 @Override
1955 public boolean convertToTranslucent(IBinder token, Bundle options) {
1956 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1957 final long origId = Binder.clearCallingIdentity();
1958 try {
1959 synchronized (mGlobalLock) {
1960 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1961 if (r == null) {
1962 return false;
1963 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001964 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 int index = task.mActivities.lastIndexOf(r);
1966 if (index > 0) {
1967 ActivityRecord under = task.mActivities.get(index - 1);
1968 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1969 }
1970 final boolean translucentChanged = r.changeWindowTranslucency(false);
1971 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001972 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001973 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001974 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001975 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 return translucentChanged;
1977 }
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) {
2135
2136 synchronized (mGlobalLock) {
2137 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2138 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002139 return r.getActivityStack().navigateUpToLocked(
2140 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 }
2142 return false;
2143 }
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) {
2350
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 final int callingPid = Binder.getCallingPid();
2352 final int callingUid = Binder.getCallingUid();
2353 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 }
2359 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)) {
2372 boolean abort = !isBackgroundActivityStartsEnabled();
2373 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2374 if (abort) {
2375 return;
2376 }
2377 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002379 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 if (task == null) {
2381 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002382 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 return;
2384 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002385 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002387 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 return;
2389 }
2390 ActivityOptions realOptions = options != null
2391 ? options.getOptions(mStackSupervisor)
2392 : null;
2393 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2394 false /* forceNonResizable */);
2395
2396 final ActivityRecord topActivity = task.getTopActivity();
2397 if (topActivity != null) {
2398
2399 // We are reshowing a task, use a starting window to hide the initial draw delay
2400 // so the transition can start earlier.
2401 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2402 true /* taskSwitch */, fromRecents);
2403 }
2404 } finally {
2405 Binder.restoreCallingIdentity(origId);
2406 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 }
2408
Ricky Waiaca8a772019-04-04 16:01:06 +01002409 /**
2410 * Return true if callingUid is system, or packageName belongs to that callingUid.
2411 */
2412 boolean isSameApp(int callingUid, @Nullable String packageName) {
2413 try {
2414 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2415 if (packageName == null) {
2416 return false;
2417 }
2418 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2419 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2420 UserHandle.getUserId(callingUid));
2421 return UserHandle.isSameApp(callingUid, uid);
2422 }
2423 } catch (RemoteException e) {
2424 // Should not happen
2425 }
2426 return true;
2427 }
2428
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002429 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2430 int callingPid, int callingUid, String name) {
2431 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2432 return true;
2433 }
2434
2435 if (getRecentTasks().isCallerRecents(sourceUid)) {
2436 return true;
2437 }
2438
2439 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2440 if (perm == PackageManager.PERMISSION_GRANTED) {
2441 return true;
2442 }
2443 if (checkAllowAppSwitchUid(sourceUid)) {
2444 return true;
2445 }
2446
2447 // If the actual IPC caller is different from the logical source, then
2448 // also see if they are allowed to control app switches.
2449 if (callingUid != -1 && callingUid != sourceUid) {
2450 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2451 if (perm == PackageManager.PERMISSION_GRANTED) {
2452 return true;
2453 }
2454 if (checkAllowAppSwitchUid(callingUid)) {
2455 return true;
2456 }
2457 }
2458
2459 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2460 return false;
2461 }
2462
2463 private boolean checkAllowAppSwitchUid(int uid) {
2464 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2465 if (types != null) {
2466 for (int i = types.size() - 1; i >= 0; i--) {
2467 if (types.valueAt(i).intValue() == uid) {
2468 return true;
2469 }
2470 }
2471 }
2472 return false;
2473 }
2474
2475 @Override
2476 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2477 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2478 "setActivityController()");
2479 synchronized (mGlobalLock) {
2480 mController = controller;
2481 mControllerIsAMonkey = imAMonkey;
2482 Watchdog.getInstance().setActivityController(controller);
2483 }
2484 }
2485
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002486 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002487 synchronized (mGlobalLock) {
2488 return mController != null && mControllerIsAMonkey;
2489 }
2490 }
2491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002492 @Override
2493 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2494 synchronized (mGlobalLock) {
2495 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2496 }
2497 }
2498
2499 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002500 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2501 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2502 }
2503
2504 @Override
2505 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2506 @WindowConfiguration.ActivityType int ignoreActivityType,
2507 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2508 final int callingUid = Binder.getCallingUid();
2509 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2510
2511 synchronized (mGlobalLock) {
2512 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2513
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002516 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 ignoreWindowingMode, callingUid, allowed);
2518 }
2519
2520 return list;
2521 }
2522
2523 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2525 synchronized (mGlobalLock) {
2526 final long origId = Binder.clearCallingIdentity();
2527 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2528 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002529 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 }
2531 Binder.restoreCallingIdentity(origId);
2532 }
2533 }
2534
2535 @Override
2536 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002537 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 ActivityStack stack = ActivityRecord.getStackLocked(token);
2539 if (stack != null) {
2540 return stack.willActivityBeVisibleLocked(token);
2541 }
2542 return false;
2543 }
2544 }
2545
2546 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002547 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002548 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 synchronized (mGlobalLock) {
2550 final long ident = Binder.clearCallingIdentity();
2551 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002552 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 if (task == null) {
2554 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2555 return;
2556 }
2557
2558 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2559 + " to stackId=" + stackId + " toTop=" + toTop);
2560
Wale Ogunwaled32da472018-11-16 07:19:28 -08002561 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 if (stack == null) {
2563 throw new IllegalStateException(
2564 "moveTaskToStack: No stack for stackId=" + stackId);
2565 }
2566 if (!stack.isActivityTypeStandardOrUndefined()) {
2567 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2568 + taskId + " to stack " + stackId);
2569 }
2570 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2573 }
2574 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2575 "moveTaskToStack");
2576 } finally {
2577 Binder.restoreCallingIdentity(ident);
2578 }
2579 }
2580 }
2581
2582 @Override
2583 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2584 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002585 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586
2587 final long ident = Binder.clearCallingIdentity();
2588 try {
2589 synchronized (mGlobalLock) {
2590 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002591 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 if (stack == null) {
2593 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2594 return;
2595 }
2596 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2597 throw new IllegalArgumentException("Stack: " + stackId
2598 + " doesn't support animated resize.");
2599 }
2600 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2601 animationDuration, false /* fromFullscreen */);
2602 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604 if (stack == null) {
2605 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2606 return;
2607 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002608 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2610 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2611 }
2612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
wilsonshih5c4cf522019-01-25 09:03:47 +08002618 @Override
2619 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2620 int animationDuration) {
2621 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2622
2623 final long ident = Binder.clearCallingIdentity();
2624 try {
2625 synchronized (mGlobalLock) {
2626 if (xOffset == 0 && yOffset == 0) {
2627 return;
2628 }
2629 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2630 if (stack == null) {
2631 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2632 return;
2633 }
2634 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2635 throw new IllegalArgumentException("Stack: " + stackId
2636 + " doesn't support animated resize.");
2637 }
2638 final Rect destBounds = new Rect();
2639 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002640 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002641 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2642 return;
2643 }
2644 destBounds.offset(xOffset, yOffset);
2645 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2646 animationDuration, false /* fromFullscreen */);
2647 }
2648 } finally {
2649 Binder.restoreCallingIdentity(ident);
2650 }
2651 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002652 /**
2653 * Moves the specified task to the primary-split-screen stack.
2654 *
2655 * @param taskId Id of task to move.
2656 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2657 * exist already. See
2658 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2659 * and
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2661 * @param toTop If the task and stack should be moved to the top.
2662 * @param animate Whether we should play an animation for the moving the task.
2663 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2664 * stack. Pass {@code null} to use default bounds.
2665 * @param showRecents If the recents activity should be shown on the other side of the task
2666 * going into split-screen mode.
2667 */
2668 @Override
2669 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2670 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002671 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 "setTaskWindowingModeSplitScreenPrimary()");
2673 synchronized (mGlobalLock) {
2674 final long ident = Binder.clearCallingIdentity();
2675 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002676 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002677 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 if (task == null) {
2679 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2680 return false;
2681 }
2682 if (DEBUG_STACK) Slog.d(TAG_STACK,
2683 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2684 + " to createMode=" + createMode + " toTop=" + toTop);
2685 if (!task.isActivityTypeStandardOrUndefined()) {
2686 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2687 + " non-standard task " + taskId + " to split-screen windowing mode");
2688 }
2689
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002690 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 final int windowingMode = task.getWindowingMode();
2692 final ActivityStack stack = task.getStack();
2693 if (toTop) {
2694 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2695 }
2696 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002697 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2698 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 return windowingMode != task.getWindowingMode();
2700 } finally {
2701 Binder.restoreCallingIdentity(ident);
2702 }
2703 }
2704 }
2705
2706 /**
2707 * Removes stacks in the input windowing modes from the system if they are of activity type
2708 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2709 */
2710 @Override
2711 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 "removeStacksInWindowingModes()");
2714
2715 synchronized (mGlobalLock) {
2716 final long ident = Binder.clearCallingIdentity();
2717 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002718 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 } finally {
2720 Binder.restoreCallingIdentity(ident);
2721 }
2722 }
2723 }
2724
2725 @Override
2726 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002727 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002728 "removeStacksWithActivityTypes()");
2729
2730 synchronized (mGlobalLock) {
2731 final long ident = Binder.clearCallingIdentity();
2732 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002733 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 } finally {
2735 Binder.restoreCallingIdentity(ident);
2736 }
2737 }
2738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739
2740 @Override
2741 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2742 int userId) {
2743 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2745 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002747 final boolean detailed = checkGetTasksPermission(
2748 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2749 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 == PackageManager.PERMISSION_GRANTED;
2751
2752 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002753 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 callingUid);
2755 }
2756 }
2757
2758 @Override
2759 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 long ident = Binder.clearCallingIdentity();
2762 try {
2763 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002764 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 }
2766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770
2771 @Override
2772 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002777 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 @Override
2785 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 final long callingUid = Binder.getCallingUid();
2788 final long origId = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
2791 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2794 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(origId);
2798 }
2799 }
2800
2801 @Override
2802 public void startLockTaskModeByToken(IBinder token) {
2803 synchronized (mGlobalLock) {
2804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2805 if (r == null) {
2806 return;
2807 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002808 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 }
2811
2812 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002813 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 // This makes inner call to look as if it was initiated by system.
2816 long ident = Binder.clearCallingIdentity();
2817 try {
2818 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002819 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002820 MATCH_TASK_IN_STACKS_ONLY);
2821 if (task == null) {
2822 return;
2823 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824
2825 // When starting lock task mode the stack must be in front and focused
2826 task.getStack().moveToFront("startSystemLockTaskMode");
2827 startLockTaskModeLocked(task, true /* isSystemCaller */);
2828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public void stopLockTaskModeByToken(IBinder token) {
2836 synchronized (mGlobalLock) {
2837 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2838 if (r == null) {
2839 return;
2840 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002841 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 }
2844
2845 /**
2846 * This API should be called by SystemUI only when user perform certain action to dismiss
2847 * lock task mode. We should only dismiss pinned lock task mode in this case.
2848 */
2849 @Override
2850 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2853 }
2854
2855 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2856 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2857 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2858 return;
2859 }
2860
Wale Ogunwaled32da472018-11-16 07:19:28 -08002861 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 if (stack == null || task != stack.topTask()) {
2863 throw new IllegalArgumentException("Invalid task, not in foreground");
2864 }
2865
2866 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2867 // system or a specific app.
2868 // * System-initiated requests will only start the pinned mode (screen pinning)
2869 // * App-initiated requests
2870 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2871 // - will start the pinned mode, otherwise
2872 final int callingUid = Binder.getCallingUid();
2873 long ident = Binder.clearCallingIdentity();
2874 try {
2875 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002876 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002878 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883
2884 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2885 final int callingUid = Binder.getCallingUid();
2886 long ident = Binder.clearCallingIdentity();
2887 try {
2888 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002889 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 }
2891 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2892 // task and jumping straight into a call in the case of emergency call back.
2893 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2894 if (tm != null) {
2895 tm.showInCallScreen(false);
2896 }
2897 } finally {
2898 Binder.restoreCallingIdentity(ident);
2899 }
2900 }
2901
2902 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002903 public void updateLockTaskPackages(int userId, String[] packages) {
2904 final int callingUid = Binder.getCallingUid();
2905 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2906 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2907 "updateLockTaskPackages()");
2908 }
2909 synchronized (this) {
2910 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2911 + Arrays.toString(packages));
2912 getLockTaskController().updateLockTaskPackages(userId, packages);
2913 }
2914 }
2915
2916 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 public boolean isInLockTaskMode() {
2918 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2919 }
2920
2921 @Override
2922 public int getLockTaskModeState() {
2923 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002924 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 }
2926 }
2927
2928 @Override
2929 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2932 if (r != null) {
2933 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002934 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002936 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939 }
2940
2941 @Override
2942 public Bundle getActivityOptions(IBinder token) {
2943 final long origId = Binder.clearCallingIdentity();
2944 try {
2945 synchronized (mGlobalLock) {
2946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2947 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002948 final ActivityOptions activityOptions = r.takeOptionsLocked(
2949 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 return activityOptions == null ? null : activityOptions.toBundle();
2951 }
2952 return null;
2953 }
2954 } finally {
2955 Binder.restoreCallingIdentity(origId);
2956 }
2957 }
2958
2959 @Override
2960 public List<IBinder> getAppTasks(String callingPackage) {
2961 int callingUid = Binder.getCallingUid();
2962 long ident = Binder.clearCallingIdentity();
2963 try {
2964 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002965 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 }
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
2970 }
2971
2972 @Override
2973 public void finishVoiceTask(IVoiceInteractionSession session) {
2974 synchronized (mGlobalLock) {
2975 final long origId = Binder.clearCallingIdentity();
2976 try {
2977 // TODO: VI Consider treating local voice interactions and voice tasks
2978 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002979 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 } finally {
2981 Binder.restoreCallingIdentity(origId);
2982 }
2983 }
2984
2985 }
2986
2987 @Override
2988 public boolean isTopOfTask(IBinder token) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002991 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void notifyLaunchTaskBehindComplete(IBinder token) {
2997 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2998 }
2999
3000 @Override
3001 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003002 mH.post(() -> {
3003 synchronized (mGlobalLock) {
3004 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003005 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 } catch (RemoteException e) {
3009 }
3010 }
3011 }
3012
3013 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015
3016 /** Called from an app when assist data is ready. */
3017 @Override
3018 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3019 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003020 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 synchronized (pae) {
3022 pae.result = extras;
3023 pae.structure = structure;
3024 pae.content = content;
3025 if (referrer != null) {
3026 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3027 }
3028 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003029 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003030 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3031 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 structure.setHomeActivity(pae.isHome);
3033 }
3034 pae.haveResult = true;
3035 pae.notifyAll();
3036 if (pae.intent == null && pae.receiver == null) {
3037 // Caller is just waiting for the result.
3038 return;
3039 }
3040 }
3041 // We are now ready to launch the assist activity.
3042 IAssistDataReceiver sendReceiver = null;
3043 Bundle sendBundle = null;
3044 synchronized (mGlobalLock) {
3045 buildAssistBundleLocked(pae, extras);
3046 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003047 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 if (!exists) {
3049 // Timed out.
3050 return;
3051 }
3052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003053 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 // Caller wants result sent back to them.
3055 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003056 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3057 pae.activity.getTaskRecord().taskId);
3058 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3059 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3061 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3062 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3063 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3064 }
3065 }
3066 if (sendReceiver != null) {
3067 try {
3068 sendReceiver.onHandleAssistData(sendBundle);
3069 } catch (RemoteException e) {
3070 }
3071 return;
3072 }
3073
3074 final long ident = Binder.clearCallingIdentity();
3075 try {
3076 if (TextUtils.equals(pae.intent.getAction(),
3077 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3078 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003079
3080 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 } else {
3082 pae.intent.replaceExtras(pae.extras);
3083 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3084 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3085 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003086 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087
3088 try {
3089 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3090 } catch (ActivityNotFoundException e) {
3091 Slog.w(TAG, "No activity to handle assist action.", e);
3092 }
3093 }
3094 } finally {
3095 Binder.restoreCallingIdentity(ident);
3096 }
3097 }
3098
Marvin Ramin830d4e32019-03-12 13:16:58 +01003099 /**
3100 * Workaround for historical API which starts the Assist service with a non-foreground
3101 * {@code startService()} call.
3102 */
3103 private void startVoiceInteractionServiceAsUser(
3104 Intent intent, int userHandle, String reason) {
3105 // Resolve the intent to find out which package we need to whitelist.
3106 ResolveInfo resolveInfo =
3107 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3108 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3109 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3110 return;
3111 }
3112 intent.setPackage(resolveInfo.serviceInfo.packageName);
3113
3114 // Whitelist background services temporarily.
3115 LocalServices.getService(DeviceIdleController.LocalService.class)
3116 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3117 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3118
3119 // Finally, try to start the service.
3120 try {
3121 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3122 } catch (RuntimeException e) {
3123 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3124 }
3125 }
3126
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 @Override
3128 public int addAppTask(IBinder activityToken, Intent intent,
3129 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3130 final int callingUid = Binder.getCallingUid();
3131 final long callingIdent = Binder.clearCallingIdentity();
3132
3133 try {
3134 synchronized (mGlobalLock) {
3135 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3136 if (r == null) {
3137 throw new IllegalArgumentException("Activity does not exist; token="
3138 + activityToken);
3139 }
3140 ComponentName comp = intent.getComponent();
3141 if (comp == null) {
3142 throw new IllegalArgumentException("Intent " + intent
3143 + " must specify explicit component");
3144 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 if (thumbnail.getWidth() != mThumbnailWidth
3146 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 throw new IllegalArgumentException("Bad thumbnail size: got "
3148 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003149 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 }
3151 if (intent.getSelector() != null) {
3152 intent.setSelector(null);
3153 }
3154 if (intent.getSourceBounds() != null) {
3155 intent.setSourceBounds(null);
3156 }
3157 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3158 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3159 // The caller has added this as an auto-remove task... that makes no
3160 // sense, so turn off auto-remove.
3161 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3162 }
3163 }
3164 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3165 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3166 if (ainfo.applicationInfo.uid != callingUid) {
3167 throw new SecurityException(
3168 "Can't add task for another application: target uid="
3169 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3170 }
3171
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003172 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003174 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003176 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 // The app has too many tasks already and we can't add any more
3178 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3179 return INVALID_TASK_ID;
3180 }
3181 task.lastTaskDescription.copyFrom(description);
3182
3183 // TODO: Send the thumbnail to WM to store it.
3184
3185 return task.taskId;
3186 }
3187 } finally {
3188 Binder.restoreCallingIdentity(callingIdent);
3189 }
3190 }
3191
3192 @Override
3193 public Point getAppTaskThumbnailSize() {
3194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 }
3198
3199 @Override
3200 public void setTaskResizeable(int taskId, int resizeableMode) {
3201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003202 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3204 if (task == null) {
3205 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3206 return;
3207 }
3208 task.setResizeMode(resizeableMode);
3209 }
3210 }
3211
3212 @Override
3213 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003214 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 long ident = Binder.clearCallingIdentity();
3216 try {
3217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003219 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 if (task == null) {
3221 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3222 return;
3223 }
3224 // Place the task in the right stack if it isn't there already based on
3225 // the requested bounds.
3226 // The stack transition logic is:
3227 // - a null bounds on a freeform task moves that task to fullscreen
3228 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3229 // that task to freeform
3230 // - otherwise the task is not moved
3231 ActivityStack stack = task.getStack();
3232 if (!task.getWindowConfiguration().canResizeTask()) {
3233 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3234 }
3235 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3236 stack = stack.getDisplay().getOrCreateStack(
3237 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3238 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3239 stack = stack.getDisplay().getOrCreateStack(
3240 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3241 }
3242
3243 // Reparent the task to the right stack if necessary
3244 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3245 if (stack != task.getStack()) {
3246 // Defer resume until the task is resized below
3247 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3248 DEFER_RESUME, "resizeTask");
3249 preserveWindow = false;
3250 }
3251
3252 // After reparenting (which only resizes the task to the stack bounds), resize the
3253 // task to the actual bounds provided
3254 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3255 }
3256 } finally {
3257 Binder.restoreCallingIdentity(ident);
3258 }
3259 }
3260
3261 @Override
3262 public boolean releaseActivityInstance(IBinder token) {
3263 synchronized (mGlobalLock) {
3264 final long origId = Binder.clearCallingIdentity();
3265 try {
3266 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3267 if (r == null) {
3268 return false;
3269 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003270 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 } finally {
3272 Binder.restoreCallingIdentity(origId);
3273 }
3274 }
3275 }
3276
3277 @Override
3278 public void releaseSomeActivities(IApplicationThread appInt) {
3279 synchronized (mGlobalLock) {
3280 final long origId = Binder.clearCallingIdentity();
3281 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003282 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003283 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 } finally {
3285 Binder.restoreCallingIdentity(origId);
3286 }
3287 }
3288 }
3289
3290 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003291 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 != PackageManager.PERMISSION_GRANTED) {
3294 throw new SecurityException("Requires permission "
3295 + android.Manifest.permission.DEVICE_POWER);
3296 }
3297
3298 synchronized (mGlobalLock) {
3299 long ident = Binder.clearCallingIdentity();
3300 if (mKeyguardShown != keyguardShowing) {
3301 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003302 final Message msg = PooledLambda.obtainMessage(
3303 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3304 keyguardShowing);
3305 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 }
3307 try {
wilsonshih177261f2019-02-22 12:02:18 +08003308 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 } finally {
3310 Binder.restoreCallingIdentity(ident);
3311 }
3312 }
3313
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mH.post(() -> {
3315 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3316 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3317 }
3318 });
3319 }
3320
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003321 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003322 mH.post(() -> {
3323 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3324 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3325 }
3326 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 }
3328
3329 @Override
3330 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3332 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333
3334 final File passedIconFile = new File(filePath);
3335 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3336 passedIconFile.getName());
3337 if (!legitIconFile.getPath().equals(filePath)
3338 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3339 throw new IllegalArgumentException("Bad file path: " + filePath
3340 + " passed for userId " + userId);
3341 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003342 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 }
3344
3345 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003346 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3348 final ActivityOptions activityOptions = safeOptions != null
3349 ? safeOptions.getOptions(mStackSupervisor)
3350 : null;
3351 if (activityOptions == null
3352 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3353 || activityOptions.getCustomInPlaceResId() == 0) {
3354 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3355 "with valid animation");
3356 }
lumark588a3e82018-07-20 18:53:54 +08003357 // Get top display of front most application.
3358 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3359 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003360 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3361 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3362 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003363 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003364 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003365 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
3367
3368 @Override
3369 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 synchronized (mGlobalLock) {
3372 final long ident = Binder.clearCallingIdentity();
3373 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003374 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 if (stack == null) {
3376 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3377 return;
3378 }
3379 if (!stack.isActivityTypeStandardOrUndefined()) {
3380 throw new IllegalArgumentException(
3381 "Removing non-standard stack is not allowed.");
3382 }
3383 mStackSupervisor.removeStack(stack);
3384 } finally {
3385 Binder.restoreCallingIdentity(ident);
3386 }
3387 }
3388 }
3389
3390 @Override
3391 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003392 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393
3394 synchronized (mGlobalLock) {
3395 final long ident = Binder.clearCallingIdentity();
3396 try {
3397 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3398 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003399 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
3404 }
3405
3406 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003407 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 synchronized (mGlobalLock) {
3409 long ident = Binder.clearCallingIdentity();
3410 try {
3411 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3412 if (r == null) {
3413 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003414 "toggleFreeformWindowingMode: No activity record matching token="
3415 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 }
3417
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003418 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003419 if (stack == null) {
3420 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3421 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423
Yunfan Chend967af82019-01-17 18:30:18 +09003424 if (!stack.inFreeformWindowingMode()
3425 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3426 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3427 + "toggle between fullscreen and freeform.");
3428 }
3429
3430 if (stack.inFreeformWindowingMode()) {
3431 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003432 } else if (stack.getParent().inFreeformWindowingMode()) {
3433 // If the window is on a freeform display, set it to undefined. It will be
3434 // resolved to freeform and it can adjust windowing mode when the display mode
3435 // changes in runtime.
3436 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003437 } else {
3438 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3439 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 } finally {
3441 Binder.restoreCallingIdentity(ident);
3442 }
3443 }
3444 }
3445
3446 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3447 @Override
3448 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003451 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 }
3453
3454 /** Unregister a task stack listener so that it stops receiving callbacks. */
3455 @Override
3456 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003459 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460 }
3461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 @Override
3463 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3464 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3465 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3466 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3467 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3468 }
3469
3470 @Override
3471 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3472 IBinder activityToken, int flags) {
3473 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3474 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3475 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3476 }
3477
3478 @Override
3479 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3480 Bundle args) {
3481 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3482 true /* focused */, true /* newSessionId */, userHandle, args,
3483 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3484 }
3485
3486 @Override
3487 public Bundle getAssistContextExtras(int requestType) {
3488 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3489 null, null, true /* focused */, true /* newSessionId */,
3490 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3491 if (pae == null) {
3492 return null;
3493 }
3494 synchronized (pae) {
3495 while (!pae.haveResult) {
3496 try {
3497 pae.wait();
3498 } catch (InterruptedException e) {
3499 }
3500 }
3501 }
3502 synchronized (mGlobalLock) {
3503 buildAssistBundleLocked(pae, pae.result);
3504 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003505 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 }
3507 return pae.extras;
3508 }
3509
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003510 /**
3511 * Binder IPC calls go through the public entry point.
3512 * This can be called with or without the global lock held.
3513 */
3514 private static int checkCallingPermission(String permission) {
3515 return checkPermission(
3516 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3517 }
3518
3519 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003520 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3522 mAmInternal.enforceCallingPermission(permission, func);
3523 }
3524 }
3525
3526 @VisibleForTesting
3527 int checkGetTasksPermission(String permission, int pid, int uid) {
3528 return checkPermission(permission, pid, uid);
3529 }
3530
3531 static int checkPermission(String permission, int pid, int uid) {
3532 if (permission == null) {
3533 return PackageManager.PERMISSION_DENIED;
3534 }
3535 return checkComponentPermission(permission, pid, uid, -1, true);
3536 }
3537
Wale Ogunwale214f3482018-10-04 11:00:47 -07003538 public static int checkComponentPermission(String permission, int pid, int uid,
3539 int owningUid, boolean exported) {
3540 return ActivityManagerService.checkComponentPermission(
3541 permission, pid, uid, owningUid, exported);
3542 }
3543
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003544 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3545 if (getRecentTasks().isCallerRecents(callingUid)) {
3546 // Always allow the recents component to get tasks
3547 return true;
3548 }
3549
3550 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3551 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3552 if (!allowed) {
3553 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3554 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3555 // Temporary compatibility: some existing apps on the system image may
3556 // still be requesting the old permission and not switched to the new
3557 // one; if so, we'll still allow them full access. This means we need
3558 // to see if they are holding the old permission and are a system app.
3559 try {
3560 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3561 allowed = true;
3562 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3563 + " is using old GET_TASKS but privileged; allowing");
3564 }
3565 } catch (RemoteException e) {
3566 }
3567 }
3568 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3569 + " does not hold REAL_GET_TASKS; limiting output");
3570 }
3571 return allowed;
3572 }
3573
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3575 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3576 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3577 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 "enqueueAssistContext()");
3580
3581 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003582 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 if (activity == null) {
3584 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3585 return null;
3586 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003587 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3589 return null;
3590 }
3591 if (focused) {
3592 if (activityToken != null) {
3593 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3594 if (activity != caller) {
3595 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3596 + " is not current top " + activity);
3597 return null;
3598 }
3599 }
3600 } else {
3601 activity = ActivityRecord.forTokenLocked(activityToken);
3602 if (activity == null) {
3603 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3604 + " couldn't be found");
3605 return null;
3606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3609 return null;
3610 }
3611 }
3612
3613 PendingAssistExtras pae;
3614 Bundle extras = new Bundle();
3615 if (args != null) {
3616 extras.putAll(args);
3617 }
3618 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003619 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620
3621 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3622 userHandle);
3623 pae.isHome = activity.isActivityTypeHome();
3624
3625 // Increment the sessionId if necessary
3626 if (newSessionId) {
3627 mViSessionId++;
3628 }
3629 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003630 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3631 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003633 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 } catch (RemoteException e) {
3635 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3636 return null;
3637 }
3638 return pae;
3639 }
3640 }
3641
3642 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3643 if (result != null) {
3644 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3645 }
3646 if (pae.hint != null) {
3647 pae.extras.putBoolean(pae.hint, true);
3648 }
3649 }
3650
3651 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3652 IAssistDataReceiver receiver;
3653 synchronized (mGlobalLock) {
3654 mPendingAssistExtras.remove(pae);
3655 receiver = pae.receiver;
3656 }
3657 if (receiver != null) {
3658 // Caller wants result sent back to them.
3659 Bundle sendBundle = new Bundle();
3660 // At least return the receiver extras
3661 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3662 try {
3663 pae.receiver.onHandleAssistData(sendBundle);
3664 } catch (RemoteException e) {
3665 }
3666 }
3667 }
3668
3669 public class PendingAssistExtras extends Binder implements Runnable {
3670 public final ActivityRecord activity;
3671 public boolean isHome;
3672 public final Bundle extras;
3673 public final Intent intent;
3674 public final String hint;
3675 public final IAssistDataReceiver receiver;
3676 public final int userHandle;
3677 public boolean haveResult = false;
3678 public Bundle result = null;
3679 public AssistStructure structure = null;
3680 public AssistContent content = null;
3681 public Bundle receiverExtras;
3682
3683 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3684 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3685 int _userHandle) {
3686 activity = _activity;
3687 extras = _extras;
3688 intent = _intent;
3689 hint = _hint;
3690 receiver = _receiver;
3691 receiverExtras = _receiverExtras;
3692 userHandle = _userHandle;
3693 }
3694
3695 @Override
3696 public void run() {
3697 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3698 synchronized (this) {
3699 haveResult = true;
3700 notifyAll();
3701 }
3702 pendingAssistExtrasTimedOut(this);
3703 }
3704 }
3705
3706 @Override
3707 public boolean isAssistDataAllowedOnCurrentActivity() {
3708 int userId;
3709 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003710 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3712 return false;
3713 }
3714
3715 final ActivityRecord activity = focusedStack.getTopActivity();
3716 if (activity == null) {
3717 return false;
3718 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003719 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003720 }
3721 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3722 }
3723
3724 @Override
3725 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3726 long ident = Binder.clearCallingIdentity();
3727 try {
3728 synchronized (mGlobalLock) {
3729 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003730 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 if (top != caller) {
3732 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3733 + " is not current top " + top);
3734 return false;
3735 }
3736 if (!top.nowVisible) {
3737 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3738 + " is not visible");
3739 return false;
3740 }
3741 }
3742 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3743 token);
3744 } finally {
3745 Binder.restoreCallingIdentity(ident);
3746 }
3747 }
3748
3749 @Override
3750 public boolean isRootVoiceInteraction(IBinder token) {
3751 synchronized (mGlobalLock) {
3752 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3753 if (r == null) {
3754 return false;
3755 }
3756 return r.rootVoiceInteraction;
3757 }
3758 }
3759
Wale Ogunwalef6733932018-06-27 05:14:34 -07003760 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3761 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3762 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3763 if (activityToCallback == null) return;
3764 activityToCallback.setVoiceSessionLocked(voiceSession);
3765
3766 // Inform the activity
3767 try {
3768 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3769 voiceInteractor);
3770 long token = Binder.clearCallingIdentity();
3771 try {
3772 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3773 } finally {
3774 Binder.restoreCallingIdentity(token);
3775 }
3776 // TODO: VI Should we cache the activity so that it's easier to find later
3777 // rather than scan through all the stacks and activities?
3778 } catch (RemoteException re) {
3779 activityToCallback.clearVoiceSessionLocked();
3780 // TODO: VI Should this terminate the voice session?
3781 }
3782 }
3783
3784 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3785 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3786 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3787 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3788 boolean wasRunningVoice = mRunningVoice != null;
3789 mRunningVoice = session;
3790 if (!wasRunningVoice) {
3791 mVoiceWakeLock.acquire();
3792 updateSleepIfNeededLocked();
3793 }
3794 }
3795 }
3796
3797 void finishRunningVoiceLocked() {
3798 if (mRunningVoice != null) {
3799 mRunningVoice = null;
3800 mVoiceWakeLock.release();
3801 updateSleepIfNeededLocked();
3802 }
3803 }
3804
3805 @Override
3806 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3807 synchronized (mGlobalLock) {
3808 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3809 if (keepAwake) {
3810 mVoiceWakeLock.acquire();
3811 } else {
3812 mVoiceWakeLock.release();
3813 }
3814 }
3815 }
3816 }
3817
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 @Override
3819 public ComponentName getActivityClassForToken(IBinder token) {
3820 synchronized (mGlobalLock) {
3821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3822 if (r == null) {
3823 return null;
3824 }
3825 return r.intent.getComponent();
3826 }
3827 }
3828
3829 @Override
3830 public String getPackageForToken(IBinder token) {
3831 synchronized (mGlobalLock) {
3832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3833 if (r == null) {
3834 return null;
3835 }
3836 return r.packageName;
3837 }
3838 }
3839
3840 @Override
3841 public void showLockTaskEscapeMessage(IBinder token) {
3842 synchronized (mGlobalLock) {
3843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3844 if (r == null) {
3845 return;
3846 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003847 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 }
3849 }
3850
3851 @Override
3852 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003853 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 final long token = Binder.clearCallingIdentity();
3855 try {
3856 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003857 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 }
3859 } finally {
3860 Binder.restoreCallingIdentity(token);
3861 }
3862 }
3863
3864 /**
3865 * Try to place task to provided position. The final position might be different depending on
3866 * current user and stacks state. The task will be moved to target stack if it's currently in
3867 * different stack.
3868 */
3869 @Override
3870 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003871 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 synchronized (mGlobalLock) {
3873 long ident = Binder.clearCallingIdentity();
3874 try {
3875 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3876 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003877 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 if (task == null) {
3879 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3880 + taskId);
3881 }
3882
Wale Ogunwaled32da472018-11-16 07:19:28 -08003883 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884
3885 if (stack == null) {
3886 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3887 + stackId);
3888 }
3889 if (!stack.isActivityTypeStandardOrUndefined()) {
3890 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3891 + " the position of task " + taskId + " in/to non-standard stack");
3892 }
3893
3894 // TODO: Have the callers of this API call a separate reparent method if that is
3895 // what they intended to do vs. having this method also do reparenting.
3896 if (task.getStack() == stack) {
3897 // Change position in current stack.
3898 stack.positionChildAt(task, position);
3899 } else {
3900 // Reparent to new stack.
3901 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3902 !DEFER_RESUME, "positionTaskInStack");
3903 }
3904 } finally {
3905 Binder.restoreCallingIdentity(ident);
3906 }
3907 }
3908 }
3909
3910 @Override
3911 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3912 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3913 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3914 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3915 synchronized (mGlobalLock) {
3916 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3917 if (record == null) {
3918 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3919 + "found for: " + token);
3920 }
3921 record.setSizeConfigurations(horizontalSizeConfiguration,
3922 verticalSizeConfigurations, smallestSizeConfigurations);
3923 }
3924 }
3925
3926 /**
3927 * Dismisses split-screen multi-window mode.
3928 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3929 */
3930 @Override
3931 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003932 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3934 final long ident = Binder.clearCallingIdentity();
3935 try {
3936 synchronized (mGlobalLock) {
3937 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003938 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 if (stack == null) {
3940 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3941 return;
3942 }
3943
3944 if (toTop) {
3945 // Caller wants the current split-screen primary stack to be the top stack after
3946 // it goes fullscreen, so move it to the front.
3947 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003948 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003949 // In this case the current split-screen primary stack shouldn't be the top
3950 // stack after it goes fullscreen, but it current has focus, so we move the
3951 // focus to the top-most split-screen secondary stack next to it.
3952 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3953 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3954 if (otherStack != null) {
3955 otherStack.moveToFront("dismissSplitScreenMode_other");
3956 }
3957 }
3958
Evan Rosky10475742018-09-05 19:02:48 -07003959 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 }
3961 } finally {
3962 Binder.restoreCallingIdentity(ident);
3963 }
3964 }
3965
3966 /**
3967 * Dismisses Pip
3968 * @param animate True if the dismissal should be animated.
3969 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3970 * default animation duration should be used.
3971 */
3972 @Override
3973 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003974 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 final long ident = Binder.clearCallingIdentity();
3976 try {
3977 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003978 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003979 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 if (stack == null) {
3981 Slog.w(TAG, "dismissPip: pinned stack not found.");
3982 return;
3983 }
3984 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3985 throw new IllegalArgumentException("Stack: " + stack
3986 + " doesn't support animated resize.");
3987 }
3988 if (animate) {
3989 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3990 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3991 } else {
3992 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3993 }
3994 }
3995 } finally {
3996 Binder.restoreCallingIdentity(ident);
3997 }
3998 }
3999
4000 @Override
4001 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004002 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 synchronized (mGlobalLock) {
4004 mSuppressResizeConfigChanges = suppress;
4005 }
4006 }
4007
4008 /**
4009 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4010 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4011 * activity and clearing the task at the same time.
4012 */
4013 @Override
4014 // TODO: API should just be about changing windowing modes...
4015 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004016 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 "moveTasksToFullscreenStack()");
4018 synchronized (mGlobalLock) {
4019 final long origId = Binder.clearCallingIdentity();
4020 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004021 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 if (stack != null){
4023 if (!stack.isActivityTypeStandardOrUndefined()) {
4024 throw new IllegalArgumentException(
4025 "You can't move tasks from non-standard stacks.");
4026 }
4027 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4028 }
4029 } finally {
4030 Binder.restoreCallingIdentity(origId);
4031 }
4032 }
4033 }
4034
4035 /**
4036 * Moves the top activity in the input stackId to the pinned stack.
4037 *
4038 * @param stackId Id of stack to move the top activity to pinned stack.
4039 * @param bounds Bounds to use for pinned stack.
4040 *
4041 * @return True if the top activity of the input stack was successfully moved to the pinned
4042 * stack.
4043 */
4044 @Override
4045 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 "moveTopActivityToPinnedStack()");
4048 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004049 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4051 + "Device doesn't support picture-in-picture mode");
4052 }
4053
4054 long ident = Binder.clearCallingIdentity();
4055 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004056 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 } finally {
4058 Binder.restoreCallingIdentity(ident);
4059 }
4060 }
4061 }
4062
4063 @Override
4064 public boolean isInMultiWindowMode(IBinder token) {
4065 final long origId = Binder.clearCallingIdentity();
4066 try {
4067 synchronized (mGlobalLock) {
4068 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4069 if (r == null) {
4070 return false;
4071 }
4072 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4073 return r.inMultiWindowMode();
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(origId);
4077 }
4078 }
4079
4080 @Override
4081 public boolean isInPictureInPictureMode(IBinder token) {
4082 final long origId = Binder.clearCallingIdentity();
4083 try {
4084 synchronized (mGlobalLock) {
4085 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4086 }
4087 } finally {
4088 Binder.restoreCallingIdentity(origId);
4089 }
4090 }
4091
4092 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004093 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4094 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 return false;
4096 }
4097
4098 // If we are animating to fullscreen then we have already dispatched the PIP mode
4099 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004100 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4101 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102 }
4103
4104 @Override
4105 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4106 final long origId = Binder.clearCallingIdentity();
4107 try {
4108 synchronized (mGlobalLock) {
4109 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4110 "enterPictureInPictureMode", token, params);
4111
4112 // If the activity is already in picture in picture mode, then just return early
4113 if (isInPictureInPictureMode(r)) {
4114 return true;
4115 }
4116
4117 // Activity supports picture-in-picture, now check that we can enter PiP at this
4118 // point, if it is
4119 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4120 false /* beforeStopping */)) {
4121 return false;
4122 }
4123
4124 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004125 synchronized (mGlobalLock) {
4126 // Only update the saved args from the args that are set
4127 r.pictureInPictureArgs.copyOnlySet(params);
4128 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4129 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4130 // Adjust the source bounds by the insets for the transition down
4131 final Rect sourceBounds = new Rect(
4132 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004133 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004134 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004135 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004136 stack.setPictureInPictureAspectRatio(aspectRatio);
4137 stack.setPictureInPictureActions(actions);
4138 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4139 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4140 logPictureInPictureArgs(params);
4141 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 };
4143
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004144 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145 // If the keyguard is showing or occluded, then try and dismiss it before
4146 // entering picture-in-picture (this will prompt the user to authenticate if the
4147 // device is currently locked).
4148 dismissKeyguard(token, new KeyguardDismissCallback() {
4149 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 public void onDismissSucceeded() {
4151 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 }
4153 }, null /* message */);
4154 } else {
4155 // Enter picture in picture immediately otherwise
4156 enterPipRunnable.run();
4157 }
4158 return true;
4159 }
4160 } finally {
4161 Binder.restoreCallingIdentity(origId);
4162 }
4163 }
4164
4165 @Override
4166 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4167 final long origId = Binder.clearCallingIdentity();
4168 try {
4169 synchronized (mGlobalLock) {
4170 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4171 "setPictureInPictureParams", token, params);
4172
4173 // Only update the saved args from the args that are set
4174 r.pictureInPictureArgs.copyOnlySet(params);
4175 if (r.inPinnedWindowingMode()) {
4176 // If the activity is already in picture-in-picture, update the pinned stack now
4177 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4178 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004179 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 if (!stack.isAnimatingBoundsToFullscreen()) {
4181 stack.setPictureInPictureAspectRatio(
4182 r.pictureInPictureArgs.getAspectRatio());
4183 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4184 }
4185 }
4186 logPictureInPictureArgs(params);
4187 }
4188 } finally {
4189 Binder.restoreCallingIdentity(origId);
4190 }
4191 }
4192
4193 @Override
4194 public int getMaxNumPictureInPictureActions(IBinder token) {
4195 // Currently, this is a static constant, but later, we may change this to be dependent on
4196 // the context of the activity
4197 return 3;
4198 }
4199
4200 private void logPictureInPictureArgs(PictureInPictureParams params) {
4201 if (params.hasSetActions()) {
4202 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4203 params.getActions().size());
4204 }
4205 if (params.hasSetAspectRatio()) {
4206 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4207 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4208 MetricsLogger.action(lm);
4209 }
4210 }
4211
4212 /**
4213 * Checks the state of the system and the activity associated with the given {@param token} to
4214 * verify that picture-in-picture is supported for that activity.
4215 *
4216 * @return the activity record for the given {@param token} if all the checks pass.
4217 */
4218 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4219 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 throw new IllegalStateException(caller
4222 + ": Device doesn't support picture-in-picture mode.");
4223 }
4224
4225 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4226 if (r == null) {
4227 throw new IllegalStateException(caller
4228 + ": Can't find activity for token=" + token);
4229 }
4230
4231 if (!r.supportsPictureInPicture()) {
4232 throw new IllegalStateException(caller
4233 + ": Current activity does not support picture-in-picture.");
4234 }
4235
4236 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004237 && !mWindowManager.isValidPictureInPictureAspectRatio(
4238 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 final float minAspectRatio = mContext.getResources().getFloat(
4240 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4241 final float maxAspectRatio = mContext.getResources().getFloat(
4242 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4243 throw new IllegalArgumentException(String.format(caller
4244 + ": Aspect ratio is too extreme (must be between %f and %f).",
4245 minAspectRatio, maxAspectRatio));
4246 }
4247
4248 // Truncate the number of actions if necessary
4249 params.truncateActions(getMaxNumPictureInPictureActions(token));
4250
4251 return r;
4252 }
4253
4254 @Override
4255 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 synchronized (mGlobalLock) {
4258 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4259 if (r == null) {
4260 throw new IllegalArgumentException("Activity does not exist; token="
4261 + activityToken);
4262 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004263 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 }
4265 }
4266
4267 @Override
4268 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4269 Rect tempDockedTaskInsetBounds,
4270 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 long ident = Binder.clearCallingIdentity();
4273 try {
4274 synchronized (mGlobalLock) {
4275 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4276 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4277 PRESERVE_WINDOWS);
4278 }
4279 } finally {
4280 Binder.restoreCallingIdentity(ident);
4281 }
4282 }
4283
4284 @Override
4285 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 final long ident = Binder.clearCallingIdentity();
4288 try {
4289 synchronized (mGlobalLock) {
4290 mStackSupervisor.setSplitScreenResizing(resizing);
4291 }
4292 } finally {
4293 Binder.restoreCallingIdentity(ident);
4294 }
4295 }
4296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 /**
4298 * Check that we have the features required for VR-related API calls, and throw an exception if
4299 * not.
4300 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004301 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 if (!mContext.getPackageManager().hasSystemFeature(
4303 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4304 throw new UnsupportedOperationException("VR mode not supported on this device!");
4305 }
4306 }
4307
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 @Override
4309 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311
4312 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4313
4314 ActivityRecord r;
4315 synchronized (mGlobalLock) {
4316 r = ActivityRecord.isInStackLocked(token);
4317 }
4318
4319 if (r == null) {
4320 throw new IllegalArgumentException();
4321 }
4322
4323 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004324 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 VrManagerInternal.NO_ERROR) {
4326 return err;
4327 }
4328
4329 // Clear the binder calling uid since this path may call moveToTask().
4330 final long callingId = Binder.clearCallingIdentity();
4331 try {
4332 synchronized (mGlobalLock) {
4333 r.requestedVrComponent = (enabled) ? packageName : null;
4334
4335 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004336 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004337 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338 }
4339 return 0;
4340 }
4341 } finally {
4342 Binder.restoreCallingIdentity(callingId);
4343 }
4344 }
4345
4346 @Override
4347 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4348 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4349 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004350 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4352 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4353 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004354 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 || activity.voiceSession != null) {
4356 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4357 return;
4358 }
4359 if (activity.pendingVoiceInteractionStart) {
4360 Slog.w(TAG, "Pending start of voice interaction already.");
4361 return;
4362 }
4363 activity.pendingVoiceInteractionStart = true;
4364 }
4365 LocalServices.getService(VoiceInteractionManagerInternal.class)
4366 .startLocalVoiceInteraction(callingActivity, options);
4367 }
4368
4369 @Override
4370 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4371 LocalServices.getService(VoiceInteractionManagerInternal.class)
4372 .stopLocalVoiceInteraction(callingActivity);
4373 }
4374
4375 @Override
4376 public boolean supportsLocalVoiceInteraction() {
4377 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4378 .supportsLocalVoiceInteraction();
4379 }
4380
4381 /** Notifies all listeners when the pinned stack animation starts. */
4382 @Override
4383 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004384 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 }
4386
4387 /** Notifies all listeners when the pinned stack animation ends. */
4388 @Override
4389 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004390 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 }
4392
4393 @Override
4394 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 final long ident = Binder.clearCallingIdentity();
4397 try {
4398 synchronized (mGlobalLock) {
4399 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4400 }
4401 } finally {
4402 Binder.restoreCallingIdentity(ident);
4403 }
4404 }
4405
4406 @Override
4407 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409
4410 synchronized (mGlobalLock) {
4411 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004412 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 // Call might come when display is not yet added or has already been removed.
4414 if (DEBUG_CONFIGURATION) {
4415 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4416 + displayId);
4417 }
4418 return false;
4419 }
4420
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 }
4425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004427 final Message msg = PooledLambda.obtainMessage(
4428 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4429 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431
4432 final long origId = Binder.clearCallingIdentity();
4433 try {
4434 if (values != null) {
4435 Settings.System.clearConfiguration(values);
4436 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4439 return mTmpUpdateConfigurationResult.changes != 0;
4440 } finally {
4441 Binder.restoreCallingIdentity(origId);
4442 }
4443 }
4444 }
4445
4446 @Override
4447 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449
4450 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004451 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
4455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004457 final Message msg = PooledLambda.obtainMessage(
4458 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4459 DEFAULT_DISPLAY);
4460 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 }
4462
4463 final long origId = Binder.clearCallingIdentity();
4464 try {
4465 if (values != null) {
4466 Settings.System.clearConfiguration(values);
4467 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 UserHandle.USER_NULL, false /* deferResume */,
4470 mTmpUpdateConfigurationResult);
4471 return mTmpUpdateConfigurationResult.changes != 0;
4472 } finally {
4473 Binder.restoreCallingIdentity(origId);
4474 }
4475 }
4476 }
4477
4478 @Override
4479 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4480 CharSequence message) {
4481 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4484 }
4485 final long callingId = Binder.clearCallingIdentity();
4486 try {
4487 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004488 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 }
4490 } finally {
4491 Binder.restoreCallingIdentity(callingId);
4492 }
4493 }
4494
4495 @Override
4496 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004497 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004498 "cancelTaskWindowTransition()");
4499 final long ident = Binder.clearCallingIdentity();
4500 try {
4501 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004502 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 MATCH_TASK_IN_STACKS_ONLY);
4504 if (task == null) {
4505 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4506 return;
4507 }
4508 task.cancelWindowTransition();
4509 }
4510 } finally {
4511 Binder.restoreCallingIdentity(ident);
4512 }
4513 }
4514
4515 @Override
4516 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 final long ident = Binder.clearCallingIdentity();
4519 try {
4520 final TaskRecord task;
4521 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004522 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4524 if (task == null) {
4525 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4526 return null;
4527 }
4528 }
4529 // Don't call this while holding the lock as this operation might hit the disk.
4530 return task.getSnapshot(reducedResolution);
4531 } finally {
4532 Binder.restoreCallingIdentity(ident);
4533 }
4534 }
4535
4536 @Override
4537 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4542 + token);
4543 return;
4544 }
4545 final long origId = Binder.clearCallingIdentity();
4546 try {
4547 r.setDisablePreviewScreenshots(disable);
4548 } finally {
4549 Binder.restoreCallingIdentity(origId);
4550 }
4551 }
4552 }
4553
4554 /** Return the user id of the last resumed activity. */
4555 @Override
4556 public @UserIdInt
4557 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004558 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4560 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004561 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004562 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004564 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 }
4566 }
4567
4568 @Override
4569 public void updateLockTaskFeatures(int userId, int flags) {
4570 final int callingUid = Binder.getCallingUid();
4571 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004572 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 "updateLockTaskFeatures()");
4574 }
4575 synchronized (mGlobalLock) {
4576 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4577 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004578 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 }
4580 }
4581
4582 @Override
4583 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4584 synchronized (mGlobalLock) {
4585 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4586 if (r == null) {
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.setShowWhenLocked(showWhenLocked);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
4598 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004599 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4600 synchronized (mGlobalLock) {
4601 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4602 if (r == null) {
4603 return;
4604 }
4605 final long origId = Binder.clearCallingIdentity();
4606 try {
4607 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4608 } finally {
4609 Binder.restoreCallingIdentity(origId);
4610 }
4611 }
4612 }
4613
4614 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4616 synchronized (mGlobalLock) {
4617 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4618 if (r == null) {
4619 return;
4620 }
4621 final long origId = Binder.clearCallingIdentity();
4622 try {
4623 r.setTurnScreenOn(turnScreenOn);
4624 } finally {
4625 Binder.restoreCallingIdentity(origId);
4626 }
4627 }
4628 }
4629
4630 @Override
4631 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004632 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 "registerRemoteAnimations");
4634 definition.setCallingPid(Binder.getCallingPid());
4635 synchronized (mGlobalLock) {
4636 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4637 if (r == null) {
4638 return;
4639 }
4640 final long origId = Binder.clearCallingIdentity();
4641 try {
4642 r.registerRemoteAnimations(definition);
4643 } finally {
4644 Binder.restoreCallingIdentity(origId);
4645 }
4646 }
4647 }
4648
4649 @Override
4650 public void registerRemoteAnimationForNextActivityStart(String packageName,
4651 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004652 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004653 "registerRemoteAnimationForNextActivityStart");
4654 adapter.setCallingPid(Binder.getCallingPid());
4655 synchronized (mGlobalLock) {
4656 final long origId = Binder.clearCallingIdentity();
4657 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004658 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004659 packageName, adapter);
4660 } finally {
4661 Binder.restoreCallingIdentity(origId);
4662 }
4663 }
4664 }
4665
Evan Rosky966759f2019-01-15 10:33:58 -08004666 @Override
4667 public void registerRemoteAnimationsForDisplay(int displayId,
4668 RemoteAnimationDefinition definition) {
4669 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4670 "registerRemoteAnimations");
4671 definition.setCallingPid(Binder.getCallingPid());
4672 synchronized (mGlobalLock) {
4673 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4674 if (display == null) {
4675 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4676 return;
4677 }
4678 final long origId = Binder.clearCallingIdentity();
4679 try {
4680 display.mDisplayContent.registerRemoteAnimations(definition);
4681 } finally {
4682 Binder.restoreCallingIdentity(origId);
4683 }
4684 }
4685 }
4686
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004687 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4688 @Override
4689 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4690 synchronized (mGlobalLock) {
4691 final long origId = Binder.clearCallingIdentity();
4692 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004693 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004694 } finally {
4695 Binder.restoreCallingIdentity(origId);
4696 }
4697 }
4698 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004699
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004700 @Override
4701 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004702 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004703 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004704 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004705 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004706 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 }
4708 }
4709
4710 @Override
4711 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004712 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 != PERMISSION_GRANTED) {
4714 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4715 + Binder.getCallingPid()
4716 + ", uid=" + Binder.getCallingUid()
4717 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4718 Slog.w(TAG, msg);
4719 throw new SecurityException(msg);
4720 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004721 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004723 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004724 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004725 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 }
4727 }
4728
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004729 @Override
4730 public void stopAppSwitches() {
4731 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4732 synchronized (mGlobalLock) {
4733 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4734 mDidAppSwitch = false;
4735 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4736 }
4737 }
4738
4739 @Override
4740 public void resumeAppSwitches() {
4741 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4742 synchronized (mGlobalLock) {
4743 // Note that we don't execute any pending app switches... we will
4744 // let those wait until either the timeout, or the next start
4745 // activity request.
4746 mAppSwitchesAllowedTime = 0;
4747 }
4748 }
4749
4750 void onStartActivitySetDidAppSwitch() {
4751 if (mDidAppSwitch) {
4752 // This is the second allowed switch since we stopped switches, so now just generally
4753 // allow switches. Use case:
4754 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4755 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4756 // anyone to switch again).
4757 mAppSwitchesAllowedTime = 0;
4758 } else {
4759 mDidAppSwitch = true;
4760 }
4761 }
4762
4763 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004764 boolean shouldDisableNonVrUiLocked() {
4765 return mVrController.shouldDisableNonVrUiLocked();
4766 }
4767
Wale Ogunwale53783742018-09-16 10:21:51 -07004768 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004769 // VR apps are expected to run in a main display. If an app is turning on VR for
4770 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4771 // fullscreen stack before enabling VR Mode.
4772 // TODO: The goal of this code is to keep the VR app on the main display. When the
4773 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4774 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4775 // option would be a better choice here.
4776 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4777 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4778 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004779 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004781 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 }
4783 mH.post(() -> {
4784 if (!mVrController.onVrModeChanged(r)) {
4785 return;
4786 }
4787 synchronized (mGlobalLock) {
4788 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4789 mWindowManager.disableNonVrUi(disableNonVrUi);
4790 if (disableNonVrUi) {
4791 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4792 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004793 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 }
4795 }
4796 });
4797 }
4798
Wale Ogunwale53783742018-09-16 10:21:51 -07004799 @Override
4800 public int getPackageScreenCompatMode(String packageName) {
4801 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4802 synchronized (mGlobalLock) {
4803 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4804 }
4805 }
4806
4807 @Override
4808 public void setPackageScreenCompatMode(String packageName, int mode) {
4809 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4810 "setPackageScreenCompatMode");
4811 synchronized (mGlobalLock) {
4812 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4813 }
4814 }
4815
4816 @Override
4817 public boolean getPackageAskScreenCompat(String packageName) {
4818 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4819 synchronized (mGlobalLock) {
4820 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4821 }
4822 }
4823
4824 @Override
4825 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4826 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4827 "setPackageAskScreenCompat");
4828 synchronized (mGlobalLock) {
4829 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4830 }
4831 }
4832
Wale Ogunwale64258362018-10-16 15:13:37 -07004833 public static String relaunchReasonToString(int relaunchReason) {
4834 switch (relaunchReason) {
4835 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4836 return "window_resize";
4837 case RELAUNCH_REASON_FREE_RESIZE:
4838 return "free_resize";
4839 default:
4840 return null;
4841 }
4842 }
4843
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004844 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004845 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004846 }
4847
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004848 /** Pokes the task persister. */
4849 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4850 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4851 }
4852
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004853 boolean isKeyguardLocked() {
4854 return mKeyguardController.isKeyguardLocked();
4855 }
4856
Garfield Tan01548632018-11-27 10:15:48 -08004857 /**
4858 * Clears launch params for the given package.
4859 * @param packageNames the names of the packages of which the launch params are to be cleared
4860 */
4861 @Override
4862 public void clearLaunchParamsForPackages(List<String> packageNames) {
4863 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4864 "clearLaunchParamsForPackages");
4865 synchronized (mGlobalLock) {
4866 for (int i = 0; i < packageNames.size(); ++i) {
4867 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4868 }
4869 }
4870 }
4871
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004872 /**
4873 * Makes the display with the given id a single task instance display. I.e the display can only
4874 * contain one task.
4875 */
4876 @Override
4877 public void setDisplayToSingleTaskInstance(int displayId) {
4878 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4879 "setDisplayToSingleTaskInstance");
4880 final long origId = Binder.clearCallingIdentity();
4881 try {
4882 final ActivityDisplay display =
4883 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4884 if (display != null) {
4885 display.setDisplayToSingleTaskInstance();
4886 }
4887 } finally {
4888 Binder.restoreCallingIdentity(origId);
4889 }
4890 }
4891
Wale Ogunwale31913b52018-10-13 08:29:31 -07004892 void dumpLastANRLocked(PrintWriter pw) {
4893 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4894 if (mLastANRState == null) {
4895 pw.println(" <no ANR has occurred since boot>");
4896 } else {
4897 pw.println(mLastANRState);
4898 }
4899 }
4900
4901 void dumpLastANRTracesLocked(PrintWriter pw) {
4902 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4903
4904 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4905 if (ArrayUtils.isEmpty(files)) {
4906 pw.println(" <no ANR has occurred since boot>");
4907 return;
4908 }
4909 // Find the latest file.
4910 File latest = null;
4911 for (File f : files) {
4912 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4913 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004914 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004915 }
4916 pw.print("File: ");
4917 pw.print(latest.getName());
4918 pw.println();
4919 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4920 String line;
4921 while ((line = in.readLine()) != null) {
4922 pw.println(line);
4923 }
4924 } catch (IOException e) {
4925 pw.print("Unable to read: ");
4926 pw.print(e);
4927 pw.println();
4928 }
4929 }
4930
4931 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4932 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4933 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4934 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4935 }
4936
4937 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4938 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4939 pw.println(header);
4940
Wale Ogunwaled32da472018-11-16 07:19:28 -08004941 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 dumpPackage);
4943 boolean needSep = printedAnything;
4944
4945 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004946 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004947 " ResumedActivity: ");
4948 if (printed) {
4949 printedAnything = true;
4950 needSep = false;
4951 }
4952
4953 if (dumpPackage == null) {
4954 if (needSep) {
4955 pw.println();
4956 }
4957 printedAnything = true;
4958 mStackSupervisor.dump(pw, " ");
4959 }
4960
4961 if (!printedAnything) {
4962 pw.println(" (nothing)");
4963 }
4964 }
4965
4966 void dumpActivityContainersLocked(PrintWriter pw) {
4967 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004968 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004969 pw.println(" ");
4970 }
4971
4972 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4973 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4974 getActivityStartController().dump(pw, "", dumpPackage);
4975 }
4976
4977 /**
4978 * There are three things that cmd can be:
4979 * - a flattened component name that matches an existing activity
4980 * - the cmd arg isn't the flattened component name of an existing activity:
4981 * dump all activity whose component contains the cmd as a substring
4982 * - A hex number of the ActivityRecord object instance.
4983 *
4984 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4985 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4986 */
4987 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4988 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4989 ArrayList<ActivityRecord> activities;
4990
4991 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004992 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004993 dumpFocusedStackOnly);
4994 }
4995
4996 if (activities.size() <= 0) {
4997 return false;
4998 }
4999
5000 String[] newArgs = new String[args.length - opti];
5001 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5002
5003 TaskRecord lastTask = null;
5004 boolean needSep = false;
5005 for (int i = activities.size() - 1; i >= 0; i--) {
5006 ActivityRecord r = activities.get(i);
5007 if (needSep) {
5008 pw.println();
5009 }
5010 needSep = true;
5011 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005012 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005013 if (lastTask != task) {
5014 lastTask = task;
5015 pw.print("TASK "); pw.print(lastTask.affinity);
5016 pw.print(" id="); pw.print(lastTask.taskId);
5017 pw.print(" userId="); pw.println(lastTask.userId);
5018 if (dumpAll) {
5019 lastTask.dump(pw, " ");
5020 }
5021 }
5022 }
5023 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5024 }
5025 return true;
5026 }
5027
5028 /**
5029 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5030 * there is a thread associated with the activity.
5031 */
5032 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5033 final ActivityRecord r, String[] args, boolean dumpAll) {
5034 String innerPrefix = prefix + " ";
5035 synchronized (mGlobalLock) {
5036 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5037 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5038 pw.print(" pid=");
5039 if (r.hasProcess()) pw.println(r.app.getPid());
5040 else pw.println("(not running)");
5041 if (dumpAll) {
5042 r.dump(pw, innerPrefix);
5043 }
5044 }
5045 if (r.attachedToProcess()) {
5046 // flush anything that is already in the PrintWriter since the thread is going
5047 // to write to the file descriptor directly
5048 pw.flush();
5049 try {
5050 TransferPipe tp = new TransferPipe();
5051 try {
5052 r.app.getThread().dumpActivity(tp.getWriteFd(),
5053 r.appToken, innerPrefix, args);
5054 tp.go(fd);
5055 } finally {
5056 tp.kill();
5057 }
5058 } catch (IOException e) {
5059 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5060 } catch (RemoteException e) {
5061 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5062 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005064 }
5065
sanryhuang498e77e2018-12-06 14:57:01 +08005066 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5067 boolean testPssMode) {
5068 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5069 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5070 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005071 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005072 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5073 st.toString());
5074 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5076 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5077 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005078 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5079 testPssMode);
5080 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005081 }
5082
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005083 int getCurrentUserId() {
5084 return mAmInternal.getCurrentUserId();
5085 }
5086
5087 private void enforceNotIsolatedCaller(String caller) {
5088 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5089 throw new SecurityException("Isolated process not allowed to call " + caller);
5090 }
5091 }
5092
Wale Ogunwalef6733932018-06-27 05:14:34 -07005093 public Configuration getConfiguration() {
5094 Configuration ci;
5095 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005096 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005097 ci.userSetLocale = false;
5098 }
5099 return ci;
5100 }
5101
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005102 /**
5103 * Current global configuration information. Contains general settings for the entire system,
5104 * also corresponds to the merged configuration of the default display.
5105 */
5106 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005107 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005108 }
5109
5110 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5111 boolean initLocale) {
5112 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5113 }
5114
5115 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5116 boolean initLocale, boolean deferResume) {
5117 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5118 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5119 UserHandle.USER_NULL, deferResume);
5120 }
5121
Wale Ogunwale59507092018-10-29 09:00:30 -07005122 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005123 final long origId = Binder.clearCallingIdentity();
5124 try {
5125 synchronized (mGlobalLock) {
5126 updateConfigurationLocked(values, null, false, true, userId,
5127 false /* deferResume */);
5128 }
5129 } finally {
5130 Binder.restoreCallingIdentity(origId);
5131 }
5132 }
5133
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5135 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5136 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5137 deferResume, null /* result */);
5138 }
5139
5140 /**
5141 * Do either or both things: (1) change the current configuration, and (2)
5142 * make sure the given activity is running with the (now) current
5143 * configuration. Returns true if the activity has been left running, or
5144 * false if <var>starting</var> is being destroyed to match the new
5145 * configuration.
5146 *
5147 * @param userId is only used when persistent parameter is set to true to persist configuration
5148 * for that particular user
5149 */
5150 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5151 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5152 ActivityTaskManagerService.UpdateConfigurationResult result) {
5153 int changes = 0;
5154 boolean kept = true;
5155
5156 if (mWindowManager != null) {
5157 mWindowManager.deferSurfaceLayout();
5158 }
5159 try {
5160 if (values != null) {
5161 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5162 deferResume);
5163 }
5164
5165 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5166 } finally {
5167 if (mWindowManager != null) {
5168 mWindowManager.continueSurfaceLayout();
5169 }
5170 }
5171
5172 if (result != null) {
5173 result.changes = changes;
5174 result.activityRelaunched = !kept;
5175 }
5176 return kept;
5177 }
5178
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179 /** Update default (global) configuration and notify listeners about changes. */
5180 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5181 boolean persistent, int userId, boolean deferResume) {
5182 mTempConfig.setTo(getGlobalConfiguration());
5183 final int changes = mTempConfig.updateFrom(values);
5184 if (changes == 0) {
5185 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5186 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5187 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5188 // (even if there are no actual changes) to unfreeze the window.
5189 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5190 return 0;
5191 }
5192
5193 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5194 "Updating global configuration to: " + values);
5195
5196 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5197 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5198 values.colorMode,
5199 values.densityDpi,
5200 values.fontScale,
5201 values.hardKeyboardHidden,
5202 values.keyboard,
5203 values.keyboardHidden,
5204 values.mcc,
5205 values.mnc,
5206 values.navigation,
5207 values.navigationHidden,
5208 values.orientation,
5209 values.screenHeightDp,
5210 values.screenLayout,
5211 values.screenWidthDp,
5212 values.smallestScreenWidthDp,
5213 values.touchscreen,
5214 values.uiMode);
5215
5216
5217 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5218 final LocaleList locales = values.getLocales();
5219 int bestLocaleIndex = 0;
5220 if (locales.size() > 1) {
5221 if (mSupportedSystemLocales == null) {
5222 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5223 }
5224 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5225 }
5226 SystemProperties.set("persist.sys.locale",
5227 locales.get(bestLocaleIndex).toLanguageTag());
5228 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005229
5230 final Message m = PooledLambda.obtainMessage(
5231 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5232 locales.get(bestLocaleIndex));
5233 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 }
5235
Yunfan Chen75157d72018-07-27 14:47:21 +09005236 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237
5238 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005239 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240
5241 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5242 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005243 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244
5245 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005246 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005247
5248 AttributeCache ac = AttributeCache.instance();
5249 if (ac != null) {
5250 ac.updateConfiguration(mTempConfig);
5251 }
5252
5253 // Make sure all resources in our process are updated right now, so that anyone who is going
5254 // to retrieve resource values after we return will be sure to get the new ones. This is
5255 // especially important during boot, where the first config change needs to guarantee all
5256 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005257 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258
5259 // We need another copy of global config because we're scheduling some calls instead of
5260 // running them in place. We need to be sure that object we send will be handled unchanged.
5261 final Configuration configCopy = new Configuration(mTempConfig);
5262 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005263 final Message msg = PooledLambda.obtainMessage(
5264 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5265 this, userId, configCopy);
5266 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005267 }
5268
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005269 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5270 for (int i = pidMap.size() - 1; i >= 0; i--) {
5271 final int pid = pidMap.keyAt(i);
5272 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005273 if (DEBUG_CONFIGURATION) {
5274 Slog.v(TAG_CONFIGURATION, "Update process config of "
5275 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005277 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
5279
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005280 final Message msg = PooledLambda.obtainMessage(
5281 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5282 mAmInternal, changes, initLocale);
5283 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284
5285 // Override configuration of the default display duplicates global config, so we need to
5286 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005287 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288 DEFAULT_DISPLAY);
5289
5290 return changes;
5291 }
5292
5293 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5294 boolean deferResume, int displayId) {
5295 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5296 displayId, null /* result */);
5297 }
5298
5299 /**
5300 * Updates override configuration specific for the selected display. If no config is provided,
5301 * new one will be computed in WM based on current display info.
5302 */
5303 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5304 ActivityRecord starting, boolean deferResume, int displayId,
5305 ActivityTaskManagerService.UpdateConfigurationResult result) {
5306 int changes = 0;
5307 boolean kept = true;
5308
5309 if (mWindowManager != null) {
5310 mWindowManager.deferSurfaceLayout();
5311 }
5312 try {
5313 if (values != null) {
5314 if (displayId == DEFAULT_DISPLAY) {
5315 // Override configuration of the default display duplicates global config, so
5316 // we're calling global config update instead for default display. It will also
5317 // apply the correct override config.
5318 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5319 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5320 } else {
5321 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5322 }
5323 }
5324
5325 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5326 } finally {
5327 if (mWindowManager != null) {
5328 mWindowManager.continueSurfaceLayout();
5329 }
5330 }
5331
5332 if (result != null) {
5333 result.changes = changes;
5334 result.activityRelaunched = !kept;
5335 }
5336 return kept;
5337 }
5338
5339 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5340 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005341 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342 final int changes = mTempConfig.updateFrom(values);
5343 if (changes != 0) {
5344 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5345 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005346 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005347
5348 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5349 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005350 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
Wale Ogunwale5c918702018-10-18 11:06:33 -07005352 // Post message to start process to avoid possible deadlock of calling into AMS with
5353 // the ATMS lock held.
5354 final Message msg = PooledLambda.obtainMessage(
5355 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005356 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005357 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005358 }
5359 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005360 return changes;
5361 }
5362
Wale Ogunwalef6733932018-06-27 05:14:34 -07005363 private void updateEventDispatchingLocked(boolean booted) {
5364 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5365 }
5366
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005367 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5368 final ContentResolver resolver = mContext.getContentResolver();
5369 Settings.System.putConfigurationForUser(resolver, config, userId);
5370 }
5371
5372 private void sendLocaleToMountDaemonMsg(Locale l) {
5373 try {
5374 IBinder service = ServiceManager.getService("mount");
5375 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5376 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5377 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5378 } catch (RemoteException e) {
5379 Log.e(TAG, "Error storing locale for decryption UI", e);
5380 }
5381 }
5382
Alison Cichowlas3e340502018-08-07 17:15:01 -04005383 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5384 mStartActivitySources.remove(permissionToken);
5385 mExpiredStartAsCallerTokens.add(permissionToken);
5386 }
5387
5388 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5389 mExpiredStartAsCallerTokens.remove(permissionToken);
5390 }
5391
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005392 boolean isActivityStartsLoggingEnabled() {
5393 return mAmInternal.isActivityStartsLoggingEnabled();
5394 }
5395
Michal Karpinski8596ded2018-11-14 14:43:48 +00005396 boolean isBackgroundActivityStartsEnabled() {
5397 return mAmInternal.isBackgroundActivityStartsEnabled();
5398 }
5399
Ricky Waiaca8a772019-04-04 16:01:06 +01005400 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5401 if (packageName == null) {
5402 return false;
5403 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005404 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5405 }
5406
Wale Ogunwalef6733932018-06-27 05:14:34 -07005407 void enableScreenAfterBoot(boolean booted) {
5408 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5409 SystemClock.uptimeMillis());
5410 mWindowManager.enableScreenAfterBoot();
5411
5412 synchronized (mGlobalLock) {
5413 updateEventDispatchingLocked(booted);
5414 }
5415 }
5416
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005417 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5418 if (r == null || !r.hasProcess()) {
5419 return KEY_DISPATCHING_TIMEOUT_MS;
5420 }
5421 return getInputDispatchingTimeoutLocked(r.app);
5422 }
5423
5424 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005425 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005426 }
5427
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 /**
5429 * Decide based on the configuration whether we should show the ANR,
5430 * crash, etc dialogs. The idea is that if there is no affordance to
5431 * press the on-screen buttons, or the user experience would be more
5432 * greatly impacted than the crash itself, we shouldn't show the dialog.
5433 *
5434 * A thought: SystemUI might also want to get told about this, the Power
5435 * dialog / global actions also might want different behaviors.
5436 */
5437 private void updateShouldShowDialogsLocked(Configuration config) {
5438 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5439 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5440 && config.navigation == Configuration.NAVIGATION_NONAV);
5441 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5442 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5443 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5444 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5445 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5446 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5447 HIDE_ERROR_DIALOGS, 0) != 0;
5448 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5449 }
5450
5451 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5452 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5453 FONT_SCALE, 1.0f, userId);
5454
5455 synchronized (this) {
5456 if (getGlobalConfiguration().fontScale == scaleFactor) {
5457 return;
5458 }
5459
5460 final Configuration configuration
5461 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5462 configuration.fontScale = scaleFactor;
5463 updatePersistentConfiguration(configuration, userId);
5464 }
5465 }
5466
5467 // Actually is sleeping or shutting down or whatever else in the future
5468 // is an inactive state.
5469 boolean isSleepingOrShuttingDownLocked() {
5470 return isSleepingLocked() || mShuttingDown;
5471 }
5472
5473 boolean isSleepingLocked() {
5474 return mSleeping;
5475 }
5476
Riddle Hsu16567132018-08-16 21:37:47 +08005477 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005479 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005480 if (task.isActivityTypeStandard()) {
5481 if (mCurAppTimeTracker != r.appTimeTracker) {
5482 // We are switching app tracking. Complete the current one.
5483 if (mCurAppTimeTracker != null) {
5484 mCurAppTimeTracker.stop();
5485 mH.obtainMessage(
5486 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005487 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 mCurAppTimeTracker = null;
5489 }
5490 if (r.appTimeTracker != null) {
5491 mCurAppTimeTracker = r.appTimeTracker;
5492 startTimeTrackingFocusedActivityLocked();
5493 }
5494 } else {
5495 startTimeTrackingFocusedActivityLocked();
5496 }
5497 } else {
5498 r.appTimeTracker = null;
5499 }
5500 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5501 // TODO: Probably not, because we don't want to resume voice on switching
5502 // back to this activity
5503 if (task.voiceInteractor != null) {
5504 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5505 } else {
5506 finishRunningVoiceLocked();
5507
5508 if (mLastResumedActivity != null) {
5509 final IVoiceInteractionSession session;
5510
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005511 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005512 if (lastResumedActivityTask != null
5513 && lastResumedActivityTask.voiceSession != null) {
5514 session = lastResumedActivityTask.voiceSession;
5515 } else {
5516 session = mLastResumedActivity.voiceSession;
5517 }
5518
5519 if (session != null) {
5520 // We had been in a voice interaction session, but now focused has
5521 // move to something different. Just finish the session, we can't
5522 // return to it and retain the proper state and synchronization with
5523 // the voice interaction service.
5524 finishVoiceTask(session);
5525 }
5526 }
5527 }
5528
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005529 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5530 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005531 }
5532 updateResumedAppTrace(r);
5533 mLastResumedActivity = r;
5534
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005535 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536
5537 applyUpdateLockStateLocked(r);
5538 applyUpdateVrModeLocked(r);
5539
5540 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 r == null ? "NULL" : r.shortComponentName,
5543 reason);
5544 }
5545
5546 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5547 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005548 final ActivityTaskManagerInternal.SleepToken token =
5549 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550 updateSleepIfNeededLocked();
5551 return token;
5552 }
5553 }
5554
5555 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005556 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 final boolean wasSleeping = mSleeping;
5558 boolean updateOomAdj = false;
5559
5560 if (!shouldSleep) {
5561 // If wasSleeping is true, we need to wake up activity manager state from when
5562 // we started sleeping. In either case, we need to apply the sleep tokens, which
5563 // will wake up stacks or put them to sleep as appropriate.
5564 if (wasSleeping) {
5565 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005566 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5567 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 startTimeTrackingFocusedActivityLocked();
5569 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005570 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5572 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005573 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 if (wasSleeping) {
5575 updateOomAdj = true;
5576 }
5577 } else if (!mSleeping && shouldSleep) {
5578 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005579 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5580 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005581 if (mCurAppTimeTracker != null) {
5582 mCurAppTimeTracker.stop();
5583 }
5584 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005585 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 mStackSupervisor.goingToSleepLocked();
5587 updateResumedAppTrace(null /* resumed */);
5588 updateOomAdj = true;
5589 }
5590 if (updateOomAdj) {
5591 mH.post(mAmInternal::updateOomAdj);
5592 }
5593 }
5594
5595 void updateOomAdj() {
5596 mH.post(mAmInternal::updateOomAdj);
5597 }
5598
Wale Ogunwale53783742018-09-16 10:21:51 -07005599 void updateCpuStats() {
5600 mH.post(mAmInternal::updateCpuStats);
5601 }
5602
Hui Yu03d12402018-12-06 18:00:37 -08005603 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5604 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005605 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5606 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005607 mH.sendMessage(m);
5608 }
5609
Hui Yu03d12402018-12-06 18:00:37 -08005610 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005611 ComponentName taskRoot = null;
5612 final TaskRecord task = activity.getTaskRecord();
5613 if (task != null) {
5614 final ActivityRecord rootActivity = task.getRootActivity();
5615 if (rootActivity != null) {
5616 taskRoot = rootActivity.mActivityComponent;
5617 }
5618 }
5619
Hui Yu03d12402018-12-06 18:00:37 -08005620 final Message m = PooledLambda.obtainMessage(
5621 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005622 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005623 mH.sendMessage(m);
5624 }
5625
Wale Ogunwale53783742018-09-16 10:21:51 -07005626 void setBooting(boolean booting) {
5627 mAmInternal.setBooting(booting);
5628 }
5629
5630 boolean isBooting() {
5631 return mAmInternal.isBooting();
5632 }
5633
5634 void setBooted(boolean booted) {
5635 mAmInternal.setBooted(booted);
5636 }
5637
5638 boolean isBooted() {
5639 return mAmInternal.isBooted();
5640 }
5641
5642 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5643 mH.post(() -> {
5644 if (finishBooting) {
5645 mAmInternal.finishBooting();
5646 }
5647 if (enableScreen) {
5648 mInternal.enableScreenAfterBoot(isBooted());
5649 }
5650 });
5651 }
5652
5653 void setHeavyWeightProcess(ActivityRecord root) {
5654 mHeavyWeightProcess = root.app;
5655 final Message m = PooledLambda.obtainMessage(
5656 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005657 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005658 mH.sendMessage(m);
5659 }
5660
5661 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5662 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5663 return;
5664 }
5665
5666 mHeavyWeightProcess = null;
5667 final Message m = PooledLambda.obtainMessage(
5668 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5669 proc.mUserId);
5670 mH.sendMessage(m);
5671 }
5672
5673 private void cancelHeavyWeightProcessNotification(int userId) {
5674 final INotificationManager inm = NotificationManager.getService();
5675 if (inm == null) {
5676 return;
5677 }
5678 try {
5679 inm.cancelNotificationWithTag("android", null,
5680 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5681 } catch (RuntimeException e) {
5682 Slog.w(TAG, "Error canceling notification for service", e);
5683 } catch (RemoteException e) {
5684 }
5685
5686 }
5687
5688 private void postHeavyWeightProcessNotification(
5689 WindowProcessController proc, Intent intent, int userId) {
5690 if (proc == null) {
5691 return;
5692 }
5693
5694 final INotificationManager inm = NotificationManager.getService();
5695 if (inm == null) {
5696 return;
5697 }
5698
5699 try {
5700 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5701 String text = mContext.getString(R.string.heavy_weight_notification,
5702 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5703 Notification notification =
5704 new Notification.Builder(context,
5705 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5706 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5707 .setWhen(0)
5708 .setOngoing(true)
5709 .setTicker(text)
5710 .setColor(mContext.getColor(
5711 com.android.internal.R.color.system_notification_accent_color))
5712 .setContentTitle(text)
5713 .setContentText(
5714 mContext.getText(R.string.heavy_weight_notification_detail))
5715 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5716 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5717 new UserHandle(userId)))
5718 .build();
5719 try {
5720 inm.enqueueNotificationWithTag("android", "android", null,
5721 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5722 } catch (RuntimeException e) {
5723 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5724 } catch (RemoteException e) {
5725 }
5726 } catch (PackageManager.NameNotFoundException e) {
5727 Slog.w(TAG, "Unable to create context for heavy notification", e);
5728 }
5729
5730 }
5731
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005732 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5733 IBinder token, String resultWho, int requestCode, Intent[] intents,
5734 String[] resolvedTypes, int flags, Bundle bOptions) {
5735
5736 ActivityRecord activity = null;
5737 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5738 activity = ActivityRecord.isInStackLocked(token);
5739 if (activity == null) {
5740 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5741 return null;
5742 }
5743 if (activity.finishing) {
5744 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5745 return null;
5746 }
5747 }
5748
5749 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5750 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5751 bOptions);
5752 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5753 if (noCreate) {
5754 return rec;
5755 }
5756 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5757 if (activity.pendingResults == null) {
5758 activity.pendingResults = new HashSet<>();
5759 }
5760 activity.pendingResults.add(rec.ref);
5761 }
5762 return rec;
5763 }
5764
Andrii Kulian52d255c2018-07-13 11:32:19 -07005765 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005766 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005767 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005768 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5769 mCurAppTimeTracker.start(resumedActivity.packageName);
5770 }
5771 }
5772
5773 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5774 if (mTracedResumedActivity != null) {
5775 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5776 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5777 }
5778 if (resumed != null) {
5779 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5780 constructResumedTraceName(resumed.packageName), 0);
5781 }
5782 mTracedResumedActivity = resumed;
5783 }
5784
5785 private String constructResumedTraceName(String packageName) {
5786 return "focused app: " + packageName;
5787 }
5788
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005789 /** Applies latest configuration and/or visibility updates if needed. */
5790 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5791 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005792 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005793 // mainStack is null during startup.
5794 if (mainStack != null) {
5795 if (changes != 0 && starting == null) {
5796 // If the configuration changed, and the caller is not already
5797 // in the process of starting an activity, then find the top
5798 // activity to check if its configuration needs to change.
5799 starting = mainStack.topRunningActivityLocked();
5800 }
5801
5802 if (starting != null) {
5803 kept = starting.ensureActivityConfiguration(changes,
5804 false /* preserveWindow */);
5805 // And we need to make sure at this point that all other activities
5806 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005807 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005808 !PRESERVE_WINDOWS);
5809 }
5810 }
5811
5812 return kept;
5813 }
5814
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005815 void scheduleAppGcsLocked() {
5816 mH.post(() -> mAmInternal.scheduleAppGcs());
5817 }
5818
Wale Ogunwale53783742018-09-16 10:21:51 -07005819 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5820 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5821 }
5822
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005823 /**
5824 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5825 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5826 * on demand.
5827 */
5828 IPackageManager getPackageManager() {
5829 return AppGlobals.getPackageManager();
5830 }
5831
5832 PackageManagerInternal getPackageManagerInternalLocked() {
5833 if (mPmInternal == null) {
5834 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5835 }
5836 return mPmInternal;
5837 }
5838
Hai Zhangf4da9be2019-05-01 13:46:06 +08005839 PermissionPolicyInternal getPermissionPolicyInternal() {
5840 if (mPermissionPolicyInternal == null) {
5841 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5842 }
5843 return mPermissionPolicyInternal;
5844 }
5845
Wale Ogunwale008163e2018-07-23 23:11:08 -07005846 AppWarnings getAppWarningsLocked() {
5847 return mAppWarnings;
5848 }
5849
Wale Ogunwale214f3482018-10-04 11:00:47 -07005850 Intent getHomeIntent() {
5851 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5852 intent.setComponent(mTopComponent);
5853 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5854 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5855 intent.addCategory(Intent.CATEGORY_HOME);
5856 }
5857 return intent;
5858 }
5859
Chilun2ef71f72018-11-16 17:57:15 +08005860 /**
5861 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5862 * activities.
5863 *
5864 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5865 * component defined in config_secondaryHomeComponent.
5866 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5867 */
5868 Intent getSecondaryHomeIntent(String preferredPackage) {
5869 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005870 if (preferredPackage == null) {
5871 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005872 final String secondaryHomeComponent = mContext.getResources().getString(
5873 com.android.internal.R.string.config_secondaryHomeComponent);
5874 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5875 } else {
5876 intent.setPackage(preferredPackage);
5877 }
5878 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5879 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5880 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5881 }
5882 return intent;
5883 }
5884
Wale Ogunwale214f3482018-10-04 11:00:47 -07005885 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5886 if (info == null) return null;
5887 ApplicationInfo newInfo = new ApplicationInfo(info);
5888 newInfo.initForUser(userId);
5889 return newInfo;
5890 }
5891
Wale Ogunwale9c103022018-10-18 07:44:54 -07005892 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005893 if (uid == SYSTEM_UID) {
5894 // The system gets to run in any process. If there are multiple processes with the same
5895 // uid, just pick the first (this should never happen).
5896 final SparseArray<WindowProcessController> procs =
5897 mProcessNames.getMap().get(processName);
5898 if (procs == null) return null;
5899 final int procCount = procs.size();
5900 for (int i = 0; i < procCount; i++) {
5901 final int procUid = procs.keyAt(i);
5902 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5903 // Don't use an app process or different user process for system component.
5904 continue;
5905 }
5906 return procs.valueAt(i);
5907 }
5908 }
5909
5910 return mProcessNames.get(processName, uid);
5911 }
5912
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005913 WindowProcessController getProcessController(IApplicationThread thread) {
5914 if (thread == null) {
5915 return null;
5916 }
5917
5918 final IBinder threadBinder = thread.asBinder();
5919 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5920 for (int i = pmap.size()-1; i >= 0; i--) {
5921 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5922 for (int j = procs.size() - 1; j >= 0; j--) {
5923 final WindowProcessController proc = procs.valueAt(j);
5924 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5925 return proc;
5926 }
5927 }
5928 }
5929
5930 return null;
5931 }
5932
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005933 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005934 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005935 if (proc == null) return null;
5936 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5937 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005938 }
5939 return null;
5940 }
5941
Riddle Hsua0536432019-02-16 00:38:59 +08005942 int getUidState(int uid) {
5943 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005944 }
5945
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005946 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005947 // A uid is considered to be foreground if it has a visible non-toast window.
5948 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005949 }
5950
Ricky Wai96f5c352019-04-10 18:40:17 +01005951 boolean isDeviceOwner(int uid) {
5952 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005953 }
5954
Ricky Wai96f5c352019-04-10 18:40:17 +01005955 void setDeviceOwnerUid(int uid) {
5956 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005957 }
5958
Wale Ogunwale9de19442018-10-18 19:05:03 -07005959 /**
5960 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5961 * the whitelist
5962 */
5963 String getPendingTempWhitelistTagForUidLocked(int uid) {
5964 return mPendingTempWhitelist.get(uid);
5965 }
5966
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005967 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5968 if (true || Build.IS_USER) {
5969 return;
5970 }
5971
5972 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5973 StrictMode.allowThreadDiskWrites();
5974 try {
5975 File tracesDir = new File("/data/anr");
5976 File tracesFile = null;
5977 try {
5978 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5979
5980 StringBuilder sb = new StringBuilder();
5981 Time tobj = new Time();
5982 tobj.set(System.currentTimeMillis());
5983 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5984 sb.append(": ");
5985 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5986 sb.append(" since ");
5987 sb.append(msg);
5988 FileOutputStream fos = new FileOutputStream(tracesFile);
5989 fos.write(sb.toString().getBytes());
5990 if (app == null) {
5991 fos.write("\n*** No application process!".getBytes());
5992 }
5993 fos.close();
5994 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5995 } catch (IOException e) {
5996 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5997 return;
5998 }
5999
6000 if (app != null && app.getPid() > 0) {
6001 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6002 firstPids.add(app.getPid());
6003 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6004 }
6005
6006 File lastTracesFile = null;
6007 File curTracesFile = null;
6008 for (int i=9; i>=0; i--) {
6009 String name = String.format(Locale.US, "slow%02d.txt", i);
6010 curTracesFile = new File(tracesDir, name);
6011 if (curTracesFile.exists()) {
6012 if (lastTracesFile != null) {
6013 curTracesFile.renameTo(lastTracesFile);
6014 } else {
6015 curTracesFile.delete();
6016 }
6017 }
6018 lastTracesFile = curTracesFile;
6019 }
6020 tracesFile.renameTo(curTracesFile);
6021 } finally {
6022 StrictMode.setThreadPolicy(oldPolicy);
6023 }
6024 }
6025
Michal Karpinskida34cd42019-04-02 19:46:52 +01006026 boolean isAssociatedCompanionApp(int userId, int uid) {
6027 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6028 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006029 return false;
6030 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006031 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006032 }
6033
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006034 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006036
6037
Wale Ogunwale98875612018-10-12 07:53:02 -07006038 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6039 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006040
Riddle Hsud93a6c42018-11-29 21:50:06 +08006041 H(Looper looper) {
6042 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006043 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044
6045 @Override
6046 public void handleMessage(Message msg) {
6047 switch (msg.what) {
6048 case REPORT_TIME_TRACKER_MSG: {
6049 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6050 tracker.deliverResult(mContext);
6051 } break;
6052 }
6053 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006054 }
6055
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006056 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058
6059 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006060 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006061 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006062
6063 @Override
6064 public void handleMessage(Message msg) {
6065 switch (msg.what) {
6066 case DISMISS_DIALOG_UI_MSG: {
6067 final Dialog d = (Dialog) msg.obj;
6068 d.dismiss();
6069 break;
6070 }
6071 }
6072 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006073 }
6074
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 final class LocalService extends ActivityTaskManagerInternal {
6076 @Override
6077 public SleepToken acquireSleepToken(String tag, int displayId) {
6078 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006080 }
6081
6082 @Override
6083 public ComponentName getHomeActivityForUser(int userId) {
6084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006085 final ActivityRecord homeActivity =
6086 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006087 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006088 }
6089 }
6090
6091 @Override
6092 public void onLocalVoiceInteractionStarted(IBinder activity,
6093 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6094 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006095 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006096 }
6097 }
6098
6099 @Override
6100 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6101 synchronized (mGlobalLock) {
6102 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6103 reasons, timestamp);
6104 }
6105 }
6106
6107 @Override
6108 public void notifyAppTransitionFinished() {
6109 synchronized (mGlobalLock) {
6110 mStackSupervisor.notifyAppTransitionDone();
6111 }
6112 }
6113
6114 @Override
6115 public void notifyAppTransitionCancelled() {
6116 synchronized (mGlobalLock) {
6117 mStackSupervisor.notifyAppTransitionDone();
6118 }
6119 }
6120
6121 @Override
6122 public List<IBinder> getTopVisibleActivities() {
6123 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006124 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 }
6126 }
6127
6128 @Override
6129 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6130 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006131 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006132 }
6133 }
6134
6135 @Override
6136 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6137 Bundle bOptions) {
6138 Preconditions.checkNotNull(intents, "intents");
6139 final String[] resolvedTypes = new String[intents.length];
6140
6141 // UID of the package on user userId.
6142 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6143 // packageUid may not be initialized.
6144 int packageUid = 0;
6145 final long ident = Binder.clearCallingIdentity();
6146
6147 try {
6148 for (int i = 0; i < intents.length; i++) {
6149 resolvedTypes[i] =
6150 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6151 }
6152
6153 packageUid = AppGlobals.getPackageManager().getPackageUid(
6154 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6155 } catch (RemoteException e) {
6156 // Shouldn't happen.
6157 } finally {
6158 Binder.restoreCallingIdentity(ident);
6159 }
6160
Riddle Hsu591bf612019-02-14 17:55:31 +08006161 return getActivityStartController().startActivitiesInPackage(
6162 packageUid, packageName,
6163 intents, resolvedTypes, null /* resultTo */,
6164 SafeActivityOptions.fromBundle(bOptions), userId,
6165 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6166 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 }
6168
6169 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006170 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6171 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6172 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6173 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006174 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006175 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006176 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6177 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6178 userId, validateIncomingUser, originatingPendingIntent,
6179 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006180 }
6181 }
6182
6183 @Override
6184 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6185 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6186 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6187 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006188 PendingIntentRecord originatingPendingIntent,
6189 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006190 synchronized (mGlobalLock) {
6191 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6192 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6193 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006194 validateIncomingUser, originatingPendingIntent,
6195 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006196 }
6197 }
6198
6199 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006200 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6201 Intent intent, Bundle options, int userId) {
6202 return ActivityTaskManagerService.this.startActivityAsUser(
6203 caller, callerPacakge, intent,
6204 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6205 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6206 false /*validateIncomingUser*/);
6207 }
6208
6209 @Override
lumark588a3e82018-07-20 18:53:54 +08006210 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 synchronized (mGlobalLock) {
6212
6213 // We might change the visibilities here, so prepare an empty app transition which
6214 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006215 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006216 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006217 if (activityDisplay == null) {
6218 return;
6219 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006220 final DisplayContent dc = activityDisplay.mDisplayContent;
6221 final boolean wasTransitionSet =
6222 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006224 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006226 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227
6228 // If there was a transition set already we don't want to interfere with it as we
6229 // might be starting it too early.
6230 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006231 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 }
6233 }
6234 if (callback != null) {
6235 callback.run();
6236 }
6237 }
6238
6239 @Override
6240 public void notifyKeyguardTrustedChanged() {
6241 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006242 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006243 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006244 }
6245 }
6246 }
6247
6248 /**
6249 * Called after virtual display Id is updated by
6250 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6251 * {@param vrVr2dDisplayId}.
6252 */
6253 @Override
6254 public void setVr2dDisplayId(int vr2dDisplayId) {
6255 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6256 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006257 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258 }
6259 }
6260
6261 @Override
6262 public void setFocusedActivity(IBinder token) {
6263 synchronized (mGlobalLock) {
6264 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6265 if (r == null) {
6266 throw new IllegalArgumentException(
6267 "setFocusedActivity: No activity record matching token=" + token);
6268 }
Louis Chang19443452018-10-09 12:10:21 +08006269 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006270 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006271 }
6272 }
6273 }
6274
6275 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006277 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006278 }
6279
6280 @Override
6281 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006282 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
6284
6285 @Override
6286 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006287 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288 }
6289
6290 @Override
6291 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6292 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6293 }
6294
6295 @Override
6296 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006297 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006299
6300 @Override
6301 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6302 synchronized (mGlobalLock) {
6303 mActiveVoiceInteractionServiceComponent = component;
6304 }
6305 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006306
6307 @Override
6308 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6309 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6310 return;
6311 }
6312 synchronized (mGlobalLock) {
6313 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6314 if (types == null) {
6315 if (uid < 0) {
6316 return;
6317 }
6318 types = new ArrayMap<>();
6319 mAllowAppSwitchUids.put(userId, types);
6320 }
6321 if (uid < 0) {
6322 types.remove(type);
6323 } else {
6324 types.put(type, uid);
6325 }
6326 }
6327 }
6328
6329 @Override
6330 public void onUserStopped(int userId) {
6331 synchronized (mGlobalLock) {
6332 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6333 mAllowAppSwitchUids.remove(userId);
6334 }
6335 }
6336
6337 @Override
6338 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6339 synchronized (mGlobalLock) {
6340 return ActivityTaskManagerService.this.isGetTasksAllowed(
6341 caller, callingPid, callingUid);
6342 }
6343 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006344
Riddle Hsua0536432019-02-16 00:38:59 +08006345 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006346 @Override
6347 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006348 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349 mProcessNames.put(proc.mName, proc.mUid, proc);
6350 }
6351 }
6352
Riddle Hsua0536432019-02-16 00:38:59 +08006353 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006354 @Override
6355 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006356 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 mProcessNames.remove(name, uid);
6358 }
6359 }
6360
Riddle Hsua0536432019-02-16 00:38:59 +08006361 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006362 @Override
6363 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 if (proc == mHomeProcess) {
6366 mHomeProcess = null;
6367 }
6368 if (proc == mPreviousProcess) {
6369 mPreviousProcess = null;
6370 }
6371 }
6372 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006373
Riddle Hsua0536432019-02-16 00:38:59 +08006374 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006375 @Override
6376 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006377 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 return mTopProcessState;
6379 }
6380 }
6381
Riddle Hsua0536432019-02-16 00:38:59 +08006382 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006383 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006384 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006385 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006386 return proc == mHeavyWeightProcess;
6387 }
6388 }
6389
Riddle Hsua0536432019-02-16 00:38:59 +08006390 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006391 @Override
6392 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006393 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6395 }
6396 }
6397
6398 @Override
6399 public void finishHeavyWeightApp() {
6400 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006401 if (mHeavyWeightProcess != null) {
6402 mHeavyWeightProcess.finishActivities();
6403 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006404 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6405 mHeavyWeightProcess);
6406 }
6407 }
6408
Riddle Hsua0536432019-02-16 00:38:59 +08006409 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006410 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006411 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006412 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006413 return isSleepingLocked();
6414 }
6415 }
6416
6417 @Override
6418 public boolean isShuttingDown() {
6419 synchronized (mGlobalLock) {
6420 return mShuttingDown;
6421 }
6422 }
6423
6424 @Override
6425 public boolean shuttingDown(boolean booted, int timeout) {
6426 synchronized (mGlobalLock) {
6427 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006428 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006429 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006430 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006431 return mStackSupervisor.shutdownLocked(timeout);
6432 }
6433 }
6434
6435 @Override
6436 public void enableScreenAfterBoot(boolean booted) {
6437 synchronized (mGlobalLock) {
6438 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6439 SystemClock.uptimeMillis());
6440 mWindowManager.enableScreenAfterBoot();
6441 updateEventDispatchingLocked(booted);
6442 }
6443 }
6444
6445 @Override
6446 public boolean showStrictModeViolationDialog() {
6447 synchronized (mGlobalLock) {
6448 return mShowDialogs && !mSleeping && !mShuttingDown;
6449 }
6450 }
6451
6452 @Override
6453 public void showSystemReadyErrorDialogsIfNeeded() {
6454 synchronized (mGlobalLock) {
6455 try {
6456 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6457 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6458 + " data partition or your device will be unstable.");
6459 mUiHandler.post(() -> {
6460 if (mShowDialogs) {
6461 AlertDialog d = new BaseErrorDialog(mUiContext);
6462 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6463 d.setCancelable(false);
6464 d.setTitle(mUiContext.getText(R.string.android_system_label));
6465 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6466 d.setButton(DialogInterface.BUTTON_POSITIVE,
6467 mUiContext.getText(R.string.ok),
6468 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6469 d.show();
6470 }
6471 });
6472 }
6473 } catch (RemoteException e) {
6474 }
6475
6476 if (!Build.isBuildConsistent()) {
6477 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6478 mUiHandler.post(() -> {
6479 if (mShowDialogs) {
6480 AlertDialog d = new BaseErrorDialog(mUiContext);
6481 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6482 d.setCancelable(false);
6483 d.setTitle(mUiContext.getText(R.string.android_system_label));
6484 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6485 d.setButton(DialogInterface.BUTTON_POSITIVE,
6486 mUiContext.getText(R.string.ok),
6487 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6488 d.show();
6489 }
6490 });
6491 }
6492 }
6493 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006494
6495 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006496 public void onProcessMapped(int pid, WindowProcessController proc) {
6497 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006498 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006499 }
6500 }
6501
6502 @Override
6503 public void onProcessUnMapped(int pid) {
6504 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006505 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006506 }
6507 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006508
6509 @Override
6510 public void onPackageDataCleared(String name) {
6511 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006512 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006513 mAppWarnings.onPackageDataCleared(name);
6514 }
6515 }
6516
6517 @Override
6518 public void onPackageUninstalled(String name) {
6519 synchronized (mGlobalLock) {
6520 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006521 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006522 }
6523 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006524
6525 @Override
6526 public void onPackageAdded(String name, boolean replacing) {
6527 synchronized (mGlobalLock) {
6528 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6529 }
6530 }
6531
6532 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006533 public void onPackageReplaced(ApplicationInfo aInfo) {
6534 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006535 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006536 }
6537 }
6538
6539 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006540 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6541 synchronized (mGlobalLock) {
6542 return compatibilityInfoForPackageLocked(ai);
6543 }
6544 }
6545
Yunfan Chen75157d72018-07-27 14:47:21 +09006546 /**
6547 * Set the corresponding display information for the process global configuration. To be
6548 * called when we need to show IME on a different display.
6549 *
6550 * @param pid The process id associated with the IME window.
6551 * @param displayId The ID of the display showing the IME.
6552 */
6553 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006554 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006555 // Don't update process-level configuration for Multi-Client IME process since other
6556 // IMEs on other displays will also receive this configuration change due to IME
6557 // services use the same application config/context.
6558 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006559
Yunfan Chen75157d72018-07-27 14:47:21 +09006560 if (pid == MY_PID || pid < 0) {
6561 if (DEBUG_CONFIGURATION) {
6562 Slog.w(TAG,
6563 "Trying to update display configuration for system/invalid process.");
6564 }
6565 return;
6566 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006567 synchronized (mGlobalLock) {
6568 final ActivityDisplay activityDisplay =
6569 mRootActivityContainer.getActivityDisplay(displayId);
6570 if (activityDisplay == null) {
6571 // Call might come when display is not yet added or has been removed.
6572 if (DEBUG_CONFIGURATION) {
6573 Slog.w(TAG, "Trying to update display configuration for non-existing "
6574 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006575 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006576 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006577 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006578 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006579 if (process == null) {
6580 if (DEBUG_CONFIGURATION) {
6581 Slog.w(TAG, "Trying to update display configuration for invalid "
6582 + "process, pid=" + pid);
6583 }
6584 return;
6585 }
6586 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6587 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006588 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006589
6590 @Override
6591 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6592 int requestCode, int resultCode, Intent data) {
6593 synchronized (mGlobalLock) {
6594 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006595 if (r != null && r.getActivityStack() != null) {
6596 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6597 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006598 }
6599 }
6600 }
6601
6602 @Override
6603 public void clearPendingResultForActivity(IBinder activityToken,
6604 WeakReference<PendingIntentRecord> pir) {
6605 synchronized (mGlobalLock) {
6606 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6607 if (r != null && r.pendingResults != null) {
6608 r.pendingResults.remove(pir);
6609 }
6610 }
6611 }
6612
6613 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006614 public ActivityTokens getTopActivityForTask(int taskId) {
6615 synchronized (mGlobalLock) {
6616 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6617 if (taskRecord == null) {
6618 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6619 + " Requested task not found");
6620 return null;
6621 }
6622 final ActivityRecord activity = taskRecord.getTopActivity();
6623 if (activity == null) {
6624 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6625 + " Requested activity not found");
6626 return null;
6627 }
6628 if (!activity.attachedToProcess()) {
6629 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6630 + activity);
6631 return null;
6632 }
6633 return new ActivityTokens(activity.appToken, activity.assistToken,
6634 activity.app.getThread());
6635 }
6636 }
6637
6638 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006639 public IIntentSender getIntentSender(int type, String packageName,
6640 int callingUid, int userId, IBinder token, String resultWho,
6641 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6642 Bundle bOptions) {
6643 synchronized (mGlobalLock) {
6644 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6645 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6646 }
6647 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006648
6649 @Override
6650 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6651 synchronized (mGlobalLock) {
6652 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6653 if (r == null) {
6654 return null;
6655 }
6656 if (r.mServiceConnectionsHolder == null) {
6657 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6658 ActivityTaskManagerService.this, r);
6659 }
6660
6661 return r.mServiceConnectionsHolder;
6662 }
6663 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006664
6665 @Override
6666 public Intent getHomeIntent() {
6667 synchronized (mGlobalLock) {
6668 return ActivityTaskManagerService.this.getHomeIntent();
6669 }
6670 }
6671
6672 @Override
6673 public boolean startHomeActivity(int userId, String reason) {
6674 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006675 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006676 }
6677 }
6678
6679 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006680 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006681 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006682 synchronized (mGlobalLock) {
6683 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006684 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006685 }
Chilun8b1f1be2019-03-13 17:14:36 +08006686 }
6687
6688 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006689 public boolean startHomeOnAllDisplays(int userId, String reason) {
6690 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006691 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006692 }
6693 }
6694
Riddle Hsua0536432019-02-16 00:38:59 +08006695 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006696 @Override
6697 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006698 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006699 if (mFactoryTest == FACTORY_TEST_OFF) {
6700 return false;
6701 }
6702 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6703 && wpc.mName.equals(mTopComponent.getPackageName())) {
6704 return true;
6705 }
6706 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6707 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6708 }
6709 }
6710
6711 @Override
6712 public void updateTopComponentForFactoryTest() {
6713 synchronized (mGlobalLock) {
6714 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6715 return;
6716 }
6717 final ResolveInfo ri = mContext.getPackageManager()
6718 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6719 final CharSequence errorMsg;
6720 if (ri != null) {
6721 final ActivityInfo ai = ri.activityInfo;
6722 final ApplicationInfo app = ai.applicationInfo;
6723 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6724 mTopAction = Intent.ACTION_FACTORY_TEST;
6725 mTopData = null;
6726 mTopComponent = new ComponentName(app.packageName, ai.name);
6727 errorMsg = null;
6728 } else {
6729 errorMsg = mContext.getResources().getText(
6730 com.android.internal.R.string.factorytest_not_system);
6731 }
6732 } else {
6733 errorMsg = mContext.getResources().getText(
6734 com.android.internal.R.string.factorytest_no_action);
6735 }
6736 if (errorMsg == null) {
6737 return;
6738 }
6739
6740 mTopAction = null;
6741 mTopData = null;
6742 mTopComponent = null;
6743 mUiHandler.post(() -> {
6744 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6745 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006746 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006747 });
6748 }
6749 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750
Riddle Hsua0536432019-02-16 00:38:59 +08006751 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 @Override
6753 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6754 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006755 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006756 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006757 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758
6759 wpc.clearRecentTasks();
6760 wpc.clearActivities();
6761
6762 if (wpc.isInstrumenting()) {
6763 finishInstrumentationCallback.run();
6764 }
6765
Jorim Jaggid0752812018-10-16 16:07:20 +02006766 if (!restarting && hasVisibleActivities) {
6767 mWindowManager.deferSurfaceLayout();
6768 try {
6769 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6770 // If there was nothing to resume, and we are not already restarting
6771 // this process, but there is a visible activity that is hosted by the
6772 // process...then make sure all visible activities are running, taking
6773 // care of restarting this process.
6774 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6775 !PRESERVE_WINDOWS);
6776 }
6777 } finally {
6778 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 }
6781 }
6782 }
6783
6784 @Override
6785 public void closeSystemDialogs(String reason) {
6786 enforceNotIsolatedCaller("closeSystemDialogs");
6787
6788 final int pid = Binder.getCallingPid();
6789 final int uid = Binder.getCallingUid();
6790 final long origId = Binder.clearCallingIdentity();
6791 try {
6792 synchronized (mGlobalLock) {
6793 // Only allow this from foreground processes, so that background
6794 // applications can't abuse it to prevent system UI from being shown.
6795 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006796 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 if (!proc.isPerceptible()) {
6798 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6799 + " from background process " + proc);
6800 return;
6801 }
6802 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 mWindowManager.closeSystemDialogs(reason);
6804
Wale Ogunwaled32da472018-11-16 07:19:28 -08006805 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006807 // Call into AM outside the synchronized block.
6808 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 } finally {
6810 Binder.restoreCallingIdentity(origId);
6811 }
6812 }
6813
6814 @Override
6815 public void cleanupDisabledPackageComponents(
6816 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6817 synchronized (mGlobalLock) {
6818 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006819 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006821 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 mStackSupervisor.scheduleIdleLocked();
6823 }
6824
6825 // Clean-up disabled tasks
6826 getRecentTasks().cleanupDisabledPackageTasksLocked(
6827 packageName, disabledClasses, userId);
6828 }
6829 }
6830
6831 @Override
6832 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6833 int userId) {
6834 synchronized (mGlobalLock) {
6835
6836 boolean didSomething =
6837 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006838 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 null, doit, evenPersistent, userId);
6840 return didSomething;
6841 }
6842 }
6843
6844 @Override
6845 public void resumeTopActivities(boolean scheduleIdle) {
6846 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006847 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 if (scheduleIdle) {
6849 mStackSupervisor.scheduleIdleLocked();
6850 }
6851 }
6852 }
6853
Riddle Hsua0536432019-02-16 00:38:59 +08006854 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 @Override
6856 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006857 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6859 }
6860 }
6861
Riddle Hsua0536432019-02-16 00:38:59 +08006862 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 @Override
6864 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006865 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006866 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 }
6869
6870 @Override
6871 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6872 try {
6873 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6874 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6875 }
6876 } catch (RemoteException ex) {
6877 throw new SecurityException("Fail to check is caller a privileged app", ex);
6878 }
6879
6880 synchronized (mGlobalLock) {
6881 final long ident = Binder.clearCallingIdentity();
6882 try {
6883 if (mAmInternal.shouldConfirmCredentials(userId)) {
6884 if (mKeyguardController.isKeyguardLocked()) {
6885 // Showing launcher to avoid user entering credential twice.
6886 startHomeActivity(currentUserId, "notifyLockedProfile");
6887 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006888 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 }
6890 } finally {
6891 Binder.restoreCallingIdentity(ident);
6892 }
6893 }
6894 }
6895
6896 @Override
6897 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6898 mAmInternal.enforceCallingPermission(
6899 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6900
6901 synchronized (mGlobalLock) {
6902 final long ident = Binder.clearCallingIdentity();
6903 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006904 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6905 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6908 UserHandle.CURRENT);
6909 } finally {
6910 Binder.restoreCallingIdentity(ident);
6911 }
6912 }
6913 }
6914
6915 @Override
6916 public void writeActivitiesToProto(ProtoOutputStream proto) {
6917 synchronized (mGlobalLock) {
6918 // The output proto of "activity --proto activities"
6919 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006920 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006921 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6922 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 }
6924 }
6925
6926 @Override
6927 public void saveANRState(String reason) {
6928 synchronized (mGlobalLock) {
6929 final StringWriter sw = new StringWriter();
6930 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6931 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6932 if (reason != null) {
6933 pw.println(" Reason: " + reason);
6934 }
6935 pw.println();
6936 getActivityStartController().dump(pw, " ", null);
6937 pw.println();
6938 pw.println("-------------------------------------------------------------------------------");
6939 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6940 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6941 "" /* header */);
6942 pw.println();
6943 pw.close();
6944
6945 mLastANRState = sw.toString();
6946 }
6947 }
6948
6949 @Override
6950 public void clearSavedANRState() {
6951 synchronized (mGlobalLock) {
6952 mLastANRState = null;
6953 }
6954 }
6955
6956 @Override
6957 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6958 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6959 synchronized (mGlobalLock) {
6960 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6961 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6962 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6963 dumpLastANRLocked(pw);
6964 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6965 dumpLastANRTracesLocked(pw);
6966 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6967 dumpActivityStarterLocked(pw, dumpPackage);
6968 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6969 dumpActivityContainersLocked(pw);
6970 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6971 if (getRecentTasks() != null) {
6972 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6973 }
6974 }
6975 }
6976 }
6977
6978 @Override
6979 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6980 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6981 int wakefulness) {
6982 synchronized (mGlobalLock) {
6983 if (mHomeProcess != null && (dumpPackage == null
6984 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6985 if (needSep) {
6986 pw.println();
6987 needSep = false;
6988 }
6989 pw.println(" mHomeProcess: " + mHomeProcess);
6990 }
6991 if (mPreviousProcess != null && (dumpPackage == null
6992 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6993 if (needSep) {
6994 pw.println();
6995 needSep = false;
6996 }
6997 pw.println(" mPreviousProcess: " + mPreviousProcess);
6998 }
6999 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7000 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7001 StringBuilder sb = new StringBuilder(128);
7002 sb.append(" mPreviousProcessVisibleTime: ");
7003 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7004 pw.println(sb);
7005 }
7006 if (mHeavyWeightProcess != null && (dumpPackage == null
7007 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7008 if (needSep) {
7009 pw.println();
7010 needSep = false;
7011 }
7012 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7013 }
7014 if (dumpPackage == null) {
7015 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007016 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 }
7018 if (dumpAll) {
7019 if (dumpPackage == null) {
7020 pw.println(" mConfigWillChange: "
7021 + getTopDisplayFocusedStack().mConfigWillChange);
7022 }
7023 if (mCompatModePackages.getPackages().size() > 0) {
7024 boolean printed = false;
7025 for (Map.Entry<String, Integer> entry
7026 : mCompatModePackages.getPackages().entrySet()) {
7027 String pkg = entry.getKey();
7028 int mode = entry.getValue();
7029 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7030 continue;
7031 }
7032 if (!printed) {
7033 pw.println(" mScreenCompatPackages:");
7034 printed = true;
7035 }
7036 pw.println(" " + pkg + ": " + mode);
7037 }
7038 }
7039 }
7040
7041 if (dumpPackage == null) {
7042 pw.println(" mWakefulness="
7043 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007044 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007045 if (mRunningVoice != null) {
7046 pw.println(" mRunningVoice=" + mRunningVoice);
7047 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7048 }
7049 pw.println(" mSleeping=" + mSleeping);
7050 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7051 pw.println(" mVrController=" + mVrController);
7052 }
7053 if (mCurAppTimeTracker != null) {
7054 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7055 }
7056 if (mAllowAppSwitchUids.size() > 0) {
7057 boolean printed = false;
7058 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7059 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7060 for (int j = 0; j < types.size(); j++) {
7061 if (dumpPackage == null ||
7062 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7063 if (needSep) {
7064 pw.println();
7065 needSep = false;
7066 }
7067 if (!printed) {
7068 pw.println(" mAllowAppSwitchUids:");
7069 printed = true;
7070 }
7071 pw.print(" User ");
7072 pw.print(mAllowAppSwitchUids.keyAt(i));
7073 pw.print(": Type ");
7074 pw.print(types.keyAt(j));
7075 pw.print(" = ");
7076 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7077 pw.println();
7078 }
7079 }
7080 }
7081 }
7082 if (dumpPackage == null) {
7083 if (mController != null) {
7084 pw.println(" mController=" + mController
7085 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7086 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007087 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7088 pw.println(" mLaunchingActivityWakeLock="
7089 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 }
7091
7092 return needSep;
7093 }
7094 }
7095
7096 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007097 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7098 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 synchronized (mGlobalLock) {
7100 if (dumpPackage == null) {
7101 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7102 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007103 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7104 if (mRunningVoice != null) {
7105 final long vrToken = proto.start(
7106 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7107 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7108 mRunningVoice.toString());
7109 mVoiceWakeLock.writeToProto(
7110 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7111 proto.end(vrToken);
7112 }
7113 mVrController.writeToProto(proto,
7114 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 if (mController != null) {
7116 final long token = proto.start(CONTROLLER);
7117 proto.write(CONTROLLER, mController.toString());
7118 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7119 proto.end(token);
7120 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007121 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7122 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7123 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125
7126 if (mHomeProcess != null && (dumpPackage == null
7127 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007128 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 }
7130
7131 if (mPreviousProcess != null && (dumpPackage == null
7132 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007133 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7135 }
7136
7137 if (mHeavyWeightProcess != null && (dumpPackage == null
7138 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007139 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141
7142 for (Map.Entry<String, Integer> entry
7143 : mCompatModePackages.getPackages().entrySet()) {
7144 String pkg = entry.getKey();
7145 int mode = entry.getValue();
7146 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7147 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7148 proto.write(PACKAGE, pkg);
7149 proto.write(MODE, mode);
7150 proto.end(compatToken);
7151 }
7152 }
7153
7154 if (mCurAppTimeTracker != null) {
7155 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7156 }
7157
7158 }
7159 }
7160
7161 @Override
7162 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7163 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7164 boolean dumpFocusedStackOnly) {
7165 synchronized (mGlobalLock) {
7166 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7167 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7168 }
7169 }
7170
7171 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007172 public void dumpForOom(PrintWriter pw) {
7173 synchronized (mGlobalLock) {
7174 pw.println(" mHomeProcess: " + mHomeProcess);
7175 pw.println(" mPreviousProcess: " + mPreviousProcess);
7176 if (mHeavyWeightProcess != null) {
7177 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7178 }
7179 }
7180 }
7181
7182 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 public boolean canGcNow() {
7184 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007185 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 }
7187 }
7188
Riddle Hsua0536432019-02-16 00:38:59 +08007189 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 @Override
7191 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007192 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007193 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 return top != null ? top.app : null;
7195 }
7196 }
7197
Riddle Hsua0536432019-02-16 00:38:59 +08007198 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 @Override
7200 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007201 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007202 if (mRootActivityContainer != null) {
7203 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 }
7205 }
7206 }
7207
7208 @Override
7209 public void scheduleDestroyAllActivities(String reason) {
7210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007211 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 }
7213 }
7214
7215 @Override
7216 public void removeUser(int userId) {
7217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007218 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 }
7220 }
7221
7222 @Override
7223 public boolean switchUser(int userId, UserState userState) {
7224 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007225 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007226 }
7227 }
7228
7229 @Override
7230 public void onHandleAppCrash(WindowProcessController wpc) {
7231 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007232 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007233 }
7234 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007235
7236 @Override
7237 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7238 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007239 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007240 }
7241 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007242
Riddle Hsua0536432019-02-16 00:38:59 +08007243 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007244 @Override
7245 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007246 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007247 }
7248
Riddle Hsua0536432019-02-16 00:38:59 +08007249 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007250 @Override
7251 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007252 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007253 }
7254
Riddle Hsua0536432019-02-16 00:38:59 +08007255 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007256 @Override
7257 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007258 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007259 }
7260
Riddle Hsua0536432019-02-16 00:38:59 +08007261 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007262 @Override
7263 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007264 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007265 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007266
7267 @Override
7268 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007269 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007270 mPendingTempWhitelist.put(uid, tag);
7271 }
7272 }
7273
7274 @Override
7275 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007277 mPendingTempWhitelist.remove(uid);
7278 }
7279 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007280
7281 @Override
7282 public boolean handleAppCrashInActivityController(String processName, int pid,
7283 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7284 Runnable killCrashingAppCallback) {
7285 synchronized (mGlobalLock) {
7286 if (mController == null) {
7287 return false;
7288 }
7289
7290 try {
7291 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7292 stackTrace)) {
7293 killCrashingAppCallback.run();
7294 return true;
7295 }
7296 } catch (RemoteException e) {
7297 mController = null;
7298 Watchdog.getInstance().setActivityController(null);
7299 }
7300 return false;
7301 }
7302 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007303
7304 @Override
7305 public void removeRecentTasksByPackageName(String packageName, int userId) {
7306 synchronized (mGlobalLock) {
7307 mRecentTasks.removeTasksByPackageName(packageName, userId);
7308 }
7309 }
7310
7311 @Override
7312 public void cleanupRecentTasksForUser(int userId) {
7313 synchronized (mGlobalLock) {
7314 mRecentTasks.cleanupLocked(userId);
7315 }
7316 }
7317
7318 @Override
7319 public void loadRecentTasksForUser(int userId) {
7320 synchronized (mGlobalLock) {
7321 mRecentTasks.loadUserRecentsLocked(userId);
7322 }
7323 }
7324
7325 @Override
7326 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7327 synchronized (mGlobalLock) {
7328 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7329 }
7330 }
7331
7332 @Override
7333 public void flushRecentTasks() {
7334 mRecentTasks.flush();
7335 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007336
7337 @Override
7338 public WindowProcessController getHomeProcess() {
7339 synchronized (mGlobalLock) {
7340 return mHomeProcess;
7341 }
7342 }
7343
7344 @Override
7345 public WindowProcessController getPreviousProcess() {
7346 synchronized (mGlobalLock) {
7347 return mPreviousProcess;
7348 }
7349 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007350
7351 @Override
7352 public void clearLockedTasks(String reason) {
7353 synchronized (mGlobalLock) {
7354 getLockTaskController().clearLockedTasks(reason);
7355 }
7356 }
7357
7358 @Override
7359 public void updateUserConfiguration() {
7360 synchronized (mGlobalLock) {
7361 final Configuration configuration = new Configuration(getGlobalConfiguration());
7362 final int currentUserId = mAmInternal.getCurrentUserId();
7363 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7364 configuration, currentUserId, Settings.System.canWrite(mContext));
7365 updateConfigurationLocked(configuration, null /* starting */,
7366 false /* initLocale */, false /* persistent */, currentUserId,
7367 false /* deferResume */);
7368 }
7369 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007370
7371 @Override
7372 public boolean canShowErrorDialogs() {
7373 synchronized (mGlobalLock) {
7374 return mShowDialogs && !mSleeping && !mShuttingDown
7375 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7376 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7377 mAmInternal.getCurrentUserId())
7378 && !(UserManager.isDeviceInDemoMode(mContext)
7379 && mAmInternal.getCurrentUser().isDemo());
7380 }
7381 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007382
7383 @Override
7384 public void setProfileApp(String profileApp) {
7385 synchronized (mGlobalLock) {
7386 mProfileApp = profileApp;
7387 }
7388 }
7389
7390 @Override
7391 public void setProfileProc(WindowProcessController wpc) {
7392 synchronized (mGlobalLock) {
7393 mProfileProc = wpc;
7394 }
7395 }
7396
7397 @Override
7398 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7399 synchronized (mGlobalLock) {
7400 mProfilerInfo = profilerInfo;
7401 }
7402 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007403
7404 @Override
7405 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7406 synchronized (mGlobalLock) {
7407 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7408 }
7409 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007410
7411 @Override
7412 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7413 synchronized (mGlobalLock) {
7414 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7415 }
7416 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007417
7418 @Override
7419 public boolean isUidForeground(int uid) {
7420 synchronized (mGlobalLock) {
7421 return ActivityTaskManagerService.this.isUidForeground(uid);
7422 }
7423 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007424
7425 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007426 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007427 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007428 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007429 }
7430 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007431
7432 @Override
7433 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007434 // Translate package names into UIDs
7435 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007436 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007437 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7438 if (uid >= 0) {
7439 result.add(uid);
7440 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007441 }
7442 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007443 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007444 }
7445 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007446 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007447}