blob: f58aea3c4ab15e1c6ac7269db49642d8ee1d6fb8 [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
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
553 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
602 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
603 // automatically. Important for devices without direct input devices.
604 private boolean mShowDialogs = true;
605
606 /** Set if we are shutting down the system, similar to sleeping. */
607 boolean mShuttingDown = false;
608
609 /**
610 * We want to hold a wake lock while running a voice interaction session, since
611 * this may happen with the screen off and we need to keep the CPU running to
612 * be able to continue to interact with the user.
613 */
614 PowerManager.WakeLock mVoiceWakeLock;
615
616 /**
617 * Set while we are running a voice interaction. This overrides sleeping while it is active.
618 */
619 IVoiceInteractionSession mRunningVoice;
620
621 /**
622 * The last resumed activity. This is identical to the current resumed activity most
623 * of the time but could be different when we're pausing one activity before we resume
624 * another activity.
625 */
626 ActivityRecord mLastResumedActivity;
627
628 /**
629 * The activity that is currently being traced as the active resumed activity.
630 *
631 * @see #updateResumedAppTrace
632 */
633 private @Nullable ActivityRecord mTracedResumedActivity;
634
635 /** If non-null, we are tracking the time the user spends in the currently focused app. */
636 AppTimeTracker mCurAppTimeTracker;
637
Wale Ogunwale008163e2018-07-23 23:11:08 -0700638 private AppWarnings mAppWarnings;
639
Wale Ogunwale53783742018-09-16 10:21:51 -0700640 /**
641 * Packages that the user has asked to have run in screen size
642 * compatibility mode instead of filling the screen.
643 */
644 CompatModePackages mCompatModePackages;
645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private FontScaleSettingObserver mFontScaleSettingObserver;
647
Ricky Wai96f5c352019-04-10 18:40:17 +0100648 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000649
Wale Ogunwalef6733932018-06-27 05:14:34 -0700650 private final class FontScaleSettingObserver extends ContentObserver {
651 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
652 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
653
654 public FontScaleSettingObserver() {
655 super(mH);
656 final ContentResolver resolver = mContext.getContentResolver();
657 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
658 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
659 UserHandle.USER_ALL);
660 }
661
662 @Override
663 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
664 if (mFontScaleUri.equals(uri)) {
665 updateFontScaleIfNeeded(userId);
666 } else if (mHideErrorDialogsUri.equals(uri)) {
667 synchronized (mGlobalLock) {
668 updateShouldShowDialogsLocked(getGlobalConfiguration());
669 }
670 }
671 }
672 }
673
Riddle Hsua0536432019-02-16 00:38:59 +0800674 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
675 @Target(ElementType.METHOD)
676 @Retention(RetentionPolicy.SOURCE)
677 @interface HotPath {
678 int NONE = 0;
679 int OOM_ADJUSTMENT = 1;
680 int LRU_UPDATE = 2;
681 int PROCESS_CHANGE = 3;
682 int caller() default NONE;
683 }
684
Charles Chen8d98dd22018-12-26 17:36:54 +0800685 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
686 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700687 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700688 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 mSystemThread = ActivityThread.currentActivityThread();
690 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700691 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800692 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700693 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void onSystemReady() {
697 synchronized (mGlobalLock) {
698 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
699 PackageManager.FEATURE_CANT_SAVE_STATE);
700 mAssistUtils = new AssistUtils(mContext);
701 mVrController.onSystemReady();
702 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700703 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void onInitPowerManagement() {
708 synchronized (mGlobalLock) {
709 mStackSupervisor.initPowerManagement();
710 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
711 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
712 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
713 mVoiceWakeLock.setReferenceCounted(false);
714 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700718 mFontScaleSettingObserver = new FontScaleSettingObserver();
719 }
720
Wale Ogunwale59507092018-10-29 09:00:30 -0700721 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722 final boolean freeformWindowManagement =
723 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
724 || Settings.Global.getInt(
725 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
726
727 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
728 final boolean supportsPictureInPicture = supportsMultiWindow &&
729 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
730 final boolean supportsSplitScreenMultiWindow =
731 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
732 final boolean supportsMultiDisplay = mContext.getPackageManager()
733 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
735 final boolean forceResizable = Settings.Global.getInt(
736 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700737 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738
739 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900740 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700741
742 final Configuration configuration = new Configuration();
743 Settings.System.getConfiguration(resolver, configuration);
744 if (forceRtl) {
745 // This will take care of setting the correct layout direction flags
746 configuration.setLayoutDirection(configuration.locale);
747 }
748
749 synchronized (mGlobalLock) {
750 mForceResizableActivities = forceResizable;
751 final boolean multiWindowFormEnabled = freeformWindowManagement
752 || supportsSplitScreenMultiWindow
753 || supportsPictureInPicture
754 || supportsMultiDisplay;
755 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
756 mSupportsMultiWindow = true;
757 mSupportsFreeformWindowManagement = freeformWindowManagement;
758 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
759 mSupportsPictureInPicture = supportsPictureInPicture;
760 mSupportsMultiDisplay = supportsMultiDisplay;
761 } else {
762 mSupportsMultiWindow = false;
763 mSupportsFreeformWindowManagement = false;
764 mSupportsSplitScreenMultiWindow = false;
765 mSupportsPictureInPicture = false;
766 mSupportsMultiDisplay = false;
767 }
768 mWindowManager.setForceResizableTasks(mForceResizableActivities);
769 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700770 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
771 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700772 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 // This happens before any activities are started, so we can change global configuration
774 // in-place.
775 updateConfigurationLocked(configuration, null, true);
776 final Configuration globalConfig = getGlobalConfiguration();
777 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
778
779 // Load resources only after the current configuration has been set.
780 final Resources res = mContext.getResources();
781 mThumbnailWidth = res.getDimensionPixelSize(
782 com.android.internal.R.dimen.thumbnail_width);
783 mThumbnailHeight = res.getDimensionPixelSize(
784 com.android.internal.R.dimen.thumbnail_height);
785
786 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
787 mFullscreenThumbnailScale = (float) res
788 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
789 (float) globalConfig.screenWidthDp;
790 } else {
791 mFullscreenThumbnailScale = res.getFraction(
792 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
793 }
794 }
795 }
796
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800797 public WindowManagerGlobalLock getGlobalLock() {
798 return mGlobalLock;
799 }
800
Yunfan Chen585f2932019-01-29 16:04:45 +0900801 /** For test purpose only. */
802 @VisibleForTesting
803 public ActivityTaskManagerInternal getAtmInternal() {
804 return mInternal;
805 }
806
Riddle Hsud93a6c42018-11-29 21:50:06 +0800807 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
808 Looper looper) {
809 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700812 final File systemDir = SystemServiceManager.ensureSystemDir();
813 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
814 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700815 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700816
817 mTempConfig.setToDefaults();
818 mTempConfig.setLocales(LocaleList.getDefault());
819 mConfigurationSeq = mTempConfig.seq = 1;
820 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800821 mRootActivityContainer = new RootActivityContainer(this);
822 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700824 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700826 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700827 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700828 mRecentTasks = createRecentTasks();
829 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700831 mKeyguardController = mStackSupervisor.getKeyguardController();
832 }
833
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700834 public void onActivityManagerInternalAdded() {
835 synchronized (mGlobalLock) {
836 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
837 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
838 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700839 }
840
Yunfan Chen75157d72018-07-27 14:47:21 +0900841 int increaseConfigurationSeqLocked() {
842 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
843 return mConfigurationSeq;
844 }
845
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700846 protected ActivityStackSupervisor createStackSupervisor() {
847 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
848 supervisor.initialize();
849 return supervisor;
850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setWindowManager(WindowManagerService wm) {
853 synchronized (mGlobalLock) {
854 mWindowManager = wm;
855 mLockTaskController.setWindowManager(wm);
856 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800857 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 }
860
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700861 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
862 synchronized (mGlobalLock) {
863 mUsageStatsInternal = usageStatsManager;
864 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700865 }
866
Wale Ogunwalef6733932018-06-27 05:14:34 -0700867 UserManagerService getUserManager() {
868 if (mUserManager == null) {
869 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
870 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
871 }
872 return mUserManager;
873 }
874
875 AppOpsService getAppOpsService() {
876 if (mAppOpsService == null) {
877 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
878 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
879 }
880 return mAppOpsService;
881 }
882
883 boolean hasUserRestriction(String restriction, int userId) {
884 return getUserManager().hasUserRestriction(restriction, userId);
885 }
886
Michal Karpinski15486842019-04-25 17:33:42 +0100887 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
888 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
889 callingUid, callingPackage);
890 if (mode == AppOpsManager.MODE_DEFAULT) {
891 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
892 == PERMISSION_GRANTED;
893 }
894 return mode == AppOpsManager.MODE_ALLOWED;
895 }
896
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700897 protected RecentTasks createRecentTasks() {
898 return new RecentTasks(this, mStackSupervisor);
899 }
900
901 RecentTasks getRecentTasks() {
902 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 ClientLifecycleManager getLifecycleManager() {
906 return mLifecycleManager;
907 }
908
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700909 ActivityStartController getActivityStartController() {
910 return mActivityStartController;
911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 TaskChangeNotificationController getTaskChangeNotificationController() {
914 return mTaskChangeNotificationController;
915 }
916
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700917 LockTaskController getLockTaskController() {
918 return mLockTaskController;
919 }
920
Yunfan Chen75157d72018-07-27 14:47:21 +0900921 /**
922 * Return the global configuration used by the process corresponding to the input pid. This is
923 * usually the global configuration with some overrides specific to that process.
924 */
925 Configuration getGlobalConfigurationForCallingPid() {
926 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800927 return getGlobalConfigurationForPid(pid);
928 }
929
930 /**
931 * Return the global configuration used by the process corresponding to the given pid.
932 */
933 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900934 if (pid == MY_PID || pid < 0) {
935 return getGlobalConfiguration();
936 }
937 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100938 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 return app != null ? app.getConfiguration() : getGlobalConfiguration();
940 }
941 }
942
943 /**
944 * Return the device configuration info used by the process corresponding to the input pid.
945 * The value is consistent with the global configuration for the process.
946 */
947 @Override
948 public ConfigurationInfo getDeviceConfigurationInfo() {
949 ConfigurationInfo config = new ConfigurationInfo();
950 synchronized (mGlobalLock) {
951 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
952 config.reqTouchScreen = globalConfig.touchscreen;
953 config.reqKeyboardType = globalConfig.keyboard;
954 config.reqNavigation = globalConfig.navigation;
955 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
956 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
958 }
959 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
960 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
961 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
962 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700963 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900964 }
965 return config;
966 }
967
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700968 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700969 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700970 }
971
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700972 public static final class Lifecycle extends SystemService {
973 private final ActivityTaskManagerService mService;
974
975 public Lifecycle(Context context) {
976 super(context);
977 mService = new ActivityTaskManagerService(context);
978 }
979
980 @Override
981 public void onStart() {
982 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700983 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700984 }
985
Garfield Tan891146c2018-10-09 12:14:00 -0700986 @Override
987 public void onUnlockUser(int userId) {
988 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800989 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700990 }
991 }
992
993 @Override
994 public void onCleanupUser(int userId) {
995 synchronized (mService.getGlobalLock()) {
996 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
997 }
998 }
999
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 public ActivityTaskManagerService getService() {
1001 return mService;
1002 }
1003 }
1004
1005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 public final int startActivity(IApplicationThread caller, String callingPackage,
1007 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1008 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1009 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1010 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1011 UserHandle.getCallingUserId());
1012 }
1013
1014 @Override
1015 public final int startActivities(IApplicationThread caller, String callingPackage,
1016 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1017 int userId) {
1018 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001019 enforceNotIsolatedCaller(reason);
1020 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001022 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1023 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1024 reason, null /* originatingPendingIntent */,
1025 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 }
1027
1028 @Override
1029 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1030 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1032 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1033 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1034 true /*validateIncomingUser*/);
1035 }
1036
1037 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1040 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001043 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1045
1046 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001047 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 .setCaller(caller)
1049 .setCallingPackage(callingPackage)
1050 .setResolvedType(resolvedType)
1051 .setResultTo(resultTo)
1052 .setResultWho(resultWho)
1053 .setRequestCode(requestCode)
1054 .setStartFlags(startFlags)
1055 .setProfilerInfo(profilerInfo)
1056 .setActivityOptions(bOptions)
1057 .setMayWait(userId)
1058 .execute();
1059
1060 }
1061
1062 @Override
1063 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1064 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1066 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 // Refuse possible leaked file descriptors
1068 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1069 throw new IllegalArgumentException("File descriptors passed in Intent");
1070 }
1071
1072 if (!(target instanceof PendingIntentRecord)) {
1073 throw new IllegalArgumentException("Bad PendingIntent object");
1074 }
1075
1076 PendingIntentRecord pir = (PendingIntentRecord)target;
1077
1078 synchronized (mGlobalLock) {
1079 // If this is coming from the currently resumed activity, it is
1080 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001081 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 if (stack.mResumedActivity != null &&
1083 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001084 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 }
1086 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001087 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 }
1090
1091 @Override
1092 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1093 Bundle bOptions) {
1094 // Refuse possible leaked file descriptors
1095 if (intent != null && intent.hasFileDescriptors()) {
1096 throw new IllegalArgumentException("File descriptors passed in Intent");
1097 }
1098 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1099
1100 synchronized (mGlobalLock) {
1101 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1102 if (r == null) {
1103 SafeActivityOptions.abort(options);
1104 return false;
1105 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001106 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 // The caller is not running... d'oh!
1108 SafeActivityOptions.abort(options);
1109 return false;
1110 }
1111 intent = new Intent(intent);
1112 // The caller is not allowed to change the data.
1113 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1114 // And we are resetting to find the next component...
1115 intent.setComponent(null);
1116
1117 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1118
1119 ActivityInfo aInfo = null;
1120 try {
1121 List<ResolveInfo> resolves =
1122 AppGlobals.getPackageManager().queryIntentActivities(
1123 intent, r.resolvedType,
1124 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1125 UserHandle.getCallingUserId()).getList();
1126
1127 // Look for the original activity in the list...
1128 final int N = resolves != null ? resolves.size() : 0;
1129 for (int i=0; i<N; i++) {
1130 ResolveInfo rInfo = resolves.get(i);
1131 if (rInfo.activityInfo.packageName.equals(r.packageName)
1132 && rInfo.activityInfo.name.equals(r.info.name)) {
1133 // We found the current one... the next matching is
1134 // after it.
1135 i++;
1136 if (i<N) {
1137 aInfo = resolves.get(i).activityInfo;
1138 }
1139 if (debug) {
1140 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1141 + "/" + r.info.name);
1142 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1143 ? "null" : aInfo.packageName + "/" + aInfo.name));
1144 }
1145 break;
1146 }
1147 }
1148 } catch (RemoteException e) {
1149 }
1150
1151 if (aInfo == null) {
1152 // Nobody who is next!
1153 SafeActivityOptions.abort(options);
1154 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1155 return false;
1156 }
1157
1158 intent.setComponent(new ComponentName(
1159 aInfo.applicationInfo.packageName, aInfo.name));
1160 intent.setFlags(intent.getFlags()&~(
1161 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1162 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1163 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1164 FLAG_ACTIVITY_NEW_TASK));
1165
1166 // Okay now we need to start the new activity, replacing the currently running activity.
1167 // This is a little tricky because we want to start the new one as if the current one is
1168 // finished, but not finish the current one first so that there is no flicker.
1169 // And thus...
1170 final boolean wasFinishing = r.finishing;
1171 r.finishing = true;
1172
1173 // Propagate reply information over to the new activity.
1174 final ActivityRecord resultTo = r.resultTo;
1175 final String resultWho = r.resultWho;
1176 final int requestCode = r.requestCode;
1177 r.resultTo = null;
1178 if (resultTo != null) {
1179 resultTo.removeResultsLocked(r, resultWho, requestCode);
1180 }
1181
1182 final long origId = Binder.clearCallingIdentity();
1183 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001184 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001185 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001186 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001187 .setResolvedType(r.resolvedType)
1188 .setActivityInfo(aInfo)
1189 .setResultTo(resultTo != null ? resultTo.appToken : null)
1190 .setResultWho(resultWho)
1191 .setRequestCode(requestCode)
1192 .setCallingPid(-1)
1193 .setCallingUid(r.launchedFromUid)
1194 .setCallingPackage(r.launchedFromPackage)
1195 .setRealCallingPid(-1)
1196 .setRealCallingUid(r.launchedFromUid)
1197 .setActivityOptions(options)
1198 .execute();
1199 Binder.restoreCallingIdentity(origId);
1200
1201 r.finishing = wasFinishing;
1202 if (res != ActivityManager.START_SUCCESS) {
1203 return false;
1204 }
1205 return true;
1206 }
1207 }
1208
1209 @Override
1210 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1211 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1212 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1213 final WaitResult res = new WaitResult();
1214 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001215 enforceNotIsolatedCaller("startActivityAndWait");
1216 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1217 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001219 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 .setCaller(caller)
1221 .setCallingPackage(callingPackage)
1222 .setResolvedType(resolvedType)
1223 .setResultTo(resultTo)
1224 .setResultWho(resultWho)
1225 .setRequestCode(requestCode)
1226 .setStartFlags(startFlags)
1227 .setActivityOptions(bOptions)
1228 .setMayWait(userId)
1229 .setProfilerInfo(profilerInfo)
1230 .setWaitResult(res)
1231 .execute();
1232 }
1233 return res;
1234 }
1235
1236 @Override
1237 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1238 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1239 int startFlags, Configuration config, Bundle bOptions, int userId) {
1240 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001241 enforceNotIsolatedCaller("startActivityWithConfig");
1242 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1243 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001245 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 .setCaller(caller)
1247 .setCallingPackage(callingPackage)
1248 .setResolvedType(resolvedType)
1249 .setResultTo(resultTo)
1250 .setResultWho(resultWho)
1251 .setRequestCode(requestCode)
1252 .setStartFlags(startFlags)
1253 .setGlobalConfiguration(config)
1254 .setActivityOptions(bOptions)
1255 .setMayWait(userId)
1256 .execute();
1257 }
1258 }
1259
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260
1261 @Override
1262 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1263 int callingUid = Binder.getCallingUid();
1264 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1265 throw new SecurityException("Only the system process can request a permission token, "
1266 + "received request from uid: " + callingUid);
1267 }
1268 IBinder permissionToken = new Binder();
1269 synchronized (mGlobalLock) {
1270 mStartActivitySources.put(permissionToken, delegatorToken);
1271 }
1272
1273 Message expireMsg = PooledLambda.obtainMessage(
1274 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1275 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1276
1277 Message forgetMsg = PooledLambda.obtainMessage(
1278 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1279 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1280
1281 return permissionToken;
1282 }
1283
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 @Override
1285 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1286 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001287 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1288 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001290 // permission grants) as any app that may launch one of your own activities. So we only
1291 // allow this in two cases:
1292 // 1) The caller is an activity that is part of the core framework, and then only when it
1293 // is running as the system.
1294 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1295 // can only be requested by a system activity, which may then delegate this call to
1296 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 final ActivityRecord sourceRecord;
1298 final int targetUid;
1299 final String targetPackage;
1300 final boolean isResolver;
1301 synchronized (mGlobalLock) {
1302 if (resultTo == null) {
1303 throw new SecurityException("Must be called from an activity");
1304 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001305 final IBinder sourceToken;
1306 if (permissionToken != null) {
1307 // To even attempt to use a permissionToken, an app must also have this signature
1308 // permission.
1309 mAmInternal.enforceCallingPermission(
1310 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1311 "startActivityAsCaller");
1312 // If called with a permissionToken, we want the sourceRecord from the delegator
1313 // activity that requested this token.
1314 sourceToken = mStartActivitySources.remove(permissionToken);
1315 if (sourceToken == null) {
1316 // Invalid permissionToken, check if it recently expired.
1317 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1318 throw new SecurityException("Called with expired permission token: "
1319 + permissionToken);
1320 } else {
1321 throw new SecurityException("Called with invalid permission token: "
1322 + permissionToken);
1323 }
1324 }
1325 } else {
1326 // This method was called directly by the source.
1327 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001328 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329
Wale Ogunwaled32da472018-11-16 07:19:28 -08001330 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331 if (sourceRecord == null) {
1332 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001333 }
1334 if (sourceRecord.app == null) {
1335 throw new SecurityException("Called without a process attached to activity");
1336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337
1338 // Whether called directly or from a delegate, the source activity must be from the
1339 // android package.
1340 if (!sourceRecord.info.packageName.equals("android")) {
1341 throw new SecurityException("Must be called from an activity that is "
1342 + "declared in the android package");
1343 }
1344
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001345 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 // This is still okay, as long as this activity is running under the
1347 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001348 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 + " must be system uid or original calling uid "
1352 + sourceRecord.launchedFromUid);
1353 }
1354 }
1355 if (ignoreTargetSecurity) {
1356 if (intent.getComponent() == null) {
1357 throw new SecurityException(
1358 "Component must be specified with ignoreTargetSecurity");
1359 }
1360 if (intent.getSelector() != null) {
1361 throw new SecurityException(
1362 "Selector not allowed with ignoreTargetSecurity");
1363 }
1364 }
1365 targetUid = sourceRecord.launchedFromUid;
1366 targetPackage = sourceRecord.launchedFromPackage;
1367 isResolver = sourceRecord.isResolverOrChildActivity();
1368 }
1369
1370 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001371 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 }
1373
1374 // TODO: Switch to user app stacks here.
1375 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001376 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 .setCallingUid(targetUid)
1378 .setCallingPackage(targetPackage)
1379 .setResolvedType(resolvedType)
1380 .setResultTo(resultTo)
1381 .setResultWho(resultWho)
1382 .setRequestCode(requestCode)
1383 .setStartFlags(startFlags)
1384 .setActivityOptions(bOptions)
1385 .setMayWait(userId)
1386 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1387 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001388 // The target may well be in the background, which would normally prevent it
1389 // from starting an activity. Here we definitely want the start to succeed.
1390 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 .execute();
1392 } catch (SecurityException e) {
1393 // XXX need to figure out how to propagate to original app.
1394 // A SecurityException here is generally actually a fault of the original
1395 // calling activity (such as a fairly granting permissions), so propagate it
1396 // back to them.
1397 /*
1398 StringBuilder msg = new StringBuilder();
1399 msg.append("While launching");
1400 msg.append(intent.toString());
1401 msg.append(": ");
1402 msg.append(e.getMessage());
1403 */
1404 throw e;
1405 }
1406 }
1407
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001408 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1409 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1410 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1411 }
1412
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 @Override
1414 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1415 Intent intent, String resolvedType, IVoiceInteractionSession session,
1416 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1417 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 if (session == null || interactor == null) {
1420 throw new NullPointerException("null session or interactor");
1421 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001422 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001424 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 .setCallingUid(callingUid)
1426 .setCallingPackage(callingPackage)
1427 .setResolvedType(resolvedType)
1428 .setVoiceSession(session)
1429 .setVoiceInteractor(interactor)
1430 .setStartFlags(startFlags)
1431 .setProfilerInfo(profilerInfo)
1432 .setActivityOptions(bOptions)
1433 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001434 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 .execute();
1436 }
1437
1438 @Override
1439 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1440 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001441 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1442 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001444 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 .setCallingUid(callingUid)
1446 .setCallingPackage(callingPackage)
1447 .setResolvedType(resolvedType)
1448 .setActivityOptions(bOptions)
1449 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001450 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 .execute();
1452 }
1453
1454 @Override
1455 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1456 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 final int callingPid = Binder.getCallingPid();
1459 final long origId = Binder.clearCallingIdentity();
1460 try {
1461 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001462 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1463 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464
1465 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001466 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1467 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1469 recentsUid, assistDataReceiver);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 @Override
1477 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001478 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 "startActivityFromRecents()");
1480
1481 final int callingPid = Binder.getCallingPid();
1482 final int callingUid = Binder.getCallingUid();
1483 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1484 final long origId = Binder.clearCallingIdentity();
1485 try {
1486 synchronized (mGlobalLock) {
1487 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1488 safeOptions);
1489 }
1490 } finally {
1491 Binder.restoreCallingIdentity(origId);
1492 }
1493 }
1494
1495 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001496 * Public API to check if the client is allowed to start an activity on specified display.
1497 *
1498 * If the target display is private or virtual, some restrictions will apply.
1499 *
1500 * @param displayId Target display id.
1501 * @param intent Intent used to launch the activity.
1502 * @param resolvedType The MIME type of the intent.
1503 * @param userId The id of the user for whom the call is made.
1504 * @return {@code true} if a call to start an activity on the target display should succeed and
1505 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1506 */
1507 @Override
1508 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1509 String resolvedType, int userId) {
1510 final int callingUid = Binder.getCallingUid();
1511 final int callingPid = Binder.getCallingPid();
1512 final long origId = Binder.clearCallingIdentity();
1513
1514 try {
1515 // Collect information about the target of the Intent.
1516 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1517 0 /* startFlags */, null /* profilerInfo */, userId,
1518 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1519 UserHandle.USER_NULL));
1520 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1521
1522 synchronized (mGlobalLock) {
1523 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1524 aInfo);
1525 }
1526 } finally {
1527 Binder.restoreCallingIdentity(origId);
1528 }
1529 }
1530
1531 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 * This is the internal entry point for handling Activity.finish().
1533 *
1534 * @param token The Binder token referencing the Activity we want to finish.
1535 * @param resultCode Result code, if any, from this Activity.
1536 * @param resultData Result data (Intent), if any, from this Activity.
1537 * @param finishTask Whether to finish the task associated with this Activity.
1538 *
1539 * @return Returns true if the activity successfully finished, or false if it is still running.
1540 */
1541 @Override
1542 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1543 int finishTask) {
1544 // Refuse possible leaked file descriptors
1545 if (resultData != null && resultData.hasFileDescriptors()) {
1546 throw new IllegalArgumentException("File descriptors passed in Intent");
1547 }
1548
1549 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001550 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 if (r == null) {
1552 return true;
1553 }
1554 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001555 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 ActivityRecord rootR = tr.getRootActivity();
1557 if (rootR == null) {
1558 Slog.w(TAG, "Finishing task with all activities already finished");
1559 }
1560 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1561 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001562 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 return false;
1564 }
1565
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001566 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1567 // We should consolidate.
1568 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001570 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (next != null) {
1572 // ask watcher if this is allowed
1573 boolean resumeOK = true;
1574 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001575 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001577 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 Watchdog.getInstance().setActivityController(null);
1579 }
1580
1581 if (!resumeOK) {
1582 Slog.i(TAG, "Not finishing activity because controller resumed");
1583 return false;
1584 }
1585 }
1586 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001587
1588 // note down that the process has finished an activity and is in background activity
1589 // starts grace period
1590 if (r.app != null) {
1591 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1592 }
1593
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001594 final long origId = Binder.clearCallingIdentity();
1595 try {
1596 boolean res;
1597 final boolean finishWithRootActivity =
1598 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1599 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1600 || (finishWithRootActivity && r == rootR)) {
1601 // If requested, remove the task that is associated to this activity only if it
1602 // was the root activity in the task. The result code and data is ignored
1603 // because we don't support returning them across task boundaries. Also, to
1604 // keep backwards compatibility we remove the task from recents when finishing
1605 // task with root activity.
1606 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1607 finishWithRootActivity, "finish-activity");
1608 if (!res) {
1609 Slog.i(TAG, "Removing task failed to finish activity");
1610 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001611 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001612 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 } else {
1614 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001615 resultData, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 if (!res) {
1617 Slog.i(TAG, "Failed to finish by app-request");
1618 }
1619 }
1620 return res;
1621 } finally {
1622 Binder.restoreCallingIdentity(origId);
1623 }
1624 }
1625 }
1626
1627 @Override
1628 public boolean finishActivityAffinity(IBinder token) {
1629 synchronized (mGlobalLock) {
1630 final long origId = Binder.clearCallingIdentity();
1631 try {
1632 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1633 if (r == null) {
1634 return false;
1635 }
1636
1637 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1638 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001639 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001640 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 return false;
1642 }
1643 return task.getStack().finishActivityAffinityLocked(r);
1644 } finally {
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1652 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001653 try {
1654 WindowProcessController proc = null;
1655 synchronized (mGlobalLock) {
1656 ActivityStack stack = ActivityRecord.getStackLocked(token);
1657 if (stack == null) {
1658 return;
1659 }
1660 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1661 false /* fromTimeout */, false /* processPausingActivities */, config);
1662 if (r != null) {
1663 proc = r.app;
1664 }
1665 if (stopProfiling && proc != null) {
1666 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 }
1668 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001669 } finally {
1670 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 }
1673
1674 @Override
1675 public final void activityResumed(IBinder token) {
1676 final long origId = Binder.clearCallingIdentity();
1677 synchronized (mGlobalLock) {
1678 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001679 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 }
1681 Binder.restoreCallingIdentity(origId);
1682 }
1683
1684 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001685 public final void activityTopResumedStateLost() {
1686 final long origId = Binder.clearCallingIdentity();
1687 synchronized (mGlobalLock) {
1688 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 public final void activityPaused(IBinder token) {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 ActivityStack stack = ActivityRecord.getStackLocked(token);
1698 if (stack != null) {
1699 stack.activityPausedLocked(token, false);
1700 }
1701 }
1702 Binder.restoreCallingIdentity(origId);
1703 }
1704
1705 @Override
1706 public final void activityStopped(IBinder token, Bundle icicle,
1707 PersistableBundle persistentState, CharSequence description) {
1708 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1709
1710 // Refuse possible leaked file descriptors
1711 if (icicle != null && icicle.hasFileDescriptors()) {
1712 throw new IllegalArgumentException("File descriptors passed in Bundle");
1713 }
1714
1715 final long origId = Binder.clearCallingIdentity();
1716
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001717 String restartingName = null;
1718 int restartingUid = 0;
1719 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001721 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001723 if (r.attachedToProcess()
1724 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1725 // The activity was requested to restart from
1726 // {@link #restartActivityProcessIfVisible}.
1727 restartingName = r.app.mName;
1728 restartingUid = r.app.mUid;
1729 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001730 r.activityStoppedLocked(icicle, persistentState, description);
1731 }
1732 }
1733
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001734 if (restartingName != null) {
1735 // In order to let the foreground activity can be restarted with its saved state from
1736 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1737 // until the activity reports stopped with the state. And the activity record will be
1738 // kept because the record state is restarting, then the activity will be restarted
1739 // immediately if it is still the top one.
1740 mStackSupervisor.removeRestartTimeouts(r);
1741 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1742 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001743 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747
1748 @Override
1749 public final void activityDestroyed(IBinder token) {
1750 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1751 synchronized (mGlobalLock) {
1752 ActivityStack stack = ActivityRecord.getStackLocked(token);
1753 if (stack != null) {
1754 stack.activityDestroyedLocked(token, "activityDestroyed");
1755 }
1756 }
1757 }
1758
1759 @Override
1760 public final void activityRelaunched(IBinder token) {
1761 final long origId = Binder.clearCallingIdentity();
1762 synchronized (mGlobalLock) {
1763 mStackSupervisor.activityRelaunchedLocked(token);
1764 }
1765 Binder.restoreCallingIdentity(origId);
1766 }
1767
1768 public final void activitySlept(IBinder token) {
1769 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1770
1771 final long origId = Binder.clearCallingIdentity();
1772
1773 synchronized (mGlobalLock) {
1774 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1775 if (r != null) {
1776 mStackSupervisor.activitySleptLocked(r);
1777 }
1778 }
1779
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782
1783 @Override
1784 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1785 synchronized (mGlobalLock) {
1786 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r == null) {
1788 return;
1789 }
1790 final long origId = Binder.clearCallingIdentity();
1791 try {
1792 r.setRequestedOrientation(requestedOrientation);
1793 } finally {
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796 }
1797 }
1798
1799 @Override
1800 public int getRequestedOrientation(IBinder token) {
1801 synchronized (mGlobalLock) {
1802 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1803 if (r == null) {
1804 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1805 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001806 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
1808 }
1809
1810 @Override
1811 public void setImmersive(IBinder token, boolean immersive) {
1812 synchronized (mGlobalLock) {
1813 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1814 if (r == null) {
1815 throw new IllegalArgumentException();
1816 }
1817 r.immersive = immersive;
1818
1819 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001820 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 }
1824 }
1825 }
1826
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 void applyUpdateLockStateLocked(ActivityRecord r) {
1828 // Modifications to the UpdateLock state are done on our handler, outside
1829 // the activity manager's locks. The new state is determined based on the
1830 // state *now* of the relevant activity record. The object is passed to
1831 // the handler solely for logging detail, not to be consulted/modified.
1832 final boolean nextState = r != null && r.immersive;
1833 mH.post(() -> {
1834 if (mUpdateLock.isHeld() != nextState) {
1835 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1836 "Applying new update lock state '" + nextState + "' for " + r);
1837 if (nextState) {
1838 mUpdateLock.acquire();
1839 } else {
1840 mUpdateLock.release();
1841 }
1842 }
1843 });
1844 }
1845
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 @Override
1847 public boolean isImmersive(IBinder token) {
1848 synchronized (mGlobalLock) {
1849 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1850 if (r == null) {
1851 throw new IllegalArgumentException();
1852 }
1853 return r.immersive;
1854 }
1855 }
1856
1857 @Override
1858 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001861 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001862 return (r != null) ? r.immersive : false;
1863 }
1864 }
1865
1866 @Override
1867 public void overridePendingTransition(IBinder token, String packageName,
1868 int enterAnim, int exitAnim) {
1869 synchronized (mGlobalLock) {
1870 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1871 if (self == null) {
1872 return;
1873 }
1874
1875 final long origId = Binder.clearCallingIdentity();
1876
1877 if (self.isState(
1878 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001879 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001880 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 }
1882
1883 Binder.restoreCallingIdentity(origId);
1884 }
1885 }
1886
1887 @Override
1888 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001889 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001891 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 if (r == null) {
1893 return ActivityManager.COMPAT_MODE_UNKNOWN;
1894 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001895 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
1897 }
1898
1899 @Override
1900 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 if (r == null) {
1907 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1908 return;
1909 }
1910 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001911 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
1913 }
1914
1915 @Override
1916 public int getLaunchedFromUid(IBinder activityToken) {
1917 ActivityRecord srec;
1918 synchronized (mGlobalLock) {
1919 srec = ActivityRecord.forTokenLocked(activityToken);
1920 }
1921 if (srec == null) {
1922 return -1;
1923 }
1924 return srec.launchedFromUid;
1925 }
1926
1927 @Override
1928 public String getLaunchedFromPackage(IBinder activityToken) {
1929 ActivityRecord srec;
1930 synchronized (mGlobalLock) {
1931 srec = ActivityRecord.forTokenLocked(activityToken);
1932 }
1933 if (srec == null) {
1934 return null;
1935 }
1936 return srec.launchedFromPackage;
1937 }
1938
1939 @Override
1940 public boolean convertFromTranslucent(IBinder token) {
1941 final long origId = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
1944 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1945 if (r == null) {
1946 return false;
1947 }
1948 final boolean translucentChanged = r.changeWindowTranslucency(true);
1949 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001950 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 return translucentChanged;
1954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(origId);
1957 }
1958 }
1959
1960 @Override
1961 public boolean convertToTranslucent(IBinder token, Bundle options) {
1962 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1963 final long origId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
1966 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1967 if (r == null) {
1968 return false;
1969 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001970 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 int index = task.mActivities.lastIndexOf(r);
1972 if (index > 0) {
1973 ActivityRecord under = task.mActivities.get(index - 1);
1974 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1975 }
1976 final boolean translucentChanged = r.changeWindowTranslucency(false);
1977 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001978 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001980 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001981 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 return translucentChanged;
1983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(origId);
1986 }
1987 }
1988
1989 @Override
1990 public void notifyActivityDrawn(IBinder token) {
1991 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1992 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001993 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001995 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 }
1997 }
1998 }
1999
2000 @Override
2001 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2002 synchronized (mGlobalLock) {
2003 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2004 if (r == null) {
2005 return;
2006 }
2007 r.reportFullyDrawnLocked(restoredFromBundle);
2008 }
2009 }
2010
2011 @Override
2012 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2013 synchronized (mGlobalLock) {
2014 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2015 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2016 return stack.mDisplayId;
2017 }
2018 return DEFAULT_DISPLAY;
2019 }
2020 }
2021
2022 @Override
2023 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 try {
2027 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002028 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 return null;
2033 }
2034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
2037 }
2038
2039 @Override
2040 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2043 final long callingId = Binder.clearCallingIdentity();
2044 try {
2045 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (stack == null) {
2048 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2049 return;
2050 }
2051 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002052 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(callingId);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002069 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (task == null) {
2071 return;
2072 }
2073 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002084 public void restartActivityProcessIfVisible(IBinder activityToken) {
2085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
2089 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2090 if (r == null) {
2091 return;
2092 }
2093 r.restartProcessIfVisible();
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingId);
2097 }
2098 }
2099
2100 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002102 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 synchronized (mGlobalLock) {
2104 final long ident = Binder.clearCallingIdentity();
2105 try {
2106 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2107 "remove-task");
2108 } finally {
2109 Binder.restoreCallingIdentity(ident);
2110 }
2111 }
2112 }
2113
2114 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002115 public void removeAllVisibleRecentTasks() {
2116 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2117 synchronized (mGlobalLock) {
2118 final long ident = Binder.clearCallingIdentity();
2119 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002120 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002121 } finally {
2122 Binder.restoreCallingIdentity(ident);
2123 }
2124 }
2125 }
2126
2127 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2129 synchronized (mGlobalLock) {
2130 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2131 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002132 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 }
2134 }
2135 return false;
2136 }
2137
2138 @Override
2139 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2140 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002142 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002143 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2144 if (r != null) {
2145 return r.getActivityStack().navigateUpToLocked(
2146 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002147 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002148 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 }
2150 }
2151
2152 /**
2153 * Attempts to move a task backwards in z-order (the order of activities within the task is
2154 * unchanged).
2155 *
2156 * There are several possible results of this call:
2157 * - if the task is locked, then we will show the lock toast
2158 * - if there is a task behind the provided task, then that task is made visible and resumed as
2159 * this task is moved to the back
2160 * - otherwise, if there are no other tasks in the stack:
2161 * - if this task is in the pinned stack, then we remove the stack completely, which will
2162 * have the effect of moving the task to the top or bottom of the fullscreen stack
2163 * (depending on whether it is visible)
2164 * - otherwise, we simply return home and hide this task
2165 *
2166 * @param token A reference to the activity we wish to move
2167 * @param nonRoot If false then this only works if the activity is the root
2168 * of a task; if true it will work for any activity in a task.
2169 * @return Returns true if the move completed, false if not.
2170 */
2171 @Override
2172 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 synchronized (mGlobalLock) {
2175 final long origId = Binder.clearCallingIdentity();
2176 try {
2177 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002178 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 if (task != null) {
2180 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2181 }
2182 } finally {
2183 Binder.restoreCallingIdentity(origId);
2184 }
2185 }
2186 return false;
2187 }
2188
2189 @Override
2190 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 long ident = Binder.clearCallingIdentity();
2193 Rect rect = new Rect();
2194 try {
2195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2198 if (task == null) {
2199 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2200 return rect;
2201 }
2202 if (task.getStack() != null) {
2203 // Return the bounds from window manager since it will be adjusted for various
2204 // things like the presense of a docked stack for tasks that aren't resizeable.
2205 task.getWindowContainerBounds(rect);
2206 } else {
2207 // Task isn't in window manager yet since it isn't associated with a stack.
2208 // Return the persist value from activity manager
2209 if (!task.matchParentBounds()) {
2210 rect.set(task.getBounds());
2211 } else if (task.mLastNonFullscreenBounds != null) {
2212 rect.set(task.mLastNonFullscreenBounds);
2213 }
2214 }
2215 }
2216 } finally {
2217 Binder.restoreCallingIdentity(ident);
2218 }
2219 return rect;
2220 }
2221
2222 @Override
2223 public ActivityManager.TaskDescription getTaskDescription(int id) {
2224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002225 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (tr != null) {
2230 return tr.lastTaskDescription;
2231 }
2232 }
2233 return null;
2234 }
2235
2236 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2238 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2239 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2240 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2241 return;
2242 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002244 synchronized (mGlobalLock) {
2245 final long ident = Binder.clearCallingIdentity();
2246 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002247 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002248 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 if (task == null) {
2250 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2251 return;
2252 }
2253
2254 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2255 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2256
2257 if (!task.isActivityTypeStandardOrUndefined()) {
2258 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2259 + " non-standard task " + taskId + " to windowing mode="
2260 + windowingMode);
2261 }
2262
2263 final ActivityStack stack = task.getStack();
2264 if (toTop) {
2265 stack.moveToFront("setTaskWindowingMode", task);
2266 }
2267 stack.setWindowingMode(windowingMode);
2268 } finally {
2269 Binder.restoreCallingIdentity(ident);
2270 }
2271 }
2272 }
2273
2274 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 ActivityRecord r = getCallingRecordLocked(token);
2278 return r != null ? r.info.packageName : null;
2279 }
2280 }
2281
2282 @Override
2283 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 ActivityRecord r = getCallingRecordLocked(token);
2286 return r != null ? r.intent.getComponent() : null;
2287 }
2288 }
2289
2290 private ActivityRecord getCallingRecordLocked(IBinder token) {
2291 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2292 if (r == null) {
2293 return null;
2294 }
2295 return r.resultTo;
2296 }
2297
2298 @Override
2299 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002300 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301
2302 synchronized (mGlobalLock) {
2303 final long origId = Binder.clearCallingIdentity();
2304 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002305 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 } finally {
2307 Binder.restoreCallingIdentity(origId);
2308 }
2309 }
2310 }
2311
Mark Renouf446251d2019-04-26 10:22:41 -04002312 @Override
2313 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2314 synchronized (mGlobalLock) {
2315 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2316 if (r == null) {
2317 return;
2318 }
2319 ActivityStack stack = r.getActivityStack();
2320 if (stack != null && stack.isSingleTaskInstance()) {
2321 // Single-task stacks are used for activities which are presented in floating
2322 // windows above full screen activities. Instead of directly finishing the
2323 // task, a task change listener is used to notify SystemUI so the action can be
2324 // handled specially.
2325 final TaskRecord task = r.getTaskRecord();
2326 mTaskChangeNotificationController
2327 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2328 } else {
2329 try {
2330 callback.requestFinish();
2331 } catch (RemoteException e) {
2332 Slog.e(TAG, "Failed to invoke request finish callback", e);
2333 }
2334 }
2335 }
2336 }
2337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 /**
2339 * TODO: Add mController hook
2340 */
2341 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2343 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2347 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002348 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2349 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 }
2351 }
2352
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2354 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 boolean fromRecents) {
2356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 final int callingPid = Binder.getCallingPid();
2358 final int callingUid = Binder.getCallingUid();
2359 if (!isSameApp(callingUid, callingPackage)) {
2360 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2361 + Binder.getCallingPid() + " as package " + callingPackage;
2362 Slog.w(TAG, msg);
2363 throw new SecurityException(msg);
2364 }
2365 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 SafeActivityOptions.abort(options);
2367 return;
2368 }
2369 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 WindowProcessController callerApp = null;
2371 if (appThread != null) {
2372 callerApp = getProcessController(appThread);
2373 }
2374 final ActivityStarter starter = getActivityStartController().obtainStarter(
2375 null /* intent */, "moveTaskToFront");
2376 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2377 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002378 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 return;
2380 }
2381 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002383 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 if (task == null) {
2385 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002386 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 return;
2388 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002389 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002391 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 return;
2393 }
2394 ActivityOptions realOptions = options != null
2395 ? options.getOptions(mStackSupervisor)
2396 : null;
2397 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2398 false /* forceNonResizable */);
2399
2400 final ActivityRecord topActivity = task.getTopActivity();
2401 if (topActivity != null) {
2402
2403 // We are reshowing a task, use a starting window to hide the initial draw delay
2404 // so the transition can start earlier.
2405 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2406 true /* taskSwitch */, fromRecents);
2407 }
2408 } finally {
2409 Binder.restoreCallingIdentity(origId);
2410 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 }
2412
Ricky Waiaca8a772019-04-04 16:01:06 +01002413 /**
2414 * Return true if callingUid is system, or packageName belongs to that callingUid.
2415 */
2416 boolean isSameApp(int callingUid, @Nullable String packageName) {
2417 try {
2418 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2419 if (packageName == null) {
2420 return false;
2421 }
2422 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2423 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2424 UserHandle.getUserId(callingUid));
2425 return UserHandle.isSameApp(callingUid, uid);
2426 }
2427 } catch (RemoteException e) {
2428 // Should not happen
2429 }
2430 return true;
2431 }
2432
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002433 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2434 int callingPid, int callingUid, String name) {
2435 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2436 return true;
2437 }
2438
2439 if (getRecentTasks().isCallerRecents(sourceUid)) {
2440 return true;
2441 }
2442
2443 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2444 if (perm == PackageManager.PERMISSION_GRANTED) {
2445 return true;
2446 }
2447 if (checkAllowAppSwitchUid(sourceUid)) {
2448 return true;
2449 }
2450
2451 // If the actual IPC caller is different from the logical source, then
2452 // also see if they are allowed to control app switches.
2453 if (callingUid != -1 && callingUid != sourceUid) {
2454 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2455 if (perm == PackageManager.PERMISSION_GRANTED) {
2456 return true;
2457 }
2458 if (checkAllowAppSwitchUid(callingUid)) {
2459 return true;
2460 }
2461 }
2462
2463 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2464 return false;
2465 }
2466
2467 private boolean checkAllowAppSwitchUid(int uid) {
2468 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2469 if (types != null) {
2470 for (int i = types.size() - 1; i >= 0; i--) {
2471 if (types.valueAt(i).intValue() == uid) {
2472 return true;
2473 }
2474 }
2475 }
2476 return false;
2477 }
2478
2479 @Override
2480 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2481 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2482 "setActivityController()");
2483 synchronized (mGlobalLock) {
2484 mController = controller;
2485 mControllerIsAMonkey = imAMonkey;
2486 Watchdog.getInstance().setActivityController(controller);
2487 }
2488 }
2489
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002490 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002491 synchronized (mGlobalLock) {
2492 return mController != null && mControllerIsAMonkey;
2493 }
2494 }
2495
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002496 @Override
2497 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2498 synchronized (mGlobalLock) {
2499 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2500 }
2501 }
2502
2503 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2505 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2506 }
2507
2508 @Override
2509 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2510 @WindowConfiguration.ActivityType int ignoreActivityType,
2511 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2512 final int callingUid = Binder.getCallingUid();
2513 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2514
2515 synchronized (mGlobalLock) {
2516 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002518 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002520 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 ignoreWindowingMode, callingUid, allowed);
2522 }
2523
2524 return list;
2525 }
2526
2527 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2529 synchronized (mGlobalLock) {
2530 final long origId = Binder.clearCallingIdentity();
2531 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2532 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002533 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 }
2535 Binder.restoreCallingIdentity(origId);
2536 }
2537 }
2538
2539 @Override
2540 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002541 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 ActivityStack stack = ActivityRecord.getStackLocked(token);
2543 if (stack != null) {
2544 return stack.willActivityBeVisibleLocked(token);
2545 }
2546 return false;
2547 }
2548 }
2549
2550 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002552 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 synchronized (mGlobalLock) {
2554 final long ident = Binder.clearCallingIdentity();
2555 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002556 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 if (task == null) {
2558 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2559 return;
2560 }
2561
2562 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2563 + " to stackId=" + stackId + " toTop=" + toTop);
2564
Wale Ogunwaled32da472018-11-16 07:19:28 -08002565 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002566 if (stack == null) {
2567 throw new IllegalStateException(
2568 "moveTaskToStack: No stack for stackId=" + stackId);
2569 }
2570 if (!stack.isActivityTypeStandardOrUndefined()) {
2571 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2572 + taskId + " to stack " + stackId);
2573 }
2574 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2577 }
2578 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2579 "moveTaskToStack");
2580 } finally {
2581 Binder.restoreCallingIdentity(ident);
2582 }
2583 }
2584 }
2585
2586 @Override
2587 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2588 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002589 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590
2591 final long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
2594 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002595 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 if (stack == null) {
2597 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2598 return;
2599 }
2600 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2601 throw new IllegalArgumentException("Stack: " + stackId
2602 + " doesn't support animated resize.");
2603 }
2604 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2605 animationDuration, false /* fromFullscreen */);
2606 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 if (stack == null) {
2609 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2610 return;
2611 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002612 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2614 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2615 }
2616 }
2617 } finally {
2618 Binder.restoreCallingIdentity(ident);
2619 }
2620 }
2621
wilsonshih5c4cf522019-01-25 09:03:47 +08002622 @Override
2623 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2624 int animationDuration) {
2625 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2626
2627 final long ident = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
2630 if (xOffset == 0 && yOffset == 0) {
2631 return;
2632 }
2633 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2634 if (stack == null) {
2635 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2636 return;
2637 }
2638 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2639 throw new IllegalArgumentException("Stack: " + stackId
2640 + " doesn't support animated resize.");
2641 }
2642 final Rect destBounds = new Rect();
2643 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002644 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002645 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2646 return;
2647 }
2648 destBounds.offset(xOffset, yOffset);
2649 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2650 animationDuration, false /* fromFullscreen */);
2651 }
2652 } finally {
2653 Binder.restoreCallingIdentity(ident);
2654 }
2655 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002656 /**
2657 * Moves the specified task to the primary-split-screen stack.
2658 *
2659 * @param taskId Id of task to move.
2660 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2661 * exist already. See
2662 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2663 * and
2664 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2665 * @param toTop If the task and stack should be moved to the top.
2666 * @param animate Whether we should play an animation for the moving the task.
2667 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2668 * stack. Pass {@code null} to use default bounds.
2669 * @param showRecents If the recents activity should be shown on the other side of the task
2670 * going into split-screen mode.
2671 */
2672 @Override
2673 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2674 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 "setTaskWindowingModeSplitScreenPrimary()");
2677 synchronized (mGlobalLock) {
2678 final long ident = Binder.clearCallingIdentity();
2679 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002680 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002681 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 if (task == null) {
2683 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2684 return false;
2685 }
2686 if (DEBUG_STACK) Slog.d(TAG_STACK,
2687 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2688 + " to createMode=" + createMode + " toTop=" + toTop);
2689 if (!task.isActivityTypeStandardOrUndefined()) {
2690 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2691 + " non-standard task " + taskId + " to split-screen windowing mode");
2692 }
2693
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002694 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002695 final int windowingMode = task.getWindowingMode();
2696 final ActivityStack stack = task.getStack();
2697 if (toTop) {
2698 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2699 }
2700 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002701 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2702 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 return windowingMode != task.getWindowingMode();
2704 } finally {
2705 Binder.restoreCallingIdentity(ident);
2706 }
2707 }
2708 }
2709
2710 /**
2711 * Removes stacks in the input windowing modes from the system if they are of activity type
2712 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2713 */
2714 @Override
2715 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002716 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 "removeStacksInWindowingModes()");
2718
2719 synchronized (mGlobalLock) {
2720 final long ident = Binder.clearCallingIdentity();
2721 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002722 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727 }
2728
2729 @Override
2730 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002731 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 "removeStacksWithActivityTypes()");
2733
2734 synchronized (mGlobalLock) {
2735 final long ident = Binder.clearCallingIdentity();
2736 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002737 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 } finally {
2739 Binder.restoreCallingIdentity(ident);
2740 }
2741 }
2742 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743
2744 @Override
2745 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2746 int userId) {
2747 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002748 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2749 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 final boolean detailed = checkGetTasksPermission(
2752 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2753 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 == PackageManager.PERMISSION_GRANTED;
2755
2756 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002757 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 callingUid);
2759 }
2760 }
2761
2762 @Override
2763 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 long ident = Binder.clearCallingIdentity();
2766 try {
2767 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002768 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 } finally {
2771 Binder.restoreCallingIdentity(ident);
2772 }
2773 }
2774
2775 @Override
2776 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 long ident = Binder.clearCallingIdentity();
2779 try {
2780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002781 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(ident);
2785 }
2786 }
2787
2788 @Override
2789 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002790 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 final long callingUid = Binder.getCallingUid();
2792 final long origId = Binder.clearCallingIdentity();
2793 try {
2794 synchronized (mGlobalLock) {
2795 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002796 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2798 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2799 }
2800 } finally {
2801 Binder.restoreCallingIdentity(origId);
2802 }
2803 }
2804
2805 @Override
2806 public void startLockTaskModeByToken(IBinder token) {
2807 synchronized (mGlobalLock) {
2808 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2809 if (r == null) {
2810 return;
2811 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002812 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 }
2814 }
2815
2816 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002817 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002818 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 // This makes inner call to look as if it was initiated by system.
2820 long ident = Binder.clearCallingIdentity();
2821 try {
2822 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002823 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002824 MATCH_TASK_IN_STACKS_ONLY);
2825 if (task == null) {
2826 return;
2827 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828
2829 // When starting lock task mode the stack must be in front and focused
2830 task.getStack().moveToFront("startSystemLockTaskMode");
2831 startLockTaskModeLocked(task, true /* isSystemCaller */);
2832 }
2833 } finally {
2834 Binder.restoreCallingIdentity(ident);
2835 }
2836 }
2837
2838 @Override
2839 public void stopLockTaskModeByToken(IBinder token) {
2840 synchronized (mGlobalLock) {
2841 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2842 if (r == null) {
2843 return;
2844 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002845 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 }
2847 }
2848
2849 /**
2850 * This API should be called by SystemUI only when user perform certain action to dismiss
2851 * lock task mode. We should only dismiss pinned lock task mode in this case.
2852 */
2853 @Override
2854 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2857 }
2858
2859 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2860 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2861 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2862 return;
2863 }
2864
Wale Ogunwaled32da472018-11-16 07:19:28 -08002865 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 if (stack == null || task != stack.topTask()) {
2867 throw new IllegalArgumentException("Invalid task, not in foreground");
2868 }
2869
2870 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2871 // system or a specific app.
2872 // * System-initiated requests will only start the pinned mode (screen pinning)
2873 // * App-initiated requests
2874 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2875 // - will start the pinned mode, otherwise
2876 final int callingUid = Binder.getCallingUid();
2877 long ident = Binder.clearCallingIdentity();
2878 try {
2879 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002880 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002882 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 } finally {
2884 Binder.restoreCallingIdentity(ident);
2885 }
2886 }
2887
2888 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2889 final int callingUid = Binder.getCallingUid();
2890 long ident = Binder.clearCallingIdentity();
2891 try {
2892 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002893 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 }
2895 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2896 // task and jumping straight into a call in the case of emergency call back.
2897 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2898 if (tm != null) {
2899 tm.showInCallScreen(false);
2900 }
2901 } finally {
2902 Binder.restoreCallingIdentity(ident);
2903 }
2904 }
2905
2906 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002907 public void updateLockTaskPackages(int userId, String[] packages) {
2908 final int callingUid = Binder.getCallingUid();
2909 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2910 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2911 "updateLockTaskPackages()");
2912 }
2913 synchronized (this) {
2914 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2915 + Arrays.toString(packages));
2916 getLockTaskController().updateLockTaskPackages(userId, packages);
2917 }
2918 }
2919
2920 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 public boolean isInLockTaskMode() {
2922 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2923 }
2924
2925 @Override
2926 public int getLockTaskModeState() {
2927 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002928 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 }
2930 }
2931
2932 @Override
2933 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2934 synchronized (mGlobalLock) {
2935 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2936 if (r != null) {
2937 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002938 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002940 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 }
2942 }
2943 }
2944
2945 @Override
2946 public Bundle getActivityOptions(IBinder token) {
2947 final long origId = Binder.clearCallingIdentity();
2948 try {
2949 synchronized (mGlobalLock) {
2950 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2951 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002952 final ActivityOptions activityOptions = r.takeOptionsLocked(
2953 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 return activityOptions == null ? null : activityOptions.toBundle();
2955 }
2956 return null;
2957 }
2958 } finally {
2959 Binder.restoreCallingIdentity(origId);
2960 }
2961 }
2962
2963 @Override
2964 public List<IBinder> getAppTasks(String callingPackage) {
2965 int callingUid = Binder.getCallingUid();
2966 long ident = Binder.clearCallingIdentity();
2967 try {
2968 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002969 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 }
2971 } finally {
2972 Binder.restoreCallingIdentity(ident);
2973 }
2974 }
2975
2976 @Override
2977 public void finishVoiceTask(IVoiceInteractionSession session) {
2978 synchronized (mGlobalLock) {
2979 final long origId = Binder.clearCallingIdentity();
2980 try {
2981 // TODO: VI Consider treating local voice interactions and voice tasks
2982 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002983 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 } finally {
2985 Binder.restoreCallingIdentity(origId);
2986 }
2987 }
2988
2989 }
2990
2991 @Override
2992 public boolean isTopOfTask(IBinder token) {
2993 synchronized (mGlobalLock) {
2994 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002995 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 }
2997 }
2998
2999 @Override
3000 public void notifyLaunchTaskBehindComplete(IBinder token) {
3001 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3002 }
3003
3004 @Override
3005 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 mH.post(() -> {
3007 synchronized (mGlobalLock) {
3008 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003009 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003011 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003012 } catch (RemoteException e) {
3013 }
3014 }
3015 }
3016
3017 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 }
3019
3020 /** Called from an app when assist data is ready. */
3021 @Override
3022 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3023 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003024 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 synchronized (pae) {
3026 pae.result = extras;
3027 pae.structure = structure;
3028 pae.content = content;
3029 if (referrer != null) {
3030 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3031 }
3032 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003033 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003034 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3035 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 structure.setHomeActivity(pae.isHome);
3037 }
3038 pae.haveResult = true;
3039 pae.notifyAll();
3040 if (pae.intent == null && pae.receiver == null) {
3041 // Caller is just waiting for the result.
3042 return;
3043 }
3044 }
3045 // We are now ready to launch the assist activity.
3046 IAssistDataReceiver sendReceiver = null;
3047 Bundle sendBundle = null;
3048 synchronized (mGlobalLock) {
3049 buildAssistBundleLocked(pae, extras);
3050 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 if (!exists) {
3053 // Timed out.
3054 return;
3055 }
3056
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003057 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 // Caller wants result sent back to them.
3059 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003060 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3061 pae.activity.getTaskRecord().taskId);
3062 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3063 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003064 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3065 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3066 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3067 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3068 }
3069 }
3070 if (sendReceiver != null) {
3071 try {
3072 sendReceiver.onHandleAssistData(sendBundle);
3073 } catch (RemoteException e) {
3074 }
3075 return;
3076 }
3077
3078 final long ident = Binder.clearCallingIdentity();
3079 try {
3080 if (TextUtils.equals(pae.intent.getAction(),
3081 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3082 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003083
3084 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 } else {
3086 pae.intent.replaceExtras(pae.extras);
3087 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3088 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3089 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003090 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091
3092 try {
3093 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3094 } catch (ActivityNotFoundException e) {
3095 Slog.w(TAG, "No activity to handle assist action.", e);
3096 }
3097 }
3098 } finally {
3099 Binder.restoreCallingIdentity(ident);
3100 }
3101 }
3102
Marvin Ramin830d4e32019-03-12 13:16:58 +01003103 /**
3104 * Workaround for historical API which starts the Assist service with a non-foreground
3105 * {@code startService()} call.
3106 */
3107 private void startVoiceInteractionServiceAsUser(
3108 Intent intent, int userHandle, String reason) {
3109 // Resolve the intent to find out which package we need to whitelist.
3110 ResolveInfo resolveInfo =
3111 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3112 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3113 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3114 return;
3115 }
3116 intent.setPackage(resolveInfo.serviceInfo.packageName);
3117
3118 // Whitelist background services temporarily.
3119 LocalServices.getService(DeviceIdleController.LocalService.class)
3120 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3121 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3122
3123 // Finally, try to start the service.
3124 try {
3125 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3126 } catch (RuntimeException e) {
3127 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3128 }
3129 }
3130
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 @Override
3132 public int addAppTask(IBinder activityToken, Intent intent,
3133 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3134 final int callingUid = Binder.getCallingUid();
3135 final long callingIdent = Binder.clearCallingIdentity();
3136
3137 try {
3138 synchronized (mGlobalLock) {
3139 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3140 if (r == null) {
3141 throw new IllegalArgumentException("Activity does not exist; token="
3142 + activityToken);
3143 }
3144 ComponentName comp = intent.getComponent();
3145 if (comp == null) {
3146 throw new IllegalArgumentException("Intent " + intent
3147 + " must specify explicit component");
3148 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003149 if (thumbnail.getWidth() != mThumbnailWidth
3150 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 throw new IllegalArgumentException("Bad thumbnail size: got "
3152 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003153 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 }
3155 if (intent.getSelector() != null) {
3156 intent.setSelector(null);
3157 }
3158 if (intent.getSourceBounds() != null) {
3159 intent.setSourceBounds(null);
3160 }
3161 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3162 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3163 // The caller has added this as an auto-remove task... that makes no
3164 // sense, so turn off auto-remove.
3165 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3166 }
3167 }
3168 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3169 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3170 if (ainfo.applicationInfo.uid != callingUid) {
3171 throw new SecurityException(
3172 "Can't add task for another application: target uid="
3173 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3174 }
3175
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003176 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003178 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003180 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 // The app has too many tasks already and we can't add any more
3182 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3183 return INVALID_TASK_ID;
3184 }
3185 task.lastTaskDescription.copyFrom(description);
3186
3187 // TODO: Send the thumbnail to WM to store it.
3188
3189 return task.taskId;
3190 }
3191 } finally {
3192 Binder.restoreCallingIdentity(callingIdent);
3193 }
3194 }
3195
3196 @Override
3197 public Point getAppTaskThumbnailSize() {
3198 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 }
3201 }
3202
3203 @Override
3204 public void setTaskResizeable(int taskId, int resizeableMode) {
3205 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003206 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3208 if (task == null) {
3209 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3210 return;
3211 }
3212 task.setResizeMode(resizeableMode);
3213 }
3214 }
3215
3216 @Override
3217 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003218 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 long ident = Binder.clearCallingIdentity();
3220 try {
3221 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003222 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003223 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 if (task == null) {
3225 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3226 return;
3227 }
3228 // Place the task in the right stack if it isn't there already based on
3229 // the requested bounds.
3230 // The stack transition logic is:
3231 // - a null bounds on a freeform task moves that task to fullscreen
3232 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3233 // that task to freeform
3234 // - otherwise the task is not moved
3235 ActivityStack stack = task.getStack();
3236 if (!task.getWindowConfiguration().canResizeTask()) {
3237 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3238 }
3239 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3240 stack = stack.getDisplay().getOrCreateStack(
3241 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3242 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3243 stack = stack.getDisplay().getOrCreateStack(
3244 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3245 }
3246
3247 // Reparent the task to the right stack if necessary
3248 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3249 if (stack != task.getStack()) {
3250 // Defer resume until the task is resized below
3251 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3252 DEFER_RESUME, "resizeTask");
3253 preserveWindow = false;
3254 }
3255
3256 // After reparenting (which only resizes the task to the stack bounds), resize the
3257 // task to the actual bounds provided
3258 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3259 }
3260 } finally {
3261 Binder.restoreCallingIdentity(ident);
3262 }
3263 }
3264
3265 @Override
3266 public boolean releaseActivityInstance(IBinder token) {
3267 synchronized (mGlobalLock) {
3268 final long origId = Binder.clearCallingIdentity();
3269 try {
3270 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3271 if (r == null) {
3272 return false;
3273 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003274 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 } finally {
3276 Binder.restoreCallingIdentity(origId);
3277 }
3278 }
3279 }
3280
3281 @Override
3282 public void releaseSomeActivities(IApplicationThread appInt) {
3283 synchronized (mGlobalLock) {
3284 final long origId = Binder.clearCallingIdentity();
3285 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003286 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003287 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 } finally {
3289 Binder.restoreCallingIdentity(origId);
3290 }
3291 }
3292 }
3293
3294 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003295 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003296 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 != PackageManager.PERMISSION_GRANTED) {
3298 throw new SecurityException("Requires permission "
3299 + android.Manifest.permission.DEVICE_POWER);
3300 }
3301
3302 synchronized (mGlobalLock) {
3303 long ident = Binder.clearCallingIdentity();
3304 if (mKeyguardShown != keyguardShowing) {
3305 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003306 final Message msg = PooledLambda.obtainMessage(
3307 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3308 keyguardShowing);
3309 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 }
3311 try {
wilsonshih177261f2019-02-22 12:02:18 +08003312 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 } finally {
3314 Binder.restoreCallingIdentity(ident);
3315 }
3316 }
3317
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003318 mH.post(() -> {
3319 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3320 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3321 }
3322 });
3323 }
3324
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003325 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 mH.post(() -> {
3327 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3328 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3329 }
3330 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 }
3332
3333 @Override
3334 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003335 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3336 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337
3338 final File passedIconFile = new File(filePath);
3339 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3340 passedIconFile.getName());
3341 if (!legitIconFile.getPath().equals(filePath)
3342 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3343 throw new IllegalArgumentException("Bad file path: " + filePath
3344 + " passed for userId " + userId);
3345 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003346 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 }
3348
3349 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003350 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3352 final ActivityOptions activityOptions = safeOptions != null
3353 ? safeOptions.getOptions(mStackSupervisor)
3354 : null;
3355 if (activityOptions == null
3356 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3357 || activityOptions.getCustomInPlaceResId() == 0) {
3358 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3359 "with valid animation");
3360 }
lumark588a3e82018-07-20 18:53:54 +08003361 // Get top display of front most application.
3362 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3363 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003364 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3365 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3366 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003367 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003368 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003369 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 }
3371
3372 @Override
3373 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 synchronized (mGlobalLock) {
3376 final long ident = Binder.clearCallingIdentity();
3377 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003378 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 if (stack == null) {
3380 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3381 return;
3382 }
3383 if (!stack.isActivityTypeStandardOrUndefined()) {
3384 throw new IllegalArgumentException(
3385 "Removing non-standard stack is not allowed.");
3386 }
3387 mStackSupervisor.removeStack(stack);
3388 } finally {
3389 Binder.restoreCallingIdentity(ident);
3390 }
3391 }
3392 }
3393
3394 @Override
3395 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397
3398 synchronized (mGlobalLock) {
3399 final long ident = Binder.clearCallingIdentity();
3400 try {
3401 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3402 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003403 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 } finally {
3405 Binder.restoreCallingIdentity(ident);
3406 }
3407 }
3408 }
3409
3410 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003411 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 synchronized (mGlobalLock) {
3413 long ident = Binder.clearCallingIdentity();
3414 try {
3415 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3416 if (r == null) {
3417 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003418 "toggleFreeformWindowingMode: No activity record matching token="
3419 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 }
3421
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003422 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003423 if (stack == null) {
3424 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3425 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427
Yunfan Chend967af82019-01-17 18:30:18 +09003428 if (!stack.inFreeformWindowingMode()
3429 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3430 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3431 + "toggle between fullscreen and freeform.");
3432 }
3433
3434 if (stack.inFreeformWindowingMode()) {
3435 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003436 } else if (stack.getParent().inFreeformWindowingMode()) {
3437 // If the window is on a freeform display, set it to undefined. It will be
3438 // resolved to freeform and it can adjust windowing mode when the display mode
3439 // changes in runtime.
3440 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003441 } else {
3442 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3443 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444 } finally {
3445 Binder.restoreCallingIdentity(ident);
3446 }
3447 }
3448 }
3449
3450 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3451 @Override
3452 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003455 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457
3458 /** Unregister a task stack listener so that it stops receiving callbacks. */
3459 @Override
3460 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003461 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003463 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 }
3465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 @Override
3467 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3468 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3469 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3470 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3471 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3472 }
3473
3474 @Override
3475 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3476 IBinder activityToken, int flags) {
3477 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3478 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3479 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3480 }
3481
3482 @Override
3483 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3484 Bundle args) {
3485 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3486 true /* focused */, true /* newSessionId */, userHandle, args,
3487 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3488 }
3489
3490 @Override
3491 public Bundle getAssistContextExtras(int requestType) {
3492 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3493 null, null, true /* focused */, true /* newSessionId */,
3494 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3495 if (pae == null) {
3496 return null;
3497 }
3498 synchronized (pae) {
3499 while (!pae.haveResult) {
3500 try {
3501 pae.wait();
3502 } catch (InterruptedException e) {
3503 }
3504 }
3505 }
3506 synchronized (mGlobalLock) {
3507 buildAssistBundleLocked(pae, pae.result);
3508 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003509 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003510 }
3511 return pae.extras;
3512 }
3513
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 /**
3515 * Binder IPC calls go through the public entry point.
3516 * This can be called with or without the global lock held.
3517 */
3518 private static int checkCallingPermission(String permission) {
3519 return checkPermission(
3520 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3521 }
3522
3523 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003524 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003525 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3526 mAmInternal.enforceCallingPermission(permission, func);
3527 }
3528 }
3529
3530 @VisibleForTesting
3531 int checkGetTasksPermission(String permission, int pid, int uid) {
3532 return checkPermission(permission, pid, uid);
3533 }
3534
3535 static int checkPermission(String permission, int pid, int uid) {
3536 if (permission == null) {
3537 return PackageManager.PERMISSION_DENIED;
3538 }
3539 return checkComponentPermission(permission, pid, uid, -1, true);
3540 }
3541
Wale Ogunwale214f3482018-10-04 11:00:47 -07003542 public static int checkComponentPermission(String permission, int pid, int uid,
3543 int owningUid, boolean exported) {
3544 return ActivityManagerService.checkComponentPermission(
3545 permission, pid, uid, owningUid, exported);
3546 }
3547
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003548 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3549 if (getRecentTasks().isCallerRecents(callingUid)) {
3550 // Always allow the recents component to get tasks
3551 return true;
3552 }
3553
3554 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3555 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3556 if (!allowed) {
3557 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3558 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3559 // Temporary compatibility: some existing apps on the system image may
3560 // still be requesting the old permission and not switched to the new
3561 // one; if so, we'll still allow them full access. This means we need
3562 // to see if they are holding the old permission and are a system app.
3563 try {
3564 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3565 allowed = true;
3566 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3567 + " is using old GET_TASKS but privileged; allowing");
3568 }
3569 } catch (RemoteException e) {
3570 }
3571 }
3572 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3573 + " does not hold REAL_GET_TASKS; limiting output");
3574 }
3575 return allowed;
3576 }
3577
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3579 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3580 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3581 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003582 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 "enqueueAssistContext()");
3584
3585 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003586 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003587 if (activity == null) {
3588 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3589 return null;
3590 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003591 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3593 return null;
3594 }
3595 if (focused) {
3596 if (activityToken != null) {
3597 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3598 if (activity != caller) {
3599 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3600 + " is not current top " + activity);
3601 return null;
3602 }
3603 }
3604 } else {
3605 activity = ActivityRecord.forTokenLocked(activityToken);
3606 if (activity == null) {
3607 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3608 + " couldn't be found");
3609 return null;
3610 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003611 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3613 return null;
3614 }
3615 }
3616
3617 PendingAssistExtras pae;
3618 Bundle extras = new Bundle();
3619 if (args != null) {
3620 extras.putAll(args);
3621 }
3622 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003623 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624
3625 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3626 userHandle);
3627 pae.isHome = activity.isActivityTypeHome();
3628
3629 // Increment the sessionId if necessary
3630 if (newSessionId) {
3631 mViSessionId++;
3632 }
3633 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003634 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3635 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003637 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 } catch (RemoteException e) {
3639 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3640 return null;
3641 }
3642 return pae;
3643 }
3644 }
3645
3646 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3647 if (result != null) {
3648 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3649 }
3650 if (pae.hint != null) {
3651 pae.extras.putBoolean(pae.hint, true);
3652 }
3653 }
3654
3655 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3656 IAssistDataReceiver receiver;
3657 synchronized (mGlobalLock) {
3658 mPendingAssistExtras.remove(pae);
3659 receiver = pae.receiver;
3660 }
3661 if (receiver != null) {
3662 // Caller wants result sent back to them.
3663 Bundle sendBundle = new Bundle();
3664 // At least return the receiver extras
3665 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3666 try {
3667 pae.receiver.onHandleAssistData(sendBundle);
3668 } catch (RemoteException e) {
3669 }
3670 }
3671 }
3672
3673 public class PendingAssistExtras extends Binder implements Runnable {
3674 public final ActivityRecord activity;
3675 public boolean isHome;
3676 public final Bundle extras;
3677 public final Intent intent;
3678 public final String hint;
3679 public final IAssistDataReceiver receiver;
3680 public final int userHandle;
3681 public boolean haveResult = false;
3682 public Bundle result = null;
3683 public AssistStructure structure = null;
3684 public AssistContent content = null;
3685 public Bundle receiverExtras;
3686
3687 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3688 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3689 int _userHandle) {
3690 activity = _activity;
3691 extras = _extras;
3692 intent = _intent;
3693 hint = _hint;
3694 receiver = _receiver;
3695 receiverExtras = _receiverExtras;
3696 userHandle = _userHandle;
3697 }
3698
3699 @Override
3700 public void run() {
3701 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3702 synchronized (this) {
3703 haveResult = true;
3704 notifyAll();
3705 }
3706 pendingAssistExtrasTimedOut(this);
3707 }
3708 }
3709
3710 @Override
3711 public boolean isAssistDataAllowedOnCurrentActivity() {
3712 int userId;
3713 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003714 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3716 return false;
3717 }
3718
3719 final ActivityRecord activity = focusedStack.getTopActivity();
3720 if (activity == null) {
3721 return false;
3722 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003723 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724 }
3725 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3726 }
3727
3728 @Override
3729 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3730 long ident = Binder.clearCallingIdentity();
3731 try {
3732 synchronized (mGlobalLock) {
3733 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003734 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (top != caller) {
3736 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3737 + " is not current top " + top);
3738 return false;
3739 }
3740 if (!top.nowVisible) {
3741 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3742 + " is not visible");
3743 return false;
3744 }
3745 }
3746 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3747 token);
3748 } finally {
3749 Binder.restoreCallingIdentity(ident);
3750 }
3751 }
3752
3753 @Override
3754 public boolean isRootVoiceInteraction(IBinder token) {
3755 synchronized (mGlobalLock) {
3756 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3757 if (r == null) {
3758 return false;
3759 }
3760 return r.rootVoiceInteraction;
3761 }
3762 }
3763
Wale Ogunwalef6733932018-06-27 05:14:34 -07003764 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3765 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3766 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3767 if (activityToCallback == null) return;
3768 activityToCallback.setVoiceSessionLocked(voiceSession);
3769
3770 // Inform the activity
3771 try {
3772 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3773 voiceInteractor);
3774 long token = Binder.clearCallingIdentity();
3775 try {
3776 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3777 } finally {
3778 Binder.restoreCallingIdentity(token);
3779 }
3780 // TODO: VI Should we cache the activity so that it's easier to find later
3781 // rather than scan through all the stacks and activities?
3782 } catch (RemoteException re) {
3783 activityToCallback.clearVoiceSessionLocked();
3784 // TODO: VI Should this terminate the voice session?
3785 }
3786 }
3787
3788 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3789 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3790 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3791 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3792 boolean wasRunningVoice = mRunningVoice != null;
3793 mRunningVoice = session;
3794 if (!wasRunningVoice) {
3795 mVoiceWakeLock.acquire();
3796 updateSleepIfNeededLocked();
3797 }
3798 }
3799 }
3800
3801 void finishRunningVoiceLocked() {
3802 if (mRunningVoice != null) {
3803 mRunningVoice = null;
3804 mVoiceWakeLock.release();
3805 updateSleepIfNeededLocked();
3806 }
3807 }
3808
3809 @Override
3810 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3811 synchronized (mGlobalLock) {
3812 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3813 if (keepAwake) {
3814 mVoiceWakeLock.acquire();
3815 } else {
3816 mVoiceWakeLock.release();
3817 }
3818 }
3819 }
3820 }
3821
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 @Override
3823 public ComponentName getActivityClassForToken(IBinder token) {
3824 synchronized (mGlobalLock) {
3825 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3826 if (r == null) {
3827 return null;
3828 }
3829 return r.intent.getComponent();
3830 }
3831 }
3832
3833 @Override
3834 public String getPackageForToken(IBinder token) {
3835 synchronized (mGlobalLock) {
3836 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3837 if (r == null) {
3838 return null;
3839 }
3840 return r.packageName;
3841 }
3842 }
3843
3844 @Override
3845 public void showLockTaskEscapeMessage(IBinder token) {
3846 synchronized (mGlobalLock) {
3847 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3848 if (r == null) {
3849 return;
3850 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003851 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 }
3853 }
3854
3855 @Override
3856 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003857 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 final long token = Binder.clearCallingIdentity();
3859 try {
3860 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003861 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 }
3863 } finally {
3864 Binder.restoreCallingIdentity(token);
3865 }
3866 }
3867
3868 /**
3869 * Try to place task to provided position. The final position might be different depending on
3870 * current user and stacks state. The task will be moved to target stack if it's currently in
3871 * different stack.
3872 */
3873 @Override
3874 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003875 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 synchronized (mGlobalLock) {
3877 long ident = Binder.clearCallingIdentity();
3878 try {
3879 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3880 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003881 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 if (task == null) {
3883 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3884 + taskId);
3885 }
3886
Wale Ogunwaled32da472018-11-16 07:19:28 -08003887 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888
3889 if (stack == null) {
3890 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3891 + stackId);
3892 }
3893 if (!stack.isActivityTypeStandardOrUndefined()) {
3894 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3895 + " the position of task " + taskId + " in/to non-standard stack");
3896 }
3897
3898 // TODO: Have the callers of this API call a separate reparent method if that is
3899 // what they intended to do vs. having this method also do reparenting.
3900 if (task.getStack() == stack) {
3901 // Change position in current stack.
3902 stack.positionChildAt(task, position);
3903 } else {
3904 // Reparent to new stack.
3905 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3906 !DEFER_RESUME, "positionTaskInStack");
3907 }
3908 } finally {
3909 Binder.restoreCallingIdentity(ident);
3910 }
3911 }
3912 }
3913
3914 @Override
3915 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3916 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3917 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003918 + Arrays.toString(horizontalSizeConfiguration) + " "
3919 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 synchronized (mGlobalLock) {
3921 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3922 if (record == null) {
3923 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3924 + "found for: " + token);
3925 }
3926 record.setSizeConfigurations(horizontalSizeConfiguration,
3927 verticalSizeConfigurations, smallestSizeConfigurations);
3928 }
3929 }
3930
3931 /**
3932 * Dismisses split-screen multi-window mode.
3933 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3934 */
3935 @Override
3936 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003937 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3939 final long ident = Binder.clearCallingIdentity();
3940 try {
3941 synchronized (mGlobalLock) {
3942 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003943 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 if (stack == null) {
3945 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3946 return;
3947 }
3948
3949 if (toTop) {
3950 // Caller wants the current split-screen primary stack to be the top stack after
3951 // it goes fullscreen, so move it to the front.
3952 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003953 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 // In this case the current split-screen primary stack shouldn't be the top
3955 // stack after it goes fullscreen, but it current has focus, so we move the
3956 // focus to the top-most split-screen secondary stack next to it.
3957 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3958 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3959 if (otherStack != null) {
3960 otherStack.moveToFront("dismissSplitScreenMode_other");
3961 }
3962 }
3963
Evan Rosky10475742018-09-05 19:02:48 -07003964 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(ident);
3968 }
3969 }
3970
3971 /**
3972 * Dismisses Pip
3973 * @param animate True if the dismissal should be animated.
3974 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3975 * default animation duration should be used.
3976 */
3977 @Override
3978 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003979 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 final long ident = Binder.clearCallingIdentity();
3981 try {
3982 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003983 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003984 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 if (stack == null) {
3986 Slog.w(TAG, "dismissPip: pinned stack not found.");
3987 return;
3988 }
3989 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3990 throw new IllegalArgumentException("Stack: " + stack
3991 + " doesn't support animated resize.");
3992 }
3993 if (animate) {
3994 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3995 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3996 } else {
3997 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3998 }
3999 }
4000 } finally {
4001 Binder.restoreCallingIdentity(ident);
4002 }
4003 }
4004
4005 @Override
4006 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 synchronized (mGlobalLock) {
4009 mSuppressResizeConfigChanges = suppress;
4010 }
4011 }
4012
4013 /**
4014 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4015 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4016 * activity and clearing the task at the same time.
4017 */
4018 @Override
4019 // TODO: API should just be about changing windowing modes...
4020 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004021 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 "moveTasksToFullscreenStack()");
4023 synchronized (mGlobalLock) {
4024 final long origId = Binder.clearCallingIdentity();
4025 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004026 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 if (stack != null){
4028 if (!stack.isActivityTypeStandardOrUndefined()) {
4029 throw new IllegalArgumentException(
4030 "You can't move tasks from non-standard stacks.");
4031 }
4032 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4033 }
4034 } finally {
4035 Binder.restoreCallingIdentity(origId);
4036 }
4037 }
4038 }
4039
4040 /**
4041 * Moves the top activity in the input stackId to the pinned stack.
4042 *
4043 * @param stackId Id of stack to move the top activity to pinned stack.
4044 * @param bounds Bounds to use for pinned stack.
4045 *
4046 * @return True if the top activity of the input stack was successfully moved to the pinned
4047 * stack.
4048 */
4049 @Override
4050 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004051 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 "moveTopActivityToPinnedStack()");
4053 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004054 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4056 + "Device doesn't support picture-in-picture mode");
4057 }
4058
4059 long ident = Binder.clearCallingIdentity();
4060 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004061 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 } finally {
4063 Binder.restoreCallingIdentity(ident);
4064 }
4065 }
4066 }
4067
4068 @Override
4069 public boolean isInMultiWindowMode(IBinder token) {
4070 final long origId = Binder.clearCallingIdentity();
4071 try {
4072 synchronized (mGlobalLock) {
4073 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4074 if (r == null) {
4075 return false;
4076 }
4077 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4078 return r.inMultiWindowMode();
4079 }
4080 } finally {
4081 Binder.restoreCallingIdentity(origId);
4082 }
4083 }
4084
4085 @Override
4086 public boolean isInPictureInPictureMode(IBinder token) {
4087 final long origId = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4091 }
4092 } finally {
4093 Binder.restoreCallingIdentity(origId);
4094 }
4095 }
4096
4097 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004098 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4099 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100 return false;
4101 }
4102
4103 // If we are animating to fullscreen then we have already dispatched the PIP mode
4104 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004105 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4106 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 }
4108
4109 @Override
4110 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4111 final long origId = Binder.clearCallingIdentity();
4112 try {
4113 synchronized (mGlobalLock) {
4114 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4115 "enterPictureInPictureMode", token, params);
4116
4117 // If the activity is already in picture in picture mode, then just return early
4118 if (isInPictureInPictureMode(r)) {
4119 return true;
4120 }
4121
4122 // Activity supports picture-in-picture, now check that we can enter PiP at this
4123 // point, if it is
4124 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4125 false /* beforeStopping */)) {
4126 return false;
4127 }
4128
4129 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004130 synchronized (mGlobalLock) {
4131 // Only update the saved args from the args that are set
4132 r.pictureInPictureArgs.copyOnlySet(params);
4133 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4134 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4135 // Adjust the source bounds by the insets for the transition down
4136 final Rect sourceBounds = new Rect(
4137 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004138 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004139 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004140 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 stack.setPictureInPictureAspectRatio(aspectRatio);
4142 stack.setPictureInPictureActions(actions);
4143 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4144 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4145 logPictureInPictureArgs(params);
4146 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 };
4148
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004149 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 // If the keyguard is showing or occluded, then try and dismiss it before
4151 // entering picture-in-picture (this will prompt the user to authenticate if the
4152 // device is currently locked).
4153 dismissKeyguard(token, new KeyguardDismissCallback() {
4154 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004155 public void onDismissSucceeded() {
4156 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 }
4158 }, null /* message */);
4159 } else {
4160 // Enter picture in picture immediately otherwise
4161 enterPipRunnable.run();
4162 }
4163 return true;
4164 }
4165 } finally {
4166 Binder.restoreCallingIdentity(origId);
4167 }
4168 }
4169
4170 @Override
4171 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4172 final long origId = Binder.clearCallingIdentity();
4173 try {
4174 synchronized (mGlobalLock) {
4175 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4176 "setPictureInPictureParams", token, params);
4177
4178 // Only update the saved args from the args that are set
4179 r.pictureInPictureArgs.copyOnlySet(params);
4180 if (r.inPinnedWindowingMode()) {
4181 // If the activity is already in picture-in-picture, update the pinned stack now
4182 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4183 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004184 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 if (!stack.isAnimatingBoundsToFullscreen()) {
4186 stack.setPictureInPictureAspectRatio(
4187 r.pictureInPictureArgs.getAspectRatio());
4188 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4189 }
4190 }
4191 logPictureInPictureArgs(params);
4192 }
4193 } finally {
4194 Binder.restoreCallingIdentity(origId);
4195 }
4196 }
4197
4198 @Override
4199 public int getMaxNumPictureInPictureActions(IBinder token) {
4200 // Currently, this is a static constant, but later, we may change this to be dependent on
4201 // the context of the activity
4202 return 3;
4203 }
4204
4205 private void logPictureInPictureArgs(PictureInPictureParams params) {
4206 if (params.hasSetActions()) {
4207 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4208 params.getActions().size());
4209 }
4210 if (params.hasSetAspectRatio()) {
4211 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4212 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4213 MetricsLogger.action(lm);
4214 }
4215 }
4216
4217 /**
4218 * Checks the state of the system and the activity associated with the given {@param token} to
4219 * verify that picture-in-picture is supported for that activity.
4220 *
4221 * @return the activity record for the given {@param token} if all the checks pass.
4222 */
4223 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4224 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004225 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004226 throw new IllegalStateException(caller
4227 + ": Device doesn't support picture-in-picture mode.");
4228 }
4229
4230 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4231 if (r == null) {
4232 throw new IllegalStateException(caller
4233 + ": Can't find activity for token=" + token);
4234 }
4235
4236 if (!r.supportsPictureInPicture()) {
4237 throw new IllegalStateException(caller
4238 + ": Current activity does not support picture-in-picture.");
4239 }
4240
4241 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004242 && !mWindowManager.isValidPictureInPictureAspectRatio(
4243 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 final float minAspectRatio = mContext.getResources().getFloat(
4245 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4246 final float maxAspectRatio = mContext.getResources().getFloat(
4247 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4248 throw new IllegalArgumentException(String.format(caller
4249 + ": Aspect ratio is too extreme (must be between %f and %f).",
4250 minAspectRatio, maxAspectRatio));
4251 }
4252
4253 // Truncate the number of actions if necessary
4254 params.truncateActions(getMaxNumPictureInPictureActions(token));
4255
4256 return r;
4257 }
4258
4259 @Override
4260 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 synchronized (mGlobalLock) {
4263 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4264 if (r == null) {
4265 throw new IllegalArgumentException("Activity does not exist; token="
4266 + activityToken);
4267 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004268 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 }
4270 }
4271
4272 @Override
4273 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4274 Rect tempDockedTaskInsetBounds,
4275 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
4280 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4281 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4282 PRESERVE_WINDOWS);
4283 }
4284 } finally {
4285 Binder.restoreCallingIdentity(ident);
4286 }
4287 }
4288
4289 @Override
4290 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 final long ident = Binder.clearCallingIdentity();
4293 try {
4294 synchronized (mGlobalLock) {
4295 mStackSupervisor.setSplitScreenResizing(resizing);
4296 }
4297 } finally {
4298 Binder.restoreCallingIdentity(ident);
4299 }
4300 }
4301
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 /**
4303 * Check that we have the features required for VR-related API calls, and throw an exception if
4304 * not.
4305 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004306 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004307 if (!mContext.getPackageManager().hasSystemFeature(
4308 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4309 throw new UnsupportedOperationException("VR mode not supported on this device!");
4310 }
4311 }
4312
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 @Override
4314 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004315 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316
4317 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4318
4319 ActivityRecord r;
4320 synchronized (mGlobalLock) {
4321 r = ActivityRecord.isInStackLocked(token);
4322 }
4323
4324 if (r == null) {
4325 throw new IllegalArgumentException();
4326 }
4327
4328 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004329 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 VrManagerInternal.NO_ERROR) {
4331 return err;
4332 }
4333
4334 // Clear the binder calling uid since this path may call moveToTask().
4335 final long callingId = Binder.clearCallingIdentity();
4336 try {
4337 synchronized (mGlobalLock) {
4338 r.requestedVrComponent = (enabled) ? packageName : null;
4339
4340 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004341 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004342 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 }
4344 return 0;
4345 }
4346 } finally {
4347 Binder.restoreCallingIdentity(callingId);
4348 }
4349 }
4350
4351 @Override
4352 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4353 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4354 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004355 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4357 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4358 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004359 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 || activity.voiceSession != null) {
4361 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4362 return;
4363 }
4364 if (activity.pendingVoiceInteractionStart) {
4365 Slog.w(TAG, "Pending start of voice interaction already.");
4366 return;
4367 }
4368 activity.pendingVoiceInteractionStart = true;
4369 }
4370 LocalServices.getService(VoiceInteractionManagerInternal.class)
4371 .startLocalVoiceInteraction(callingActivity, options);
4372 }
4373
4374 @Override
4375 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4376 LocalServices.getService(VoiceInteractionManagerInternal.class)
4377 .stopLocalVoiceInteraction(callingActivity);
4378 }
4379
4380 @Override
4381 public boolean supportsLocalVoiceInteraction() {
4382 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4383 .supportsLocalVoiceInteraction();
4384 }
4385
4386 /** Notifies all listeners when the pinned stack animation starts. */
4387 @Override
4388 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004389 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 }
4391
4392 /** Notifies all listeners when the pinned stack animation ends. */
4393 @Override
4394 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004395 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 }
4397
4398 @Override
4399 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 final long ident = Binder.clearCallingIdentity();
4402 try {
4403 synchronized (mGlobalLock) {
4404 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4405 }
4406 } finally {
4407 Binder.restoreCallingIdentity(ident);
4408 }
4409 }
4410
4411 @Override
4412 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414
4415 synchronized (mGlobalLock) {
4416 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004417 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 // Call might come when display is not yet added or has already been removed.
4419 if (DEBUG_CONFIGURATION) {
4420 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4421 + displayId);
4422 }
4423 return false;
4424 }
4425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 }
4430
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004431 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004432 final Message msg = PooledLambda.obtainMessage(
4433 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4434 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 }
4436
4437 final long origId = Binder.clearCallingIdentity();
4438 try {
4439 if (values != null) {
4440 Settings.System.clearConfiguration(values);
4441 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4444 return mTmpUpdateConfigurationResult.changes != 0;
4445 } finally {
4446 Binder.restoreCallingIdentity(origId);
4447 }
4448 }
4449 }
4450
4451 @Override
4452 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454
4455 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 }
4460
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004462 final Message msg = PooledLambda.obtainMessage(
4463 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4464 DEFAULT_DISPLAY);
4465 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 }
4467
4468 final long origId = Binder.clearCallingIdentity();
4469 try {
4470 if (values != null) {
4471 Settings.System.clearConfiguration(values);
4472 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 UserHandle.USER_NULL, false /* deferResume */,
4475 mTmpUpdateConfigurationResult);
4476 return mTmpUpdateConfigurationResult.changes != 0;
4477 } finally {
4478 Binder.restoreCallingIdentity(origId);
4479 }
4480 }
4481 }
4482
4483 @Override
4484 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4485 CharSequence message) {
4486 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4489 }
4490 final long callingId = Binder.clearCallingIdentity();
4491 try {
4492 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004493 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 }
4495 } finally {
4496 Binder.restoreCallingIdentity(callingId);
4497 }
4498 }
4499
4500 @Override
4501 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004502 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 "cancelTaskWindowTransition()");
4504 final long ident = Binder.clearCallingIdentity();
4505 try {
4506 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004507 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 MATCH_TASK_IN_STACKS_ONLY);
4509 if (task == null) {
4510 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4511 return;
4512 }
4513 task.cancelWindowTransition();
4514 }
4515 } finally {
4516 Binder.restoreCallingIdentity(ident);
4517 }
4518 }
4519
4520 @Override
4521 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 final long ident = Binder.clearCallingIdentity();
4524 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004525 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 } finally {
4527 Binder.restoreCallingIdentity(ident);
4528 }
4529 }
4530
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004531 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4532 boolean restoreFromDisk) {
4533 final TaskRecord task;
4534 synchronized (mGlobalLock) {
4535 task = mRootActivityContainer.anyTaskForId(taskId,
4536 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4537 if (task == null) {
4538 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4539 return null;
4540 }
4541 }
4542 // Don't call this while holding the lock as this operation might hit the disk.
4543 return task.getSnapshot(reducedResolution, restoreFromDisk);
4544 }
4545
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004546 @Override
4547 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4548 synchronized (mGlobalLock) {
4549 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4550 if (r == null) {
4551 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4552 + token);
4553 return;
4554 }
4555 final long origId = Binder.clearCallingIdentity();
4556 try {
4557 r.setDisablePreviewScreenshots(disable);
4558 } finally {
4559 Binder.restoreCallingIdentity(origId);
4560 }
4561 }
4562 }
4563
4564 /** Return the user id of the last resumed activity. */
4565 @Override
4566 public @UserIdInt
4567 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004568 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4570 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004571 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004572 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004574 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 }
4576 }
4577
4578 @Override
4579 public void updateLockTaskFeatures(int userId, int flags) {
4580 final int callingUid = Binder.getCallingUid();
4581 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 "updateLockTaskFeatures()");
4584 }
4585 synchronized (mGlobalLock) {
4586 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4587 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004588 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004589 }
4590 }
4591
4592 @Override
4593 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4594 synchronized (mGlobalLock) {
4595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4596 if (r == null) {
4597 return;
4598 }
4599 final long origId = Binder.clearCallingIdentity();
4600 try {
4601 r.setShowWhenLocked(showWhenLocked);
4602 } finally {
4603 Binder.restoreCallingIdentity(origId);
4604 }
4605 }
4606 }
4607
4608 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004609 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4610 synchronized (mGlobalLock) {
4611 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4612 if (r == null) {
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
4624 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4626 synchronized (mGlobalLock) {
4627 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4628 if (r == null) {
4629 return;
4630 }
4631 final long origId = Binder.clearCallingIdentity();
4632 try {
4633 r.setTurnScreenOn(turnScreenOn);
4634 } finally {
4635 Binder.restoreCallingIdentity(origId);
4636 }
4637 }
4638 }
4639
4640 @Override
4641 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004642 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 "registerRemoteAnimations");
4644 definition.setCallingPid(Binder.getCallingPid());
4645 synchronized (mGlobalLock) {
4646 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4647 if (r == null) {
4648 return;
4649 }
4650 final long origId = Binder.clearCallingIdentity();
4651 try {
4652 r.registerRemoteAnimations(definition);
4653 } finally {
4654 Binder.restoreCallingIdentity(origId);
4655 }
4656 }
4657 }
4658
4659 @Override
4660 public void registerRemoteAnimationForNextActivityStart(String packageName,
4661 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004662 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004663 "registerRemoteAnimationForNextActivityStart");
4664 adapter.setCallingPid(Binder.getCallingPid());
4665 synchronized (mGlobalLock) {
4666 final long origId = Binder.clearCallingIdentity();
4667 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004668 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 packageName, adapter);
4670 } finally {
4671 Binder.restoreCallingIdentity(origId);
4672 }
4673 }
4674 }
4675
Evan Rosky966759f2019-01-15 10:33:58 -08004676 @Override
4677 public void registerRemoteAnimationsForDisplay(int displayId,
4678 RemoteAnimationDefinition definition) {
4679 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4680 "registerRemoteAnimations");
4681 definition.setCallingPid(Binder.getCallingPid());
4682 synchronized (mGlobalLock) {
4683 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4684 if (display == null) {
4685 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4686 return;
4687 }
4688 final long origId = Binder.clearCallingIdentity();
4689 try {
4690 display.mDisplayContent.registerRemoteAnimations(definition);
4691 } finally {
4692 Binder.restoreCallingIdentity(origId);
4693 }
4694 }
4695 }
4696
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004697 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4698 @Override
4699 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4700 synchronized (mGlobalLock) {
4701 final long origId = Binder.clearCallingIdentity();
4702 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004703 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004704 } finally {
4705 Binder.restoreCallingIdentity(origId);
4706 }
4707 }
4708 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004709
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 @Override
4711 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004712 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004714 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004715 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004716 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 }
4718 }
4719
4720 @Override
4721 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004722 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 != PERMISSION_GRANTED) {
4724 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4725 + Binder.getCallingPid()
4726 + ", uid=" + Binder.getCallingUid()
4727 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4728 Slog.w(TAG, msg);
4729 throw new SecurityException(msg);
4730 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004731 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004733 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004734 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004735 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004736 }
4737 }
4738
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004739 @Override
4740 public void stopAppSwitches() {
4741 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4742 synchronized (mGlobalLock) {
4743 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004744 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 mDidAppSwitch = false;
4746 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4747 }
4748 }
4749
4750 @Override
4751 public void resumeAppSwitches() {
4752 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4753 synchronized (mGlobalLock) {
4754 // Note that we don't execute any pending app switches... we will
4755 // let those wait until either the timeout, or the next start
4756 // activity request.
4757 mAppSwitchesAllowedTime = 0;
4758 }
4759 }
4760
Ricky Wai906af482019-06-03 17:25:28 +01004761 long getLastStopAppSwitchesTime() {
4762 return mLastStopAppSwitchesTime;
4763 }
4764
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004765 void onStartActivitySetDidAppSwitch() {
4766 if (mDidAppSwitch) {
4767 // This is the second allowed switch since we stopped switches, so now just generally
4768 // allow switches. Use case:
4769 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4770 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4771 // anyone to switch again).
4772 mAppSwitchesAllowedTime = 0;
4773 } else {
4774 mDidAppSwitch = true;
4775 }
4776 }
4777
4778 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004779 boolean shouldDisableNonVrUiLocked() {
4780 return mVrController.shouldDisableNonVrUiLocked();
4781 }
4782
Wale Ogunwale53783742018-09-16 10:21:51 -07004783 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004784 // VR apps are expected to run in a main display. If an app is turning on VR for
4785 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4786 // fullscreen stack before enabling VR Mode.
4787 // TODO: The goal of this code is to keep the VR app on the main display. When the
4788 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4789 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4790 // option would be a better choice here.
4791 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4792 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4793 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004794 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004796 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 }
4798 mH.post(() -> {
4799 if (!mVrController.onVrModeChanged(r)) {
4800 return;
4801 }
4802 synchronized (mGlobalLock) {
4803 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4804 mWindowManager.disableNonVrUi(disableNonVrUi);
4805 if (disableNonVrUi) {
4806 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4807 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004808 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 }
4810 }
4811 });
4812 }
4813
Wale Ogunwale53783742018-09-16 10:21:51 -07004814 @Override
4815 public int getPackageScreenCompatMode(String packageName) {
4816 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4817 synchronized (mGlobalLock) {
4818 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4819 }
4820 }
4821
4822 @Override
4823 public void setPackageScreenCompatMode(String packageName, int mode) {
4824 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4825 "setPackageScreenCompatMode");
4826 synchronized (mGlobalLock) {
4827 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4828 }
4829 }
4830
4831 @Override
4832 public boolean getPackageAskScreenCompat(String packageName) {
4833 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4834 synchronized (mGlobalLock) {
4835 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4836 }
4837 }
4838
4839 @Override
4840 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4841 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4842 "setPackageAskScreenCompat");
4843 synchronized (mGlobalLock) {
4844 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4845 }
4846 }
4847
Wale Ogunwale64258362018-10-16 15:13:37 -07004848 public static String relaunchReasonToString(int relaunchReason) {
4849 switch (relaunchReason) {
4850 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4851 return "window_resize";
4852 case RELAUNCH_REASON_FREE_RESIZE:
4853 return "free_resize";
4854 default:
4855 return null;
4856 }
4857 }
4858
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004859 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004860 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861 }
4862
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004863 /** Pokes the task persister. */
4864 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4865 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4866 }
4867
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004868 boolean isKeyguardLocked() {
4869 return mKeyguardController.isKeyguardLocked();
4870 }
4871
Garfield Tan01548632018-11-27 10:15:48 -08004872 /**
4873 * Clears launch params for the given package.
4874 * @param packageNames the names of the packages of which the launch params are to be cleared
4875 */
4876 @Override
4877 public void clearLaunchParamsForPackages(List<String> packageNames) {
4878 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4879 "clearLaunchParamsForPackages");
4880 synchronized (mGlobalLock) {
4881 for (int i = 0; i < packageNames.size(); ++i) {
4882 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4883 }
4884 }
4885 }
4886
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004887 /**
4888 * Makes the display with the given id a single task instance display. I.e the display can only
4889 * contain one task.
4890 */
4891 @Override
4892 public void setDisplayToSingleTaskInstance(int displayId) {
4893 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4894 "setDisplayToSingleTaskInstance");
4895 final long origId = Binder.clearCallingIdentity();
4896 try {
4897 final ActivityDisplay display =
4898 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4899 if (display != null) {
4900 display.setDisplayToSingleTaskInstance();
4901 }
4902 } finally {
4903 Binder.restoreCallingIdentity(origId);
4904 }
4905 }
4906
Wale Ogunwale31913b52018-10-13 08:29:31 -07004907 void dumpLastANRLocked(PrintWriter pw) {
4908 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4909 if (mLastANRState == null) {
4910 pw.println(" <no ANR has occurred since boot>");
4911 } else {
4912 pw.println(mLastANRState);
4913 }
4914 }
4915
4916 void dumpLastANRTracesLocked(PrintWriter pw) {
4917 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4918
4919 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4920 if (ArrayUtils.isEmpty(files)) {
4921 pw.println(" <no ANR has occurred since boot>");
4922 return;
4923 }
4924 // Find the latest file.
4925 File latest = null;
4926 for (File f : files) {
4927 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4928 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004929 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 }
4931 pw.print("File: ");
4932 pw.print(latest.getName());
4933 pw.println();
4934 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4935 String line;
4936 while ((line = in.readLine()) != null) {
4937 pw.println(line);
4938 }
4939 } catch (IOException e) {
4940 pw.print("Unable to read: ");
4941 pw.print(e);
4942 pw.println();
4943 }
4944 }
4945
4946 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4947 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4948 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4949 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4950 }
4951
4952 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4953 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4954 pw.println(header);
4955
Wale Ogunwaled32da472018-11-16 07:19:28 -08004956 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004957 dumpPackage);
4958 boolean needSep = printedAnything;
4959
4960 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004961 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 " ResumedActivity: ");
4963 if (printed) {
4964 printedAnything = true;
4965 needSep = false;
4966 }
4967
4968 if (dumpPackage == null) {
4969 if (needSep) {
4970 pw.println();
4971 }
4972 printedAnything = true;
4973 mStackSupervisor.dump(pw, " ");
4974 }
4975
4976 if (!printedAnything) {
4977 pw.println(" (nothing)");
4978 }
4979 }
4980
4981 void dumpActivityContainersLocked(PrintWriter pw) {
4982 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004983 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 pw.println(" ");
4985 }
4986
4987 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4988 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4989 getActivityStartController().dump(pw, "", dumpPackage);
4990 }
4991
4992 /**
4993 * There are three things that cmd can be:
4994 * - a flattened component name that matches an existing activity
4995 * - the cmd arg isn't the flattened component name of an existing activity:
4996 * dump all activity whose component contains the cmd as a substring
4997 * - A hex number of the ActivityRecord object instance.
4998 *
4999 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5000 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5001 */
5002 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5003 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5004 ArrayList<ActivityRecord> activities;
5005
5006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005007 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005008 dumpFocusedStackOnly);
5009 }
5010
5011 if (activities.size() <= 0) {
5012 return false;
5013 }
5014
5015 String[] newArgs = new String[args.length - opti];
5016 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5017
5018 TaskRecord lastTask = null;
5019 boolean needSep = false;
5020 for (int i = activities.size() - 1; i >= 0; i--) {
5021 ActivityRecord r = activities.get(i);
5022 if (needSep) {
5023 pw.println();
5024 }
5025 needSep = true;
5026 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005027 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005028 if (lastTask != task) {
5029 lastTask = task;
5030 pw.print("TASK "); pw.print(lastTask.affinity);
5031 pw.print(" id="); pw.print(lastTask.taskId);
5032 pw.print(" userId="); pw.println(lastTask.userId);
5033 if (dumpAll) {
5034 lastTask.dump(pw, " ");
5035 }
5036 }
5037 }
5038 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5039 }
5040 return true;
5041 }
5042
5043 /**
5044 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5045 * there is a thread associated with the activity.
5046 */
5047 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5048 final ActivityRecord r, String[] args, boolean dumpAll) {
5049 String innerPrefix = prefix + " ";
5050 synchronized (mGlobalLock) {
5051 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5052 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5053 pw.print(" pid=");
5054 if (r.hasProcess()) pw.println(r.app.getPid());
5055 else pw.println("(not running)");
5056 if (dumpAll) {
5057 r.dump(pw, innerPrefix);
5058 }
5059 }
5060 if (r.attachedToProcess()) {
5061 // flush anything that is already in the PrintWriter since the thread is going
5062 // to write to the file descriptor directly
5063 pw.flush();
5064 try {
5065 TransferPipe tp = new TransferPipe();
5066 try {
5067 r.app.getThread().dumpActivity(tp.getWriteFd(),
5068 r.appToken, innerPrefix, args);
5069 tp.go(fd);
5070 } finally {
5071 tp.kill();
5072 }
5073 } catch (IOException e) {
5074 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5075 } catch (RemoteException e) {
5076 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5077 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005079 }
5080
sanryhuang498e77e2018-12-06 14:57:01 +08005081 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5082 boolean testPssMode) {
5083 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5084 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5085 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005086 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005087 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5088 st.toString());
5089 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005090 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5091 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5092 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005093 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5094 testPssMode);
5095 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005096 }
5097
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005098 int getCurrentUserId() {
5099 return mAmInternal.getCurrentUserId();
5100 }
5101
5102 private void enforceNotIsolatedCaller(String caller) {
5103 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5104 throw new SecurityException("Isolated process not allowed to call " + caller);
5105 }
5106 }
5107
Wale Ogunwalef6733932018-06-27 05:14:34 -07005108 public Configuration getConfiguration() {
5109 Configuration ci;
5110 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005111 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005112 ci.userSetLocale = false;
5113 }
5114 return ci;
5115 }
5116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005117 /**
5118 * Current global configuration information. Contains general settings for the entire system,
5119 * also corresponds to the merged configuration of the default display.
5120 */
5121 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005122 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005123 }
5124
5125 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5126 boolean initLocale) {
5127 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5128 }
5129
5130 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5131 boolean initLocale, boolean deferResume) {
5132 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5133 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5134 UserHandle.USER_NULL, deferResume);
5135 }
5136
Wale Ogunwale59507092018-10-29 09:00:30 -07005137 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138 final long origId = Binder.clearCallingIdentity();
5139 try {
5140 synchronized (mGlobalLock) {
5141 updateConfigurationLocked(values, null, false, true, userId,
5142 false /* deferResume */);
5143 }
5144 } finally {
5145 Binder.restoreCallingIdentity(origId);
5146 }
5147 }
5148
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005149 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5150 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5151 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5152 deferResume, null /* result */);
5153 }
5154
5155 /**
5156 * Do either or both things: (1) change the current configuration, and (2)
5157 * make sure the given activity is running with the (now) current
5158 * configuration. Returns true if the activity has been left running, or
5159 * false if <var>starting</var> is being destroyed to match the new
5160 * configuration.
5161 *
5162 * @param userId is only used when persistent parameter is set to true to persist configuration
5163 * for that particular user
5164 */
5165 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5166 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5167 ActivityTaskManagerService.UpdateConfigurationResult result) {
5168 int changes = 0;
5169 boolean kept = true;
5170
5171 if (mWindowManager != null) {
5172 mWindowManager.deferSurfaceLayout();
5173 }
5174 try {
5175 if (values != null) {
5176 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5177 deferResume);
5178 }
5179
5180 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5181 } finally {
5182 if (mWindowManager != null) {
5183 mWindowManager.continueSurfaceLayout();
5184 }
5185 }
5186
5187 if (result != null) {
5188 result.changes = changes;
5189 result.activityRelaunched = !kept;
5190 }
5191 return kept;
5192 }
5193
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194 /** Update default (global) configuration and notify listeners about changes. */
5195 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5196 boolean persistent, int userId, boolean deferResume) {
5197 mTempConfig.setTo(getGlobalConfiguration());
5198 final int changes = mTempConfig.updateFrom(values);
5199 if (changes == 0) {
5200 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5201 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5202 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5203 // (even if there are no actual changes) to unfreeze the window.
5204 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5205 return 0;
5206 }
5207
5208 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5209 "Updating global configuration to: " + values);
5210
5211 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5212 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5213 values.colorMode,
5214 values.densityDpi,
5215 values.fontScale,
5216 values.hardKeyboardHidden,
5217 values.keyboard,
5218 values.keyboardHidden,
5219 values.mcc,
5220 values.mnc,
5221 values.navigation,
5222 values.navigationHidden,
5223 values.orientation,
5224 values.screenHeightDp,
5225 values.screenLayout,
5226 values.screenWidthDp,
5227 values.smallestScreenWidthDp,
5228 values.touchscreen,
5229 values.uiMode);
5230
5231
5232 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5233 final LocaleList locales = values.getLocales();
5234 int bestLocaleIndex = 0;
5235 if (locales.size() > 1) {
5236 if (mSupportedSystemLocales == null) {
5237 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5238 }
5239 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5240 }
5241 SystemProperties.set("persist.sys.locale",
5242 locales.get(bestLocaleIndex).toLanguageTag());
5243 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005244
5245 final Message m = PooledLambda.obtainMessage(
5246 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5247 locales.get(bestLocaleIndex));
5248 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 }
5250
Yunfan Chen75157d72018-07-27 14:47:21 +09005251 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252
5253 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005254 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255
5256 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5257 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005258 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259
5260 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005261 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 AttributeCache ac = AttributeCache.instance();
5264 if (ac != null) {
5265 ac.updateConfiguration(mTempConfig);
5266 }
5267
5268 // Make sure all resources in our process are updated right now, so that anyone who is going
5269 // to retrieve resource values after we return will be sure to get the new ones. This is
5270 // especially important during boot, where the first config change needs to guarantee all
5271 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005272 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273
5274 // We need another copy of global config because we're scheduling some calls instead of
5275 // running them in place. We need to be sure that object we send will be handled unchanged.
5276 final Configuration configCopy = new Configuration(mTempConfig);
5277 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005278 final Message msg = PooledLambda.obtainMessage(
5279 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5280 this, userId, configCopy);
5281 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005282 }
5283
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005284 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5285 for (int i = pidMap.size() - 1; i >= 0; i--) {
5286 final int pid = pidMap.keyAt(i);
5287 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005288 if (DEBUG_CONFIGURATION) {
5289 Slog.v(TAG_CONFIGURATION, "Update process config of "
5290 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005292 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293 }
5294
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005295 final Message msg = PooledLambda.obtainMessage(
5296 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5297 mAmInternal, changes, initLocale);
5298 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299
5300 // Override configuration of the default display duplicates global config, so we need to
5301 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005302 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005303 DEFAULT_DISPLAY);
5304
5305 return changes;
5306 }
5307
5308 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5309 boolean deferResume, int displayId) {
5310 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5311 displayId, null /* result */);
5312 }
5313
5314 /**
5315 * Updates override configuration specific for the selected display. If no config is provided,
5316 * new one will be computed in WM based on current display info.
5317 */
5318 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5319 ActivityRecord starting, boolean deferResume, int displayId,
5320 ActivityTaskManagerService.UpdateConfigurationResult result) {
5321 int changes = 0;
5322 boolean kept = true;
5323
5324 if (mWindowManager != null) {
5325 mWindowManager.deferSurfaceLayout();
5326 }
5327 try {
5328 if (values != null) {
5329 if (displayId == DEFAULT_DISPLAY) {
5330 // Override configuration of the default display duplicates global config, so
5331 // we're calling global config update instead for default display. It will also
5332 // apply the correct override config.
5333 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5334 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5335 } else {
5336 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5337 }
5338 }
5339
5340 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5341 } finally {
5342 if (mWindowManager != null) {
5343 mWindowManager.continueSurfaceLayout();
5344 }
5345 }
5346
5347 if (result != null) {
5348 result.changes = changes;
5349 result.activityRelaunched = !kept;
5350 }
5351 return kept;
5352 }
5353
5354 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5355 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005356 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005357 final int changes = mTempConfig.updateFrom(values);
5358 if (changes != 0) {
5359 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5360 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005361 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362
5363 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5364 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005365 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005366
Wale Ogunwale5c918702018-10-18 11:06:33 -07005367 // Post message to start process to avoid possible deadlock of calling into AMS with
5368 // the ATMS lock held.
5369 final Message msg = PooledLambda.obtainMessage(
5370 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005371 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005372 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005373 }
5374 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005375 return changes;
5376 }
5377
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 private void updateEventDispatchingLocked(boolean booted) {
5379 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5380 }
5381
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005382 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5383 final ContentResolver resolver = mContext.getContentResolver();
5384 Settings.System.putConfigurationForUser(resolver, config, userId);
5385 }
5386
5387 private void sendLocaleToMountDaemonMsg(Locale l) {
5388 try {
5389 IBinder service = ServiceManager.getService("mount");
5390 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5391 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5392 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5393 } catch (RemoteException e) {
5394 Log.e(TAG, "Error storing locale for decryption UI", e);
5395 }
5396 }
5397
Alison Cichowlas3e340502018-08-07 17:15:01 -04005398 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5399 mStartActivitySources.remove(permissionToken);
5400 mExpiredStartAsCallerTokens.add(permissionToken);
5401 }
5402
5403 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5404 mExpiredStartAsCallerTokens.remove(permissionToken);
5405 }
5406
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005407 boolean isActivityStartsLoggingEnabled() {
5408 return mAmInternal.isActivityStartsLoggingEnabled();
5409 }
5410
Michal Karpinski8596ded2018-11-14 14:43:48 +00005411 boolean isBackgroundActivityStartsEnabled() {
5412 return mAmInternal.isBackgroundActivityStartsEnabled();
5413 }
5414
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 void enableScreenAfterBoot(boolean booted) {
5416 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5417 SystemClock.uptimeMillis());
5418 mWindowManager.enableScreenAfterBoot();
5419
5420 synchronized (mGlobalLock) {
5421 updateEventDispatchingLocked(booted);
5422 }
5423 }
5424
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005425 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5426 if (r == null || !r.hasProcess()) {
5427 return KEY_DISPATCHING_TIMEOUT_MS;
5428 }
5429 return getInputDispatchingTimeoutLocked(r.app);
5430 }
5431
5432 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005433 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005434 }
5435
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 /**
5437 * Decide based on the configuration whether we should show the ANR,
5438 * crash, etc dialogs. The idea is that if there is no affordance to
5439 * press the on-screen buttons, or the user experience would be more
5440 * greatly impacted than the crash itself, we shouldn't show the dialog.
5441 *
5442 * A thought: SystemUI might also want to get told about this, the Power
5443 * dialog / global actions also might want different behaviors.
5444 */
5445 private void updateShouldShowDialogsLocked(Configuration config) {
5446 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5447 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5448 && config.navigation == Configuration.NAVIGATION_NONAV);
5449 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5450 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5451 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5452 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5453 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5454 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5455 HIDE_ERROR_DIALOGS, 0) != 0;
5456 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5457 }
5458
5459 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5460 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5461 FONT_SCALE, 1.0f, userId);
5462
5463 synchronized (this) {
5464 if (getGlobalConfiguration().fontScale == scaleFactor) {
5465 return;
5466 }
5467
5468 final Configuration configuration
5469 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5470 configuration.fontScale = scaleFactor;
5471 updatePersistentConfiguration(configuration, userId);
5472 }
5473 }
5474
5475 // Actually is sleeping or shutting down or whatever else in the future
5476 // is an inactive state.
5477 boolean isSleepingOrShuttingDownLocked() {
5478 return isSleepingLocked() || mShuttingDown;
5479 }
5480
5481 boolean isSleepingLocked() {
5482 return mSleeping;
5483 }
5484
Riddle Hsu16567132018-08-16 21:37:47 +08005485 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005487 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 if (task.isActivityTypeStandard()) {
5489 if (mCurAppTimeTracker != r.appTimeTracker) {
5490 // We are switching app tracking. Complete the current one.
5491 if (mCurAppTimeTracker != null) {
5492 mCurAppTimeTracker.stop();
5493 mH.obtainMessage(
5494 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005495 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005496 mCurAppTimeTracker = null;
5497 }
5498 if (r.appTimeTracker != null) {
5499 mCurAppTimeTracker = r.appTimeTracker;
5500 startTimeTrackingFocusedActivityLocked();
5501 }
5502 } else {
5503 startTimeTrackingFocusedActivityLocked();
5504 }
5505 } else {
5506 r.appTimeTracker = null;
5507 }
5508 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5509 // TODO: Probably not, because we don't want to resume voice on switching
5510 // back to this activity
5511 if (task.voiceInteractor != null) {
5512 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5513 } else {
5514 finishRunningVoiceLocked();
5515
5516 if (mLastResumedActivity != null) {
5517 final IVoiceInteractionSession session;
5518
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005519 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 if (lastResumedActivityTask != null
5521 && lastResumedActivityTask.voiceSession != null) {
5522 session = lastResumedActivityTask.voiceSession;
5523 } else {
5524 session = mLastResumedActivity.voiceSession;
5525 }
5526
5527 if (session != null) {
5528 // We had been in a voice interaction session, but now focused has
5529 // move to something different. Just finish the session, we can't
5530 // return to it and retain the proper state and synchronization with
5531 // the voice interaction service.
5532 finishVoiceTask(session);
5533 }
5534 }
5535 }
5536
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005537 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5538 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 }
5540 updateResumedAppTrace(r);
5541 mLastResumedActivity = r;
5542
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005543 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544
5545 applyUpdateLockStateLocked(r);
5546 applyUpdateVrModeLocked(r);
5547
5548 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005549 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550 r == null ? "NULL" : r.shortComponentName,
5551 reason);
5552 }
5553
5554 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5555 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005556 final ActivityTaskManagerInternal.SleepToken token =
5557 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 updateSleepIfNeededLocked();
5559 return token;
5560 }
5561 }
5562
5563 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005564 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005565 final boolean wasSleeping = mSleeping;
5566 boolean updateOomAdj = false;
5567
5568 if (!shouldSleep) {
5569 // If wasSleeping is true, we need to wake up activity manager state from when
5570 // we started sleeping. In either case, we need to apply the sleep tokens, which
5571 // will wake up stacks or put them to sleep as appropriate.
5572 if (wasSleeping) {
5573 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005574 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5575 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 startTimeTrackingFocusedActivityLocked();
5577 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005578 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5580 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005581 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 if (wasSleeping) {
5583 updateOomAdj = true;
5584 }
5585 } else if (!mSleeping && shouldSleep) {
5586 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005587 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5588 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 if (mCurAppTimeTracker != null) {
5590 mCurAppTimeTracker.stop();
5591 }
5592 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005593 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005594 mStackSupervisor.goingToSleepLocked();
5595 updateResumedAppTrace(null /* resumed */);
5596 updateOomAdj = true;
5597 }
5598 if (updateOomAdj) {
5599 mH.post(mAmInternal::updateOomAdj);
5600 }
5601 }
5602
5603 void updateOomAdj() {
5604 mH.post(mAmInternal::updateOomAdj);
5605 }
5606
Wale Ogunwale53783742018-09-16 10:21:51 -07005607 void updateCpuStats() {
5608 mH.post(mAmInternal::updateCpuStats);
5609 }
5610
Hui Yu03d12402018-12-06 18:00:37 -08005611 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5612 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005613 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5614 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005615 mH.sendMessage(m);
5616 }
5617
Hui Yu03d12402018-12-06 18:00:37 -08005618 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005619 ComponentName taskRoot = null;
5620 final TaskRecord task = activity.getTaskRecord();
5621 if (task != null) {
5622 final ActivityRecord rootActivity = task.getRootActivity();
5623 if (rootActivity != null) {
5624 taskRoot = rootActivity.mActivityComponent;
5625 }
5626 }
5627
Hui Yu03d12402018-12-06 18:00:37 -08005628 final Message m = PooledLambda.obtainMessage(
5629 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005630 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005631 mH.sendMessage(m);
5632 }
5633
Wale Ogunwale53783742018-09-16 10:21:51 -07005634 void setBooting(boolean booting) {
5635 mAmInternal.setBooting(booting);
5636 }
5637
5638 boolean isBooting() {
5639 return mAmInternal.isBooting();
5640 }
5641
5642 void setBooted(boolean booted) {
5643 mAmInternal.setBooted(booted);
5644 }
5645
5646 boolean isBooted() {
5647 return mAmInternal.isBooted();
5648 }
5649
5650 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5651 mH.post(() -> {
5652 if (finishBooting) {
5653 mAmInternal.finishBooting();
5654 }
5655 if (enableScreen) {
5656 mInternal.enableScreenAfterBoot(isBooted());
5657 }
5658 });
5659 }
5660
5661 void setHeavyWeightProcess(ActivityRecord root) {
5662 mHeavyWeightProcess = root.app;
5663 final Message m = PooledLambda.obtainMessage(
5664 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005665 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005666 mH.sendMessage(m);
5667 }
5668
5669 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5670 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5671 return;
5672 }
5673
5674 mHeavyWeightProcess = null;
5675 final Message m = PooledLambda.obtainMessage(
5676 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5677 proc.mUserId);
5678 mH.sendMessage(m);
5679 }
5680
5681 private void cancelHeavyWeightProcessNotification(int userId) {
5682 final INotificationManager inm = NotificationManager.getService();
5683 if (inm == null) {
5684 return;
5685 }
5686 try {
5687 inm.cancelNotificationWithTag("android", null,
5688 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5689 } catch (RuntimeException e) {
5690 Slog.w(TAG, "Error canceling notification for service", e);
5691 } catch (RemoteException e) {
5692 }
5693
5694 }
5695
5696 private void postHeavyWeightProcessNotification(
5697 WindowProcessController proc, Intent intent, int userId) {
5698 if (proc == null) {
5699 return;
5700 }
5701
5702 final INotificationManager inm = NotificationManager.getService();
5703 if (inm == null) {
5704 return;
5705 }
5706
5707 try {
5708 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5709 String text = mContext.getString(R.string.heavy_weight_notification,
5710 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5711 Notification notification =
5712 new Notification.Builder(context,
5713 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5714 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5715 .setWhen(0)
5716 .setOngoing(true)
5717 .setTicker(text)
5718 .setColor(mContext.getColor(
5719 com.android.internal.R.color.system_notification_accent_color))
5720 .setContentTitle(text)
5721 .setContentText(
5722 mContext.getText(R.string.heavy_weight_notification_detail))
5723 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5724 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5725 new UserHandle(userId)))
5726 .build();
5727 try {
5728 inm.enqueueNotificationWithTag("android", "android", null,
5729 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5730 } catch (RuntimeException e) {
5731 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5732 } catch (RemoteException e) {
5733 }
5734 } catch (PackageManager.NameNotFoundException e) {
5735 Slog.w(TAG, "Unable to create context for heavy notification", e);
5736 }
5737
5738 }
5739
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005740 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5741 IBinder token, String resultWho, int requestCode, Intent[] intents,
5742 String[] resolvedTypes, int flags, Bundle bOptions) {
5743
5744 ActivityRecord activity = null;
5745 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5746 activity = ActivityRecord.isInStackLocked(token);
5747 if (activity == null) {
5748 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5749 return null;
5750 }
5751 if (activity.finishing) {
5752 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5753 return null;
5754 }
5755 }
5756
5757 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5758 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5759 bOptions);
5760 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5761 if (noCreate) {
5762 return rec;
5763 }
5764 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5765 if (activity.pendingResults == null) {
5766 activity.pendingResults = new HashSet<>();
5767 }
5768 activity.pendingResults.add(rec.ref);
5769 }
5770 return rec;
5771 }
5772
Andrii Kulian52d255c2018-07-13 11:32:19 -07005773 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005774 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005775 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005776 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5777 mCurAppTimeTracker.start(resumedActivity.packageName);
5778 }
5779 }
5780
5781 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5782 if (mTracedResumedActivity != null) {
5783 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5784 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5785 }
5786 if (resumed != null) {
5787 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5788 constructResumedTraceName(resumed.packageName), 0);
5789 }
5790 mTracedResumedActivity = resumed;
5791 }
5792
5793 private String constructResumedTraceName(String packageName) {
5794 return "focused app: " + packageName;
5795 }
5796
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005797 /** Applies latest configuration and/or visibility updates if needed. */
5798 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5799 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005800 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005801 // mainStack is null during startup.
5802 if (mainStack != null) {
5803 if (changes != 0 && starting == null) {
5804 // If the configuration changed, and the caller is not already
5805 // in the process of starting an activity, then find the top
5806 // activity to check if its configuration needs to change.
5807 starting = mainStack.topRunningActivityLocked();
5808 }
5809
5810 if (starting != null) {
5811 kept = starting.ensureActivityConfiguration(changes,
5812 false /* preserveWindow */);
5813 // And we need to make sure at this point that all other activities
5814 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005815 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005816 !PRESERVE_WINDOWS);
5817 }
5818 }
5819
5820 return kept;
5821 }
5822
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005823 void scheduleAppGcsLocked() {
5824 mH.post(() -> mAmInternal.scheduleAppGcs());
5825 }
5826
Wale Ogunwale53783742018-09-16 10:21:51 -07005827 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5828 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5829 }
5830
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005831 /**
5832 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5833 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5834 * on demand.
5835 */
5836 IPackageManager getPackageManager() {
5837 return AppGlobals.getPackageManager();
5838 }
5839
5840 PackageManagerInternal getPackageManagerInternalLocked() {
5841 if (mPmInternal == null) {
5842 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5843 }
5844 return mPmInternal;
5845 }
5846
Hai Zhangf4da9be2019-05-01 13:46:06 +08005847 PermissionPolicyInternal getPermissionPolicyInternal() {
5848 if (mPermissionPolicyInternal == null) {
5849 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5850 }
5851 return mPermissionPolicyInternal;
5852 }
5853
Wale Ogunwale008163e2018-07-23 23:11:08 -07005854 AppWarnings getAppWarningsLocked() {
5855 return mAppWarnings;
5856 }
5857
Wale Ogunwale214f3482018-10-04 11:00:47 -07005858 Intent getHomeIntent() {
5859 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5860 intent.setComponent(mTopComponent);
5861 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5862 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5863 intent.addCategory(Intent.CATEGORY_HOME);
5864 }
5865 return intent;
5866 }
5867
Chilun2ef71f72018-11-16 17:57:15 +08005868 /**
5869 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5870 * activities.
5871 *
5872 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5873 * component defined in config_secondaryHomeComponent.
5874 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5875 */
5876 Intent getSecondaryHomeIntent(String preferredPackage) {
5877 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005878 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5879 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5880 if (preferredPackage == null || useSystemProvidedLauncher) {
5881 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005882 final String secondaryHomeComponent = mContext.getResources().getString(
5883 com.android.internal.R.string.config_secondaryHomeComponent);
5884 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5885 } else {
5886 intent.setPackage(preferredPackage);
5887 }
5888 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5889 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5890 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5891 }
5892 return intent;
5893 }
5894
Wale Ogunwale214f3482018-10-04 11:00:47 -07005895 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5896 if (info == null) return null;
5897 ApplicationInfo newInfo = new ApplicationInfo(info);
5898 newInfo.initForUser(userId);
5899 return newInfo;
5900 }
5901
Wale Ogunwale9c103022018-10-18 07:44:54 -07005902 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005903 if (uid == SYSTEM_UID) {
5904 // The system gets to run in any process. If there are multiple processes with the same
5905 // uid, just pick the first (this should never happen).
5906 final SparseArray<WindowProcessController> procs =
5907 mProcessNames.getMap().get(processName);
5908 if (procs == null) return null;
5909 final int procCount = procs.size();
5910 for (int i = 0; i < procCount; i++) {
5911 final int procUid = procs.keyAt(i);
5912 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5913 // Don't use an app process or different user process for system component.
5914 continue;
5915 }
5916 return procs.valueAt(i);
5917 }
5918 }
5919
5920 return mProcessNames.get(processName, uid);
5921 }
5922
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005923 WindowProcessController getProcessController(IApplicationThread thread) {
5924 if (thread == null) {
5925 return null;
5926 }
5927
5928 final IBinder threadBinder = thread.asBinder();
5929 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5930 for (int i = pmap.size()-1; i >= 0; i--) {
5931 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5932 for (int j = procs.size() - 1; j >= 0; j--) {
5933 final WindowProcessController proc = procs.valueAt(j);
5934 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5935 return proc;
5936 }
5937 }
5938 }
5939
5940 return null;
5941 }
5942
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005943 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005944 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005945 if (proc == null) return null;
5946 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5947 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005948 }
5949 return null;
5950 }
5951
Riddle Hsua0536432019-02-16 00:38:59 +08005952 int getUidState(int uid) {
5953 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005954 }
5955
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005956 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005957 // A uid is considered to be foreground if it has a visible non-toast window.
5958 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005959 }
5960
Ricky Wai96f5c352019-04-10 18:40:17 +01005961 boolean isDeviceOwner(int uid) {
5962 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005963 }
5964
Ricky Wai96f5c352019-04-10 18:40:17 +01005965 void setDeviceOwnerUid(int uid) {
5966 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005967 }
5968
Wale Ogunwale9de19442018-10-18 19:05:03 -07005969 /**
5970 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5971 * the whitelist
5972 */
5973 String getPendingTempWhitelistTagForUidLocked(int uid) {
5974 return mPendingTempWhitelist.get(uid);
5975 }
5976
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005977 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5978 if (true || Build.IS_USER) {
5979 return;
5980 }
5981
5982 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5983 StrictMode.allowThreadDiskWrites();
5984 try {
5985 File tracesDir = new File("/data/anr");
5986 File tracesFile = null;
5987 try {
5988 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5989
5990 StringBuilder sb = new StringBuilder();
5991 Time tobj = new Time();
5992 tobj.set(System.currentTimeMillis());
5993 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5994 sb.append(": ");
5995 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5996 sb.append(" since ");
5997 sb.append(msg);
5998 FileOutputStream fos = new FileOutputStream(tracesFile);
5999 fos.write(sb.toString().getBytes());
6000 if (app == null) {
6001 fos.write("\n*** No application process!".getBytes());
6002 }
6003 fos.close();
6004 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6005 } catch (IOException e) {
6006 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6007 return;
6008 }
6009
6010 if (app != null && app.getPid() > 0) {
6011 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6012 firstPids.add(app.getPid());
6013 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6014 }
6015
6016 File lastTracesFile = null;
6017 File curTracesFile = null;
6018 for (int i=9; i>=0; i--) {
6019 String name = String.format(Locale.US, "slow%02d.txt", i);
6020 curTracesFile = new File(tracesDir, name);
6021 if (curTracesFile.exists()) {
6022 if (lastTracesFile != null) {
6023 curTracesFile.renameTo(lastTracesFile);
6024 } else {
6025 curTracesFile.delete();
6026 }
6027 }
6028 lastTracesFile = curTracesFile;
6029 }
6030 tracesFile.renameTo(curTracesFile);
6031 } finally {
6032 StrictMode.setThreadPolicy(oldPolicy);
6033 }
6034 }
6035
Michal Karpinskida34cd42019-04-02 19:46:52 +01006036 boolean isAssociatedCompanionApp(int userId, int uid) {
6037 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6038 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006039 return false;
6040 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006041 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006042 }
6043
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006044 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006045 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006046
6047
Wale Ogunwale98875612018-10-12 07:53:02 -07006048 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6049 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006050
Riddle Hsud93a6c42018-11-29 21:50:06 +08006051 H(Looper looper) {
6052 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006053 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006054
6055 @Override
6056 public void handleMessage(Message msg) {
6057 switch (msg.what) {
6058 case REPORT_TIME_TRACKER_MSG: {
6059 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6060 tracker.deliverResult(mContext);
6061 } break;
6062 }
6063 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006064 }
6065
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006066 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006067 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006068
6069 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006070 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006071 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006072
6073 @Override
6074 public void handleMessage(Message msg) {
6075 switch (msg.what) {
6076 case DISMISS_DIALOG_UI_MSG: {
6077 final Dialog d = (Dialog) msg.obj;
6078 d.dismiss();
6079 break;
6080 }
6081 }
6082 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006083 }
6084
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006085 final class LocalService extends ActivityTaskManagerInternal {
6086 @Override
6087 public SleepToken acquireSleepToken(String tag, int displayId) {
6088 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006089 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006090 }
6091
6092 @Override
6093 public ComponentName getHomeActivityForUser(int userId) {
6094 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006095 final ActivityRecord homeActivity =
6096 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006097 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 }
6099 }
6100
6101 @Override
6102 public void onLocalVoiceInteractionStarted(IBinder activity,
6103 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6104 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006105 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 }
6107 }
6108
6109 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006110 public void notifyAppTransitionStarting(SparseIntArray reasons,
6111 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 synchronized (mGlobalLock) {
6113 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6114 reasons, timestamp);
6115 }
6116 }
6117
6118 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006119 public void notifySingleTaskDisplayDrawn(int displayId) {
6120 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6121 }
6122
6123 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006124 public void notifyAppTransitionFinished() {
6125 synchronized (mGlobalLock) {
6126 mStackSupervisor.notifyAppTransitionDone();
6127 }
6128 }
6129
6130 @Override
6131 public void notifyAppTransitionCancelled() {
6132 synchronized (mGlobalLock) {
6133 mStackSupervisor.notifyAppTransitionDone();
6134 }
6135 }
6136
6137 @Override
6138 public List<IBinder> getTopVisibleActivities() {
6139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006140 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006141 }
6142 }
6143
6144 @Override
6145 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006147 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150
6151 @Override
6152 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6153 Bundle bOptions) {
6154 Preconditions.checkNotNull(intents, "intents");
6155 final String[] resolvedTypes = new String[intents.length];
6156
6157 // UID of the package on user userId.
6158 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6159 // packageUid may not be initialized.
6160 int packageUid = 0;
6161 final long ident = Binder.clearCallingIdentity();
6162
6163 try {
6164 for (int i = 0; i < intents.length; i++) {
6165 resolvedTypes[i] =
6166 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6167 }
6168
6169 packageUid = AppGlobals.getPackageManager().getPackageUid(
6170 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6171 } catch (RemoteException e) {
6172 // Shouldn't happen.
6173 } finally {
6174 Binder.restoreCallingIdentity(ident);
6175 }
6176
Riddle Hsu591bf612019-02-14 17:55:31 +08006177 return getActivityStartController().startActivitiesInPackage(
6178 packageUid, packageName,
6179 intents, resolvedTypes, null /* resultTo */,
6180 SafeActivityOptions.fromBundle(bOptions), userId,
6181 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6182 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006183 }
6184
6185 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006186 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6187 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6188 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6189 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006190 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006191 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006192 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6193 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6194 userId, validateIncomingUser, originatingPendingIntent,
6195 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006196 }
6197 }
6198
6199 @Override
6200 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6201 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6202 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6203 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006204 PendingIntentRecord originatingPendingIntent,
6205 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006206 synchronized (mGlobalLock) {
6207 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6208 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6209 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006210 validateIncomingUser, originatingPendingIntent,
6211 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006212 }
6213 }
6214
6215 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6217 Intent intent, Bundle options, int userId) {
6218 return ActivityTaskManagerService.this.startActivityAsUser(
6219 caller, callerPacakge, intent,
6220 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6221 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6222 false /*validateIncomingUser*/);
6223 }
6224
6225 @Override
lumark588a3e82018-07-20 18:53:54 +08006226 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 synchronized (mGlobalLock) {
6228
6229 // We might change the visibilities here, so prepare an empty app transition which
6230 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006231 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006232 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006233 if (activityDisplay == null) {
6234 return;
6235 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006236 final DisplayContent dc = activityDisplay.mDisplayContent;
6237 final boolean wasTransitionSet =
6238 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006240 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006242 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243
6244 // If there was a transition set already we don't want to interfere with it as we
6245 // might be starting it too early.
6246 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006247 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
6249 }
6250 if (callback != null) {
6251 callback.run();
6252 }
6253 }
6254
6255 @Override
6256 public void notifyKeyguardTrustedChanged() {
6257 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006258 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006259 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 }
6261 }
6262 }
6263
6264 /**
6265 * Called after virtual display Id is updated by
6266 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6267 * {@param vrVr2dDisplayId}.
6268 */
6269 @Override
6270 public void setVr2dDisplayId(int vr2dDisplayId) {
6271 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6272 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006273 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 }
6275 }
6276
6277 @Override
6278 public void setFocusedActivity(IBinder token) {
6279 synchronized (mGlobalLock) {
6280 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6281 if (r == null) {
6282 throw new IllegalArgumentException(
6283 "setFocusedActivity: No activity record matching token=" + token);
6284 }
Louis Chang19443452018-10-09 12:10:21 +08006285 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006286 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006287 }
6288 }
6289 }
6290
6291 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006292 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006293 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 }
6295
6296 @Override
6297 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006298 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 }
6300
6301 @Override
6302 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006303 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006304 }
6305
6306 @Override
6307 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6308 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6309 }
6310
6311 @Override
6312 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006313 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006315
6316 @Override
6317 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6318 synchronized (mGlobalLock) {
6319 mActiveVoiceInteractionServiceComponent = component;
6320 }
6321 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006322
6323 @Override
6324 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6325 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6326 return;
6327 }
6328 synchronized (mGlobalLock) {
6329 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6330 if (types == null) {
6331 if (uid < 0) {
6332 return;
6333 }
6334 types = new ArrayMap<>();
6335 mAllowAppSwitchUids.put(userId, types);
6336 }
6337 if (uid < 0) {
6338 types.remove(type);
6339 } else {
6340 types.put(type, uid);
6341 }
6342 }
6343 }
6344
6345 @Override
6346 public void onUserStopped(int userId) {
6347 synchronized (mGlobalLock) {
6348 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6349 mAllowAppSwitchUids.remove(userId);
6350 }
6351 }
6352
6353 @Override
6354 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6355 synchronized (mGlobalLock) {
6356 return ActivityTaskManagerService.this.isGetTasksAllowed(
6357 caller, callingPid, callingUid);
6358 }
6359 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360
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 onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 mProcessNames.put(proc.mName, proc.mUid, proc);
6366 }
6367 }
6368
Riddle Hsua0536432019-02-16 00:38:59 +08006369 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006370 @Override
6371 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006372 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006373 mProcessNames.remove(name, uid);
6374 }
6375 }
6376
Riddle Hsua0536432019-02-16 00:38:59 +08006377 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006378 @Override
6379 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006380 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006381 if (proc == mHomeProcess) {
6382 mHomeProcess = null;
6383 }
6384 if (proc == mPreviousProcess) {
6385 mPreviousProcess = null;
6386 }
6387 }
6388 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006389
Riddle Hsua0536432019-02-16 00:38:59 +08006390 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006391 @Override
6392 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006393 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006394 return mTopProcessState;
6395 }
6396 }
6397
Riddle Hsua0536432019-02-16 00:38:59 +08006398 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006399 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006400 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006401 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 return proc == mHeavyWeightProcess;
6403 }
6404 }
6405
Riddle Hsua0536432019-02-16 00:38:59 +08006406 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006407 @Override
6408 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006409 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006410 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6411 }
6412 }
6413
6414 @Override
6415 public void finishHeavyWeightApp() {
6416 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006417 if (mHeavyWeightProcess != null) {
6418 mHeavyWeightProcess.finishActivities();
6419 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006420 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6421 mHeavyWeightProcess);
6422 }
6423 }
6424
Riddle Hsua0536432019-02-16 00:38:59 +08006425 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006426 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006427 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006428 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006429 return isSleepingLocked();
6430 }
6431 }
6432
6433 @Override
6434 public boolean isShuttingDown() {
6435 synchronized (mGlobalLock) {
6436 return mShuttingDown;
6437 }
6438 }
6439
6440 @Override
6441 public boolean shuttingDown(boolean booted, int timeout) {
6442 synchronized (mGlobalLock) {
6443 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006444 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006445 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006446 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006447 return mStackSupervisor.shutdownLocked(timeout);
6448 }
6449 }
6450
6451 @Override
6452 public void enableScreenAfterBoot(boolean booted) {
6453 synchronized (mGlobalLock) {
6454 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6455 SystemClock.uptimeMillis());
6456 mWindowManager.enableScreenAfterBoot();
6457 updateEventDispatchingLocked(booted);
6458 }
6459 }
6460
6461 @Override
6462 public boolean showStrictModeViolationDialog() {
6463 synchronized (mGlobalLock) {
6464 return mShowDialogs && !mSleeping && !mShuttingDown;
6465 }
6466 }
6467
6468 @Override
6469 public void showSystemReadyErrorDialogsIfNeeded() {
6470 synchronized (mGlobalLock) {
6471 try {
6472 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6473 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6474 + " data partition or your device will be unstable.");
6475 mUiHandler.post(() -> {
6476 if (mShowDialogs) {
6477 AlertDialog d = new BaseErrorDialog(mUiContext);
6478 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6479 d.setCancelable(false);
6480 d.setTitle(mUiContext.getText(R.string.android_system_label));
6481 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6482 d.setButton(DialogInterface.BUTTON_POSITIVE,
6483 mUiContext.getText(R.string.ok),
6484 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6485 d.show();
6486 }
6487 });
6488 }
6489 } catch (RemoteException e) {
6490 }
6491
6492 if (!Build.isBuildConsistent()) {
6493 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6494 mUiHandler.post(() -> {
6495 if (mShowDialogs) {
6496 AlertDialog d = new BaseErrorDialog(mUiContext);
6497 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6498 d.setCancelable(false);
6499 d.setTitle(mUiContext.getText(R.string.android_system_label));
6500 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6501 d.setButton(DialogInterface.BUTTON_POSITIVE,
6502 mUiContext.getText(R.string.ok),
6503 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6504 d.show();
6505 }
6506 });
6507 }
6508 }
6509 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006510
6511 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006512 public void onProcessMapped(int pid, WindowProcessController proc) {
6513 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006514 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006515 }
6516 }
6517
6518 @Override
6519 public void onProcessUnMapped(int pid) {
6520 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006522 }
6523 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006524
6525 @Override
6526 public void onPackageDataCleared(String name) {
6527 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006528 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006529 mAppWarnings.onPackageDataCleared(name);
6530 }
6531 }
6532
6533 @Override
6534 public void onPackageUninstalled(String name) {
6535 synchronized (mGlobalLock) {
6536 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006537 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006538 }
6539 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006540
6541 @Override
6542 public void onPackageAdded(String name, boolean replacing) {
6543 synchronized (mGlobalLock) {
6544 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6545 }
6546 }
6547
6548 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006549 public void onPackageReplaced(ApplicationInfo aInfo) {
6550 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006551 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006552 }
6553 }
6554
6555 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006556 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6557 synchronized (mGlobalLock) {
6558 return compatibilityInfoForPackageLocked(ai);
6559 }
6560 }
6561
Yunfan Chen75157d72018-07-27 14:47:21 +09006562 /**
6563 * Set the corresponding display information for the process global configuration. To be
6564 * called when we need to show IME on a different display.
6565 *
6566 * @param pid The process id associated with the IME window.
6567 * @param displayId The ID of the display showing the IME.
6568 */
6569 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006570 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006571 // Don't update process-level configuration for Multi-Client IME process since other
6572 // IMEs on other displays will also receive this configuration change due to IME
6573 // services use the same application config/context.
6574 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006575
Yunfan Chen75157d72018-07-27 14:47:21 +09006576 if (pid == MY_PID || pid < 0) {
6577 if (DEBUG_CONFIGURATION) {
6578 Slog.w(TAG,
6579 "Trying to update display configuration for system/invalid process.");
6580 }
6581 return;
6582 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006583 synchronized (mGlobalLock) {
6584 final ActivityDisplay activityDisplay =
6585 mRootActivityContainer.getActivityDisplay(displayId);
6586 if (activityDisplay == null) {
6587 // Call might come when display is not yet added or has been removed.
6588 if (DEBUG_CONFIGURATION) {
6589 Slog.w(TAG, "Trying to update display configuration for non-existing "
6590 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006591 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006592 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006593 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006594 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006595 if (process == null) {
6596 if (DEBUG_CONFIGURATION) {
6597 Slog.w(TAG, "Trying to update display configuration for invalid "
6598 + "process, pid=" + pid);
6599 }
6600 return;
6601 }
6602 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6603 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006604 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006605
6606 @Override
6607 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006608 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006609 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006610 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6611 if (r != null && r.getActivityStack() != null) {
6612 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6613 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006614 }
6615 }
6616 }
6617
6618 @Override
6619 public void clearPendingResultForActivity(IBinder activityToken,
6620 WeakReference<PendingIntentRecord> pir) {
6621 synchronized (mGlobalLock) {
6622 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6623 if (r != null && r.pendingResults != null) {
6624 r.pendingResults.remove(pir);
6625 }
6626 }
6627 }
6628
6629 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006630 public ActivityTokens getTopActivityForTask(int taskId) {
6631 synchronized (mGlobalLock) {
6632 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6633 if (taskRecord == null) {
6634 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6635 + " Requested task not found");
6636 return null;
6637 }
6638 final ActivityRecord activity = taskRecord.getTopActivity();
6639 if (activity == null) {
6640 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6641 + " Requested activity not found");
6642 return null;
6643 }
6644 if (!activity.attachedToProcess()) {
6645 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6646 + activity);
6647 return null;
6648 }
6649 return new ActivityTokens(activity.appToken, activity.assistToken,
6650 activity.app.getThread());
6651 }
6652 }
6653
6654 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006655 public IIntentSender getIntentSender(int type, String packageName,
6656 int callingUid, int userId, IBinder token, String resultWho,
6657 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6658 Bundle bOptions) {
6659 synchronized (mGlobalLock) {
6660 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6661 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6662 }
6663 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006664
6665 @Override
6666 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6667 synchronized (mGlobalLock) {
6668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6669 if (r == null) {
6670 return null;
6671 }
6672 if (r.mServiceConnectionsHolder == null) {
6673 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6674 ActivityTaskManagerService.this, r);
6675 }
6676
6677 return r.mServiceConnectionsHolder;
6678 }
6679 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680
6681 @Override
6682 public Intent getHomeIntent() {
6683 synchronized (mGlobalLock) {
6684 return ActivityTaskManagerService.this.getHomeIntent();
6685 }
6686 }
6687
6688 @Override
6689 public boolean startHomeActivity(int userId, String reason) {
6690 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006691 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006692 }
6693 }
6694
6695 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006696 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006697 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006698 synchronized (mGlobalLock) {
6699 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006700 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006701 }
Chilun8b1f1be2019-03-13 17:14:36 +08006702 }
6703
6704 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006705 public boolean startHomeOnAllDisplays(int userId, String reason) {
6706 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006707 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006708 }
6709 }
6710
Riddle Hsua0536432019-02-16 00:38:59 +08006711 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006712 @Override
6713 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006714 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715 if (mFactoryTest == FACTORY_TEST_OFF) {
6716 return false;
6717 }
6718 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6719 && wpc.mName.equals(mTopComponent.getPackageName())) {
6720 return true;
6721 }
6722 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6723 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6724 }
6725 }
6726
6727 @Override
6728 public void updateTopComponentForFactoryTest() {
6729 synchronized (mGlobalLock) {
6730 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6731 return;
6732 }
6733 final ResolveInfo ri = mContext.getPackageManager()
6734 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6735 final CharSequence errorMsg;
6736 if (ri != null) {
6737 final ActivityInfo ai = ri.activityInfo;
6738 final ApplicationInfo app = ai.applicationInfo;
6739 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6740 mTopAction = Intent.ACTION_FACTORY_TEST;
6741 mTopData = null;
6742 mTopComponent = new ComponentName(app.packageName, ai.name);
6743 errorMsg = null;
6744 } else {
6745 errorMsg = mContext.getResources().getText(
6746 com.android.internal.R.string.factorytest_not_system);
6747 }
6748 } else {
6749 errorMsg = mContext.getResources().getText(
6750 com.android.internal.R.string.factorytest_no_action);
6751 }
6752 if (errorMsg == null) {
6753 return;
6754 }
6755
6756 mTopAction = null;
6757 mTopData = null;
6758 mTopComponent = null;
6759 mUiHandler.post(() -> {
6760 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6761 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006762 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763 });
6764 }
6765 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766
Riddle Hsua0536432019-02-16 00:38:59 +08006767 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 @Override
6769 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6770 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006771 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006773 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774
6775 wpc.clearRecentTasks();
6776 wpc.clearActivities();
6777
6778 if (wpc.isInstrumenting()) {
6779 finishInstrumentationCallback.run();
6780 }
6781
Jorim Jaggid0752812018-10-16 16:07:20 +02006782 if (!restarting && hasVisibleActivities) {
6783 mWindowManager.deferSurfaceLayout();
6784 try {
6785 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6786 // If there was nothing to resume, and we are not already restarting
6787 // this process, but there is a visible activity that is hosted by the
6788 // process...then make sure all visible activities are running, taking
6789 // care of restarting this process.
6790 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6791 !PRESERVE_WINDOWS);
6792 }
6793 } finally {
6794 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006795 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 }
6797 }
6798 }
6799
6800 @Override
6801 public void closeSystemDialogs(String reason) {
6802 enforceNotIsolatedCaller("closeSystemDialogs");
6803
6804 final int pid = Binder.getCallingPid();
6805 final int uid = Binder.getCallingUid();
6806 final long origId = Binder.clearCallingIdentity();
6807 try {
6808 synchronized (mGlobalLock) {
6809 // Only allow this from foreground processes, so that background
6810 // applications can't abuse it to prevent system UI from being shown.
6811 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006812 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 if (!proc.isPerceptible()) {
6814 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6815 + " from background process " + proc);
6816 return;
6817 }
6818 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 mWindowManager.closeSystemDialogs(reason);
6820
Wale Ogunwaled32da472018-11-16 07:19:28 -08006821 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006823 // Call into AM outside the synchronized block.
6824 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 } finally {
6826 Binder.restoreCallingIdentity(origId);
6827 }
6828 }
6829
6830 @Override
6831 public void cleanupDisabledPackageComponents(
6832 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6833 synchronized (mGlobalLock) {
6834 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006835 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006837 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 mStackSupervisor.scheduleIdleLocked();
6839 }
6840
6841 // Clean-up disabled tasks
6842 getRecentTasks().cleanupDisabledPackageTasksLocked(
6843 packageName, disabledClasses, userId);
6844 }
6845 }
6846
6847 @Override
6848 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6849 int userId) {
6850 synchronized (mGlobalLock) {
6851
6852 boolean didSomething =
6853 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006854 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 null, doit, evenPersistent, userId);
6856 return didSomething;
6857 }
6858 }
6859
6860 @Override
6861 public void resumeTopActivities(boolean scheduleIdle) {
6862 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006863 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 if (scheduleIdle) {
6865 mStackSupervisor.scheduleIdleLocked();
6866 }
6867 }
6868 }
6869
Riddle Hsua0536432019-02-16 00:38:59 +08006870 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 @Override
6872 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006873 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6875 }
6876 }
6877
Riddle Hsua0536432019-02-16 00:38:59 +08006878 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 @Override
6880 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006881 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006882 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006883 }
6884 }
6885
6886 @Override
6887 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6888 try {
6889 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6890 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6891 }
6892 } catch (RemoteException ex) {
6893 throw new SecurityException("Fail to check is caller a privileged app", ex);
6894 }
6895
6896 synchronized (mGlobalLock) {
6897 final long ident = Binder.clearCallingIdentity();
6898 try {
6899 if (mAmInternal.shouldConfirmCredentials(userId)) {
6900 if (mKeyguardController.isKeyguardLocked()) {
6901 // Showing launcher to avoid user entering credential twice.
6902 startHomeActivity(currentUserId, "notifyLockedProfile");
6903 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006904 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
6906 } finally {
6907 Binder.restoreCallingIdentity(ident);
6908 }
6909 }
6910 }
6911
6912 @Override
6913 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6914 mAmInternal.enforceCallingPermission(
6915 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6916
6917 synchronized (mGlobalLock) {
6918 final long ident = Binder.clearCallingIdentity();
6919 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006920 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6921 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6924 UserHandle.CURRENT);
6925 } finally {
6926 Binder.restoreCallingIdentity(ident);
6927 }
6928 }
6929 }
6930
6931 @Override
6932 public void writeActivitiesToProto(ProtoOutputStream proto) {
6933 synchronized (mGlobalLock) {
6934 // The output proto of "activity --proto activities"
6935 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006936 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006937 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6938 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006939 }
6940 }
6941
6942 @Override
6943 public void saveANRState(String reason) {
6944 synchronized (mGlobalLock) {
6945 final StringWriter sw = new StringWriter();
6946 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6947 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6948 if (reason != null) {
6949 pw.println(" Reason: " + reason);
6950 }
6951 pw.println();
6952 getActivityStartController().dump(pw, " ", null);
6953 pw.println();
6954 pw.println("-------------------------------------------------------------------------------");
6955 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6956 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6957 "" /* header */);
6958 pw.println();
6959 pw.close();
6960
6961 mLastANRState = sw.toString();
6962 }
6963 }
6964
6965 @Override
6966 public void clearSavedANRState() {
6967 synchronized (mGlobalLock) {
6968 mLastANRState = null;
6969 }
6970 }
6971
6972 @Override
6973 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6974 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6975 synchronized (mGlobalLock) {
6976 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6977 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6978 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6979 dumpLastANRLocked(pw);
6980 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6981 dumpLastANRTracesLocked(pw);
6982 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6983 dumpActivityStarterLocked(pw, dumpPackage);
6984 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6985 dumpActivityContainersLocked(pw);
6986 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6987 if (getRecentTasks() != null) {
6988 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6989 }
6990 }
6991 }
6992 }
6993
6994 @Override
6995 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6996 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6997 int wakefulness) {
6998 synchronized (mGlobalLock) {
6999 if (mHomeProcess != null && (dumpPackage == null
7000 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7001 if (needSep) {
7002 pw.println();
7003 needSep = false;
7004 }
7005 pw.println(" mHomeProcess: " + mHomeProcess);
7006 }
7007 if (mPreviousProcess != null && (dumpPackage == null
7008 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7009 if (needSep) {
7010 pw.println();
7011 needSep = false;
7012 }
7013 pw.println(" mPreviousProcess: " + mPreviousProcess);
7014 }
7015 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7016 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7017 StringBuilder sb = new StringBuilder(128);
7018 sb.append(" mPreviousProcessVisibleTime: ");
7019 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7020 pw.println(sb);
7021 }
7022 if (mHeavyWeightProcess != null && (dumpPackage == null
7023 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7024 if (needSep) {
7025 pw.println();
7026 needSep = false;
7027 }
7028 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7029 }
7030 if (dumpPackage == null) {
7031 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007032 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034 if (dumpAll) {
7035 if (dumpPackage == null) {
7036 pw.println(" mConfigWillChange: "
7037 + getTopDisplayFocusedStack().mConfigWillChange);
7038 }
7039 if (mCompatModePackages.getPackages().size() > 0) {
7040 boolean printed = false;
7041 for (Map.Entry<String, Integer> entry
7042 : mCompatModePackages.getPackages().entrySet()) {
7043 String pkg = entry.getKey();
7044 int mode = entry.getValue();
7045 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7046 continue;
7047 }
7048 if (!printed) {
7049 pw.println(" mScreenCompatPackages:");
7050 printed = true;
7051 }
7052 pw.println(" " + pkg + ": " + mode);
7053 }
7054 }
7055 }
7056
7057 if (dumpPackage == null) {
7058 pw.println(" mWakefulness="
7059 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007060 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007061 if (mRunningVoice != null) {
7062 pw.println(" mRunningVoice=" + mRunningVoice);
7063 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7064 }
7065 pw.println(" mSleeping=" + mSleeping);
7066 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7067 pw.println(" mVrController=" + mVrController);
7068 }
7069 if (mCurAppTimeTracker != null) {
7070 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7071 }
7072 if (mAllowAppSwitchUids.size() > 0) {
7073 boolean printed = false;
7074 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7075 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7076 for (int j = 0; j < types.size(); j++) {
7077 if (dumpPackage == null ||
7078 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7079 if (needSep) {
7080 pw.println();
7081 needSep = false;
7082 }
7083 if (!printed) {
7084 pw.println(" mAllowAppSwitchUids:");
7085 printed = true;
7086 }
7087 pw.print(" User ");
7088 pw.print(mAllowAppSwitchUids.keyAt(i));
7089 pw.print(": Type ");
7090 pw.print(types.keyAt(j));
7091 pw.print(" = ");
7092 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7093 pw.println();
7094 }
7095 }
7096 }
7097 }
7098 if (dumpPackage == null) {
7099 if (mController != null) {
7100 pw.println(" mController=" + mController
7101 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7102 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007103 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7104 pw.println(" mLaunchingActivityWakeLock="
7105 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 }
7107
7108 return needSep;
7109 }
7110 }
7111
7112 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007113 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7114 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 synchronized (mGlobalLock) {
7116 if (dumpPackage == null) {
7117 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7118 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007119 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7120 if (mRunningVoice != null) {
7121 final long vrToken = proto.start(
7122 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7123 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7124 mRunningVoice.toString());
7125 mVoiceWakeLock.writeToProto(
7126 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7127 proto.end(vrToken);
7128 }
7129 mVrController.writeToProto(proto,
7130 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 if (mController != null) {
7132 final long token = proto.start(CONTROLLER);
7133 proto.write(CONTROLLER, mController.toString());
7134 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7135 proto.end(token);
7136 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007137 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7138 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7139 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141
7142 if (mHomeProcess != null && (dumpPackage == null
7143 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007144 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146
7147 if (mPreviousProcess != null && (dumpPackage == null
7148 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007149 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007150 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7151 }
7152
7153 if (mHeavyWeightProcess != null && (dumpPackage == null
7154 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007155 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 }
7157
7158 for (Map.Entry<String, Integer> entry
7159 : mCompatModePackages.getPackages().entrySet()) {
7160 String pkg = entry.getKey();
7161 int mode = entry.getValue();
7162 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7163 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7164 proto.write(PACKAGE, pkg);
7165 proto.write(MODE, mode);
7166 proto.end(compatToken);
7167 }
7168 }
7169
7170 if (mCurAppTimeTracker != null) {
7171 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7172 }
7173
7174 }
7175 }
7176
7177 @Override
7178 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7179 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7180 boolean dumpFocusedStackOnly) {
7181 synchronized (mGlobalLock) {
7182 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7183 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7184 }
7185 }
7186
7187 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007188 public void dumpForOom(PrintWriter pw) {
7189 synchronized (mGlobalLock) {
7190 pw.println(" mHomeProcess: " + mHomeProcess);
7191 pw.println(" mPreviousProcess: " + mPreviousProcess);
7192 if (mHeavyWeightProcess != null) {
7193 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7194 }
7195 }
7196 }
7197
7198 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 public boolean canGcNow() {
7200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007201 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203 }
7204
Riddle Hsua0536432019-02-16 00:38:59 +08007205 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 @Override
7207 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007208 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007209 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 return top != null ? top.app : null;
7211 }
7212 }
7213
Riddle Hsua0536432019-02-16 00:38:59 +08007214 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 @Override
7216 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007217 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007218 if (mRootActivityContainer != null) {
7219 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 }
7221 }
7222 }
7223
7224 @Override
7225 public void scheduleDestroyAllActivities(String reason) {
7226 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007227 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 }
7229 }
7230
7231 @Override
7232 public void removeUser(int userId) {
7233 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007234 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007235 }
7236 }
7237
7238 @Override
7239 public boolean switchUser(int userId, UserState userState) {
7240 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007241 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007242 }
7243 }
7244
7245 @Override
7246 public void onHandleAppCrash(WindowProcessController wpc) {
7247 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007248 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007251
7252 @Override
7253 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7254 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007255 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007256 }
7257 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007258
Riddle Hsua0536432019-02-16 00:38:59 +08007259 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007260 @Override
7261 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007262 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007263 }
7264
Riddle Hsua0536432019-02-16 00:38:59 +08007265 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007266 @Override
7267 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007268 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007269 }
7270
Riddle Hsua0536432019-02-16 00:38:59 +08007271 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007272 @Override
7273 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007274 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007275 }
7276
Riddle Hsua0536432019-02-16 00:38:59 +08007277 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007278 @Override
7279 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007280 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007281 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007282
7283 @Override
7284 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007285 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007286 mPendingTempWhitelist.put(uid, tag);
7287 }
7288 }
7289
7290 @Override
7291 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007292 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007293 mPendingTempWhitelist.remove(uid);
7294 }
7295 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007296
7297 @Override
7298 public boolean handleAppCrashInActivityController(String processName, int pid,
7299 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7300 Runnable killCrashingAppCallback) {
7301 synchronized (mGlobalLock) {
7302 if (mController == null) {
7303 return false;
7304 }
7305
7306 try {
7307 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7308 stackTrace)) {
7309 killCrashingAppCallback.run();
7310 return true;
7311 }
7312 } catch (RemoteException e) {
7313 mController = null;
7314 Watchdog.getInstance().setActivityController(null);
7315 }
7316 return false;
7317 }
7318 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007319
7320 @Override
7321 public void removeRecentTasksByPackageName(String packageName, int userId) {
7322 synchronized (mGlobalLock) {
7323 mRecentTasks.removeTasksByPackageName(packageName, userId);
7324 }
7325 }
7326
7327 @Override
7328 public void cleanupRecentTasksForUser(int userId) {
7329 synchronized (mGlobalLock) {
7330 mRecentTasks.cleanupLocked(userId);
7331 }
7332 }
7333
7334 @Override
7335 public void loadRecentTasksForUser(int userId) {
7336 synchronized (mGlobalLock) {
7337 mRecentTasks.loadUserRecentsLocked(userId);
7338 }
7339 }
7340
7341 @Override
7342 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7343 synchronized (mGlobalLock) {
7344 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7345 }
7346 }
7347
7348 @Override
7349 public void flushRecentTasks() {
7350 mRecentTasks.flush();
7351 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007352
7353 @Override
7354 public WindowProcessController getHomeProcess() {
7355 synchronized (mGlobalLock) {
7356 return mHomeProcess;
7357 }
7358 }
7359
7360 @Override
7361 public WindowProcessController getPreviousProcess() {
7362 synchronized (mGlobalLock) {
7363 return mPreviousProcess;
7364 }
7365 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007366
7367 @Override
7368 public void clearLockedTasks(String reason) {
7369 synchronized (mGlobalLock) {
7370 getLockTaskController().clearLockedTasks(reason);
7371 }
7372 }
7373
7374 @Override
7375 public void updateUserConfiguration() {
7376 synchronized (mGlobalLock) {
7377 final Configuration configuration = new Configuration(getGlobalConfiguration());
7378 final int currentUserId = mAmInternal.getCurrentUserId();
7379 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7380 configuration, currentUserId, Settings.System.canWrite(mContext));
7381 updateConfigurationLocked(configuration, null /* starting */,
7382 false /* initLocale */, false /* persistent */, currentUserId,
7383 false /* deferResume */);
7384 }
7385 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007386
7387 @Override
7388 public boolean canShowErrorDialogs() {
7389 synchronized (mGlobalLock) {
7390 return mShowDialogs && !mSleeping && !mShuttingDown
7391 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7392 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7393 mAmInternal.getCurrentUserId())
7394 && !(UserManager.isDeviceInDemoMode(mContext)
7395 && mAmInternal.getCurrentUser().isDemo());
7396 }
7397 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007398
7399 @Override
7400 public void setProfileApp(String profileApp) {
7401 synchronized (mGlobalLock) {
7402 mProfileApp = profileApp;
7403 }
7404 }
7405
7406 @Override
7407 public void setProfileProc(WindowProcessController wpc) {
7408 synchronized (mGlobalLock) {
7409 mProfileProc = wpc;
7410 }
7411 }
7412
7413 @Override
7414 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7415 synchronized (mGlobalLock) {
7416 mProfilerInfo = profilerInfo;
7417 }
7418 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007419
7420 @Override
7421 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7422 synchronized (mGlobalLock) {
7423 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7424 }
7425 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007426
7427 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007428 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7429 boolean reducedResolution) {
7430 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7431 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007432 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007433
7434 @Override
7435 public boolean isUidForeground(int uid) {
7436 synchronized (mGlobalLock) {
7437 return ActivityTaskManagerService.this.isUidForeground(uid);
7438 }
7439 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007440
7441 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007442 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007443 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007444 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007445 }
7446 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007447
7448 @Override
7449 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007450 // Translate package names into UIDs
7451 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007452 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007453 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7454 if (uid >= 0) {
7455 result.add(uid);
7456 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007457 }
7458 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007459 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007460 }
7461 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007462 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007463}