blob: 03af38895e3da0c2f0f628fded24b9d9152cca31 [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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800266import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100313 // How long we permit background activity starts after an activity in the process
314 // started or finished.
315 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316
Wale Ogunwale98875612018-10-12 07:53:02 -0700317 /** Used to indicate that an app transition should be animated. */
318 static final boolean ANIMATE = true;
319
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700320 /** Hardware-reported OpenGLES version. */
321 final int GL_ES_VERSION;
322
Wale Ogunwale31913b52018-10-13 08:29:31 -0700323 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
324 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
325 public static final String DUMP_LASTANR_CMD = "lastanr" ;
326 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
327 public static final String DUMP_STARTER_CMD = "starter" ;
328 public static final String DUMP_CONTAINERS_CMD = "containers" ;
329 public static final String DUMP_RECENTS_CMD = "recents" ;
330 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
331
Wale Ogunwale64258362018-10-16 15:13:37 -0700332 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
333 public static final int RELAUNCH_REASON_NONE = 0;
334 /** This activity is being relaunched due to windowing mode change. */
335 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
336 /** This activity is being relaunched due to a free-resize operation. */
337 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
338
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700339 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700340
Wale Ogunwalef6733932018-06-27 05:14:34 -0700341 /**
342 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
343 * change at runtime. Use mContext for non-UI purposes.
344 */
345 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700347 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700350 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700351 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800352 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800353 @VisibleForTesting
354 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 PowerManagerInternal mPowerManagerInternal;
356 private UsageStatsManagerInternal mUsageStatsInternal;
357
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700358 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 IntentFirewall mIntentFirewall;
360
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700361 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800362 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800363 /**
364 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
365 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
366 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
367 *
368 * @see WindowManagerThreadPriorityBooster
369 */
370 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700371 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800372 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700373 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700374 private UserManagerService mUserManager;
375 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700376 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800377 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700378 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /** All processes currently running that might have a window organized by name. */
380 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100381 /** All processes we currently have running mapped by pid and uid */
382 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** This is the process holding what we currently consider to be the "home" activity. */
384 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700385 /** The currently running heavy-weight process, if any. */
386 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700387 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /**
389 * This is the process holding the activity the user last visited that is in a different process
390 * from the one they are currently in.
391 */
392 WindowProcessController mPreviousProcess;
393 /** The time at which the previous process was last visible. */
394 long mPreviousProcessVisibleTime;
395
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700396 /** List of intents that were used to start the most recent tasks. */
397 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700398 /** State of external calls telling us if the device is awake or asleep. */
399 private boolean mKeyguardShown = false;
400
401 // Wrapper around VoiceInteractionServiceManager
402 private AssistUtils mAssistUtils;
403
404 // VoiceInteraction session ID that changes for each new request except when
405 // being called for multi-window assist in a single session.
406 private int mViSessionId = 1000;
407
408 // How long to wait in getAssistContextExtras for the activity and foreground services
409 // to respond with the result.
410 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
411
412 // How long top wait when going through the modern assist (which doesn't need to block
413 // on getting this result before starting to launch its UI).
414 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
415
416 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
417 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
418
Alison Cichowlas3e340502018-08-07 17:15:01 -0400419 // Permission tokens are used to temporarily granted a trusted app the ability to call
420 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
421 // showing any appropriate error messages to the user.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
423 10 * MINUTE_IN_MILLIS;
424
425 // How long before the service actually expires a token. This is slightly longer than
426 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
427 // expiration exception.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
429 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
430
431 // How long the service will remember expired tokens, for the purpose of providing error
432 // messaging when a client uses an expired token.
433 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
434 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
435
436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700462 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
Ricky Wai906af482019-06-03 17:25:28 +0100507 /**
508 * Last stop app switches time, apps finished before this time cannot start background activity
509 * even if they are in grace period.
510 */
511 private long mLastStopAppSwitchesTime;
512
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 IActivityController mController = null;
514 boolean mControllerIsAMonkey = false;
515
Wale Ogunwale214f3482018-10-04 11:00:47 -0700516 final int mFactoryTest;
517
518 /** Used to control how we initialize the service. */
519 ComponentName mTopComponent;
520 String mTopAction = Intent.ACTION_MAIN;
521 String mTopData;
522
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800523 /** Profiling app information. */
524 String mProfileApp = null;
525 WindowProcessController mProfileProc = null;
526 ProfilerInfo mProfilerInfo = null;
527
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700528 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700529 * Dump of the activity state at the time of the last ANR. Cleared after
530 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
531 */
532 String mLastANRState;
533
534 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 * Used to retain an update lock when the foreground activity is in
536 * immersive mode.
537 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700538 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539
540 /**
541 * Packages that are being allowed to perform unrestricted app switches. Mapping is
542 * User -> Type -> uid.
543 */
544 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
545
546 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private int mThumbnailWidth;
548 private int mThumbnailHeight;
549 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700550
551 /**
552 * Flag that indicates if multi-window is enabled.
553 *
554 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
555 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
556 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
557 * At least one of the forms of multi-window must be enabled in order for this flag to be
558 * initialized to 'true'.
559 *
560 * @see #mSupportsSplitScreenMultiWindow
561 * @see #mSupportsFreeformWindowManagement
562 * @see #mSupportsPictureInPicture
563 * @see #mSupportsMultiDisplay
564 */
565 boolean mSupportsMultiWindow;
566 boolean mSupportsSplitScreenMultiWindow;
567 boolean mSupportsFreeformWindowManagement;
568 boolean mSupportsPictureInPicture;
569 boolean mSupportsMultiDisplay;
570 boolean mForceResizableActivities;
571
572 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
573
574 // VR Vr2d Display Id.
575 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700576
Wale Ogunwalef6733932018-06-27 05:14:34 -0700577 /**
578 * Set while we are wanting to sleep, to prevent any
579 * activities from being started/resumed.
580 *
581 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
582 *
583 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
584 * while in the sleep state until there is a pending transition out of sleep, in which case
585 * mSleeping is set to false, and remains false while awake.
586 *
587 * Whether mSleeping can quickly toggled between true/false without the device actually
588 * display changing states is undefined.
589 */
590 private boolean mSleeping = false;
591
592 /**
593 * The process state used for processes that are running the top activities.
594 * This changes between TOP and TOP_SLEEPING to following mSleeping.
595 */
596 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
597
598 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
599 // automatically. Important for devices without direct input devices.
600 private boolean mShowDialogs = true;
601
602 /** Set if we are shutting down the system, similar to sleeping. */
603 boolean mShuttingDown = false;
604
605 /**
606 * We want to hold a wake lock while running a voice interaction session, since
607 * this may happen with the screen off and we need to keep the CPU running to
608 * be able to continue to interact with the user.
609 */
610 PowerManager.WakeLock mVoiceWakeLock;
611
612 /**
613 * Set while we are running a voice interaction. This overrides sleeping while it is active.
614 */
615 IVoiceInteractionSession mRunningVoice;
616
617 /**
618 * The last resumed activity. This is identical to the current resumed activity most
619 * of the time but could be different when we're pausing one activity before we resume
620 * another activity.
621 */
622 ActivityRecord mLastResumedActivity;
623
624 /**
625 * The activity that is currently being traced as the active resumed activity.
626 *
627 * @see #updateResumedAppTrace
628 */
629 private @Nullable ActivityRecord mTracedResumedActivity;
630
631 /** If non-null, we are tracking the time the user spends in the currently focused app. */
632 AppTimeTracker mCurAppTimeTracker;
633
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700634 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700635
Wale Ogunwale53783742018-09-16 10:21:51 -0700636 /**
637 * Packages that the user has asked to have run in screen size
638 * compatibility mode instead of filling the screen.
639 */
640 CompatModePackages mCompatModePackages;
641
Wale Ogunwalef6733932018-06-27 05:14:34 -0700642 private FontScaleSettingObserver mFontScaleSettingObserver;
643
Ricky Wai96f5c352019-04-10 18:40:17 +0100644 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private final class FontScaleSettingObserver extends ContentObserver {
647 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
648 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
649
650 public FontScaleSettingObserver() {
651 super(mH);
652 final ContentResolver resolver = mContext.getContentResolver();
653 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
654 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
655 UserHandle.USER_ALL);
656 }
657
658 @Override
659 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
660 if (mFontScaleUri.equals(uri)) {
661 updateFontScaleIfNeeded(userId);
662 } else if (mHideErrorDialogsUri.equals(uri)) {
663 synchronized (mGlobalLock) {
664 updateShouldShowDialogsLocked(getGlobalConfiguration());
665 }
666 }
667 }
668 }
669
Riddle Hsua0536432019-02-16 00:38:59 +0800670 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
671 @Target(ElementType.METHOD)
672 @Retention(RetentionPolicy.SOURCE)
673 @interface HotPath {
674 int NONE = 0;
675 int OOM_ADJUSTMENT = 1;
676 int LRU_UPDATE = 2;
677 int PROCESS_CHANGE = 3;
678 int caller() default NONE;
679 }
680
Charles Chen8d98dd22018-12-26 17:36:54 +0800681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
682 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700683 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700684 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700685 mSystemThread = ActivityThread.currentActivityThread();
686 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700687 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800688 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700690 }
691
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 public void onSystemReady() {
693 synchronized (mGlobalLock) {
694 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
695 PackageManager.FEATURE_CANT_SAVE_STATE);
696 mAssistUtils = new AssistUtils(mContext);
697 mVrController.onSystemReady();
698 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700699 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700700 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700701 }
702
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700703 public void onInitPowerManagement() {
704 synchronized (mGlobalLock) {
705 mStackSupervisor.initPowerManagement();
706 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
707 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
708 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
709 mVoiceWakeLock.setReferenceCounted(false);
710 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700711 }
712
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700713 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700714 mFontScaleSettingObserver = new FontScaleSettingObserver();
715 }
716
Wale Ogunwale59507092018-10-29 09:00:30 -0700717 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean freeformWindowManagement =
719 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
720 || Settings.Global.getInt(
721 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
722
723 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
724 final boolean supportsPictureInPicture = supportsMultiWindow &&
725 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
726 final boolean supportsSplitScreenMultiWindow =
727 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
728 final boolean supportsMultiDisplay = mContext.getPackageManager()
729 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
731 final boolean forceResizable = Settings.Global.getInt(
732 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700733 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734
735 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900736 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737
738 final Configuration configuration = new Configuration();
739 Settings.System.getConfiguration(resolver, configuration);
740 if (forceRtl) {
741 // This will take care of setting the correct layout direction flags
742 configuration.setLayoutDirection(configuration.locale);
743 }
744
745 synchronized (mGlobalLock) {
746 mForceResizableActivities = forceResizable;
747 final boolean multiWindowFormEnabled = freeformWindowManagement
748 || supportsSplitScreenMultiWindow
749 || supportsPictureInPicture
750 || supportsMultiDisplay;
751 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
752 mSupportsMultiWindow = true;
753 mSupportsFreeformWindowManagement = freeformWindowManagement;
754 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
755 mSupportsPictureInPicture = supportsPictureInPicture;
756 mSupportsMultiDisplay = supportsMultiDisplay;
757 } else {
758 mSupportsMultiWindow = false;
759 mSupportsFreeformWindowManagement = false;
760 mSupportsSplitScreenMultiWindow = false;
761 mSupportsPictureInPicture = false;
762 mSupportsMultiDisplay = false;
763 }
764 mWindowManager.setForceResizableTasks(mForceResizableActivities);
765 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700766 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
767 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700768 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769 // This happens before any activities are started, so we can change global configuration
770 // in-place.
771 updateConfigurationLocked(configuration, null, true);
772 final Configuration globalConfig = getGlobalConfiguration();
773 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
774
775 // Load resources only after the current configuration has been set.
776 final Resources res = mContext.getResources();
777 mThumbnailWidth = res.getDimensionPixelSize(
778 com.android.internal.R.dimen.thumbnail_width);
779 mThumbnailHeight = res.getDimensionPixelSize(
780 com.android.internal.R.dimen.thumbnail_height);
781
782 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
783 mFullscreenThumbnailScale = (float) res
784 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
785 (float) globalConfig.screenWidthDp;
786 } else {
787 mFullscreenThumbnailScale = res.getFraction(
788 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
789 }
790 }
791 }
792
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800793 public WindowManagerGlobalLock getGlobalLock() {
794 return mGlobalLock;
795 }
796
Yunfan Chen585f2932019-01-29 16:04:45 +0900797 /** For test purpose only. */
798 @VisibleForTesting
799 public ActivityTaskManagerInternal getAtmInternal() {
800 return mInternal;
801 }
802
Riddle Hsud93a6c42018-11-29 21:50:06 +0800803 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
804 Looper looper) {
805 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700808 final File systemDir = SystemServiceManager.ensureSystemDir();
809 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
810 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
813 mTempConfig.setToDefaults();
814 mTempConfig.setLocales(LocaleList.getDefault());
815 mConfigurationSeq = mTempConfig.seq = 1;
816 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800817 mRootActivityContainer = new RootActivityContainer(this);
818 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700822 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700824 mRecentTasks = createRecentTasks();
825 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mKeyguardController = mStackSupervisor.getKeyguardController();
828 }
829
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 public void onActivityManagerInternalAdded() {
831 synchronized (mGlobalLock) {
832 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
833 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
834 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700835 }
836
Yunfan Chen75157d72018-07-27 14:47:21 +0900837 int increaseConfigurationSeqLocked() {
838 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
839 return mConfigurationSeq;
840 }
841
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700842 protected ActivityStackSupervisor createStackSupervisor() {
843 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
844 supervisor.initialize();
845 return supervisor;
846 }
847
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 public void setWindowManager(WindowManagerService wm) {
849 synchronized (mGlobalLock) {
850 mWindowManager = wm;
851 mLockTaskController.setWindowManager(wm);
852 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800853 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700854 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700855 }
856
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700857 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
858 synchronized (mGlobalLock) {
859 mUsageStatsInternal = usageStatsManager;
860 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700861 }
862
Wale Ogunwalef6733932018-06-27 05:14:34 -0700863 UserManagerService getUserManager() {
864 if (mUserManager == null) {
865 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
866 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
867 }
868 return mUserManager;
869 }
870
871 AppOpsService getAppOpsService() {
872 if (mAppOpsService == null) {
873 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
874 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
875 }
876 return mAppOpsService;
877 }
878
879 boolean hasUserRestriction(String restriction, int userId) {
880 return getUserManager().hasUserRestriction(restriction, userId);
881 }
882
Michal Karpinski15486842019-04-25 17:33:42 +0100883 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
884 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
885 callingUid, callingPackage);
886 if (mode == AppOpsManager.MODE_DEFAULT) {
887 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
888 == PERMISSION_GRANTED;
889 }
890 return mode == AppOpsManager.MODE_ALLOWED;
891 }
892
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700893 protected RecentTasks createRecentTasks() {
894 return new RecentTasks(this, mStackSupervisor);
895 }
896
897 RecentTasks getRecentTasks() {
898 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700899 }
900
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700901 ClientLifecycleManager getLifecycleManager() {
902 return mLifecycleManager;
903 }
904
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700905 ActivityStartController getActivityStartController() {
906 return mActivityStartController;
907 }
908
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700909 TaskChangeNotificationController getTaskChangeNotificationController() {
910 return mTaskChangeNotificationController;
911 }
912
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700913 LockTaskController getLockTaskController() {
914 return mLockTaskController;
915 }
916
Yunfan Chen75157d72018-07-27 14:47:21 +0900917 /**
918 * Return the global configuration used by the process corresponding to the input pid. This is
919 * usually the global configuration with some overrides specific to that process.
920 */
921 Configuration getGlobalConfigurationForCallingPid() {
922 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800923 return getGlobalConfigurationForPid(pid);
924 }
925
926 /**
927 * Return the global configuration used by the process corresponding to the given pid.
928 */
929 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 if (pid == MY_PID || pid < 0) {
931 return getGlobalConfiguration();
932 }
933 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100934 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900935 return app != null ? app.getConfiguration() : getGlobalConfiguration();
936 }
937 }
938
939 /**
940 * Return the device configuration info used by the process corresponding to the input pid.
941 * The value is consistent with the global configuration for the process.
942 */
943 @Override
944 public ConfigurationInfo getDeviceConfigurationInfo() {
945 ConfigurationInfo config = new ConfigurationInfo();
946 synchronized (mGlobalLock) {
947 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
948 config.reqTouchScreen = globalConfig.touchscreen;
949 config.reqKeyboardType = globalConfig.keyboard;
950 config.reqNavigation = globalConfig.navigation;
951 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
952 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
954 }
955 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
956 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
958 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700959 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 }
961 return config;
962 }
963
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700965 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700966 }
967
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700968 public static final class Lifecycle extends SystemService {
969 private final ActivityTaskManagerService mService;
970
971 public Lifecycle(Context context) {
972 super(context);
973 mService = new ActivityTaskManagerService(context);
974 }
975
976 @Override
977 public void onStart() {
978 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700979 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 }
981
Garfield Tan891146c2018-10-09 12:14:00 -0700982 @Override
983 public void onUnlockUser(int userId) {
984 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800985 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700986 }
987 }
988
989 @Override
990 public void onCleanupUser(int userId) {
991 synchronized (mService.getGlobalLock()) {
992 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
993 }
994 }
995
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700996 public ActivityTaskManagerService getService() {
997 return mService;
998 }
999 }
1000
1001 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001002 public final int startActivity(IApplicationThread caller, String callingPackage,
1003 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1004 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1005 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1006 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1007 UserHandle.getCallingUserId());
1008 }
1009
1010 @Override
1011 public final int startActivities(IApplicationThread caller, String callingPackage,
1012 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1013 int userId) {
1014 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 enforceNotIsolatedCaller(reason);
1016 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001018 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1019 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1020 reason, null /* originatingPendingIntent */,
1021 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 }
1023
1024 @Override
1025 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1026 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1027 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1028 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1029 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1030 true /*validateIncomingUser*/);
1031 }
1032
1033 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1034 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1035 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1036 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1041
1042 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001043 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 .setCaller(caller)
1045 .setCallingPackage(callingPackage)
1046 .setResolvedType(resolvedType)
1047 .setResultTo(resultTo)
1048 .setResultWho(resultWho)
1049 .setRequestCode(requestCode)
1050 .setStartFlags(startFlags)
1051 .setProfilerInfo(profilerInfo)
1052 .setActivityOptions(bOptions)
1053 .setMayWait(userId)
1054 .execute();
1055
1056 }
1057
1058 @Override
1059 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1060 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001061 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1062 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 // Refuse possible leaked file descriptors
1064 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1065 throw new IllegalArgumentException("File descriptors passed in Intent");
1066 }
1067
1068 if (!(target instanceof PendingIntentRecord)) {
1069 throw new IllegalArgumentException("Bad PendingIntent object");
1070 }
1071
1072 PendingIntentRecord pir = (PendingIntentRecord)target;
1073
1074 synchronized (mGlobalLock) {
1075 // If this is coming from the currently resumed activity, it is
1076 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001077 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 if (stack.mResumedActivity != null &&
1079 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001080 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 }
1086
1087 @Override
1088 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1089 Bundle bOptions) {
1090 // Refuse possible leaked file descriptors
1091 if (intent != null && intent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1095
1096 synchronized (mGlobalLock) {
1097 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1098 if (r == null) {
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001102 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 // The caller is not running... d'oh!
1104 SafeActivityOptions.abort(options);
1105 return false;
1106 }
1107 intent = new Intent(intent);
1108 // The caller is not allowed to change the data.
1109 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1110 // And we are resetting to find the next component...
1111 intent.setComponent(null);
1112
1113 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1114
1115 ActivityInfo aInfo = null;
1116 try {
1117 List<ResolveInfo> resolves =
1118 AppGlobals.getPackageManager().queryIntentActivities(
1119 intent, r.resolvedType,
1120 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1121 UserHandle.getCallingUserId()).getList();
1122
1123 // Look for the original activity in the list...
1124 final int N = resolves != null ? resolves.size() : 0;
1125 for (int i=0; i<N; i++) {
1126 ResolveInfo rInfo = resolves.get(i);
1127 if (rInfo.activityInfo.packageName.equals(r.packageName)
1128 && rInfo.activityInfo.name.equals(r.info.name)) {
1129 // We found the current one... the next matching is
1130 // after it.
1131 i++;
1132 if (i<N) {
1133 aInfo = resolves.get(i).activityInfo;
1134 }
1135 if (debug) {
1136 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1137 + "/" + r.info.name);
1138 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1139 ? "null" : aInfo.packageName + "/" + aInfo.name));
1140 }
1141 break;
1142 }
1143 }
1144 } catch (RemoteException e) {
1145 }
1146
1147 if (aInfo == null) {
1148 // Nobody who is next!
1149 SafeActivityOptions.abort(options);
1150 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1151 return false;
1152 }
1153
1154 intent.setComponent(new ComponentName(
1155 aInfo.applicationInfo.packageName, aInfo.name));
1156 intent.setFlags(intent.getFlags()&~(
1157 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1158 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1159 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1160 FLAG_ACTIVITY_NEW_TASK));
1161
1162 // Okay now we need to start the new activity, replacing the currently running activity.
1163 // This is a little tricky because we want to start the new one as if the current one is
1164 // finished, but not finish the current one first so that there is no flicker.
1165 // And thus...
1166 final boolean wasFinishing = r.finishing;
1167 r.finishing = true;
1168
1169 // Propagate reply information over to the new activity.
1170 final ActivityRecord resultTo = r.resultTo;
1171 final String resultWho = r.resultWho;
1172 final int requestCode = r.requestCode;
1173 r.resultTo = null;
1174 if (resultTo != null) {
1175 resultTo.removeResultsLocked(r, resultWho, requestCode);
1176 }
1177
1178 final long origId = Binder.clearCallingIdentity();
1179 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001180 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001182 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 .setResolvedType(r.resolvedType)
1184 .setActivityInfo(aInfo)
1185 .setResultTo(resultTo != null ? resultTo.appToken : null)
1186 .setResultWho(resultWho)
1187 .setRequestCode(requestCode)
1188 .setCallingPid(-1)
1189 .setCallingUid(r.launchedFromUid)
1190 .setCallingPackage(r.launchedFromPackage)
1191 .setRealCallingPid(-1)
1192 .setRealCallingUid(r.launchedFromUid)
1193 .setActivityOptions(options)
1194 .execute();
1195 Binder.restoreCallingIdentity(origId);
1196
1197 r.finishing = wasFinishing;
1198 if (res != ActivityManager.START_SUCCESS) {
1199 return false;
1200 }
1201 return true;
1202 }
1203 }
1204
1205 @Override
1206 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1207 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1208 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1209 final WaitResult res = new WaitResult();
1210 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001211 enforceNotIsolatedCaller("startActivityAndWait");
1212 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1213 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001215 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 .setCaller(caller)
1217 .setCallingPackage(callingPackage)
1218 .setResolvedType(resolvedType)
1219 .setResultTo(resultTo)
1220 .setResultWho(resultWho)
1221 .setRequestCode(requestCode)
1222 .setStartFlags(startFlags)
1223 .setActivityOptions(bOptions)
1224 .setMayWait(userId)
1225 .setProfilerInfo(profilerInfo)
1226 .setWaitResult(res)
1227 .execute();
1228 }
1229 return res;
1230 }
1231
1232 @Override
1233 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, Configuration config, Bundle bOptions, int userId) {
1236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001237 enforceNotIsolatedCaller("startActivityWithConfig");
1238 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1239 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001240 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001241 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001242 .setCaller(caller)
1243 .setCallingPackage(callingPackage)
1244 .setResolvedType(resolvedType)
1245 .setResultTo(resultTo)
1246 .setResultWho(resultWho)
1247 .setRequestCode(requestCode)
1248 .setStartFlags(startFlags)
1249 .setGlobalConfiguration(config)
1250 .setActivityOptions(bOptions)
1251 .setMayWait(userId)
1252 .execute();
1253 }
1254 }
1255
Alison Cichowlas3e340502018-08-07 17:15:01 -04001256
1257 @Override
1258 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1259 int callingUid = Binder.getCallingUid();
1260 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1261 throw new SecurityException("Only the system process can request a permission token, "
1262 + "received request from uid: " + callingUid);
1263 }
1264 IBinder permissionToken = new Binder();
1265 synchronized (mGlobalLock) {
1266 mStartActivitySources.put(permissionToken, delegatorToken);
1267 }
1268
1269 Message expireMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1272
1273 Message forgetMsg = PooledLambda.obtainMessage(
1274 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1275 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1276
1277 return permissionToken;
1278 }
1279
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 @Override
1281 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1282 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1284 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 // permission grants) as any app that may launch one of your own activities. So we only
1287 // allow this in two cases:
1288 // 1) The caller is an activity that is part of the core framework, and then only when it
1289 // is running as the system.
1290 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1291 // can only be requested by a system activity, which may then delegate this call to
1292 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 final ActivityRecord sourceRecord;
1294 final int targetUid;
1295 final String targetPackage;
1296 final boolean isResolver;
1297 synchronized (mGlobalLock) {
1298 if (resultTo == null) {
1299 throw new SecurityException("Must be called from an activity");
1300 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 final IBinder sourceToken;
1302 if (permissionToken != null) {
1303 // To even attempt to use a permissionToken, an app must also have this signature
1304 // permission.
1305 mAmInternal.enforceCallingPermission(
1306 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1307 "startActivityAsCaller");
1308 // If called with a permissionToken, we want the sourceRecord from the delegator
1309 // activity that requested this token.
1310 sourceToken = mStartActivitySources.remove(permissionToken);
1311 if (sourceToken == null) {
1312 // Invalid permissionToken, check if it recently expired.
1313 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1314 throw new SecurityException("Called with expired permission token: "
1315 + permissionToken);
1316 } else {
1317 throw new SecurityException("Called with invalid permission token: "
1318 + permissionToken);
1319 }
1320 }
1321 } else {
1322 // This method was called directly by the source.
1323 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325
Wale Ogunwaled32da472018-11-16 07:19:28 -08001326 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327 if (sourceRecord == null) {
1328 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 }
1330 if (sourceRecord.app == null) {
1331 throw new SecurityException("Called without a process attached to activity");
1332 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333
1334 // Whether called directly or from a delegate, the source activity must be from the
1335 // android package.
1336 if (!sourceRecord.info.packageName.equals("android")) {
1337 throw new SecurityException("Must be called from an activity that is "
1338 + "declared in the android package");
1339 }
1340
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 // This is still okay, as long as this activity is running under the
1343 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 + " must be system uid or original calling uid "
1348 + sourceRecord.launchedFromUid);
1349 }
1350 }
1351 if (ignoreTargetSecurity) {
1352 if (intent.getComponent() == null) {
1353 throw new SecurityException(
1354 "Component must be specified with ignoreTargetSecurity");
1355 }
1356 if (intent.getSelector() != null) {
1357 throw new SecurityException(
1358 "Selector not allowed with ignoreTargetSecurity");
1359 }
1360 }
1361 targetUid = sourceRecord.launchedFromUid;
1362 targetPackage = sourceRecord.launchedFromPackage;
1363 isResolver = sourceRecord.isResolverOrChildActivity();
1364 }
1365
1366 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001367 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 }
1369
1370 // TODO: Switch to user app stacks here.
1371 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001372 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 .setCallingUid(targetUid)
1374 .setCallingPackage(targetPackage)
1375 .setResolvedType(resolvedType)
1376 .setResultTo(resultTo)
1377 .setResultWho(resultWho)
1378 .setRequestCode(requestCode)
1379 .setStartFlags(startFlags)
1380 .setActivityOptions(bOptions)
1381 .setMayWait(userId)
1382 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1383 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001384 // The target may well be in the background, which would normally prevent it
1385 // from starting an activity. Here we definitely want the start to succeed.
1386 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .execute();
1388 } catch (SecurityException e) {
1389 // XXX need to figure out how to propagate to original app.
1390 // A SecurityException here is generally actually a fault of the original
1391 // calling activity (such as a fairly granting permissions), so propagate it
1392 // back to them.
1393 /*
1394 StringBuilder msg = new StringBuilder();
1395 msg.append("While launching");
1396 msg.append(intent.toString());
1397 msg.append(": ");
1398 msg.append(e.getMessage());
1399 */
1400 throw e;
1401 }
1402 }
1403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1405 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1406 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1407 }
1408
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 @Override
1410 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1411 Intent intent, String resolvedType, IVoiceInteractionSession session,
1412 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1413 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 if (session == null || interactor == null) {
1416 throw new NullPointerException("null session or interactor");
1417 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001420 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 .setCallingUid(callingUid)
1422 .setCallingPackage(callingPackage)
1423 .setResolvedType(resolvedType)
1424 .setVoiceSession(session)
1425 .setVoiceInteractor(interactor)
1426 .setStartFlags(startFlags)
1427 .setProfilerInfo(profilerInfo)
1428 .setActivityOptions(bOptions)
1429 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001430 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 .execute();
1432 }
1433
1434 @Override
1435 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1436 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1438 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001440 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 .setCallingUid(callingUid)
1442 .setCallingPackage(callingPackage)
1443 .setResolvedType(resolvedType)
1444 .setActivityOptions(bOptions)
1445 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001446 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .execute();
1448 }
1449
Riddle Hsu609a8e22019-06-27 16:46:29 -06001450 /**
1451 * Start the recents activity to perform the recents animation.
1452 *
1453 * @param intent The intent to start the recents activity.
1454 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1455 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001457 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1458 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001459 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 final int callingPid = Binder.getCallingPid();
1461 final long origId = Binder.clearCallingIdentity();
1462 try {
1463 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001464 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1465 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466
1467 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001468 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 getActivityStartController(), mWindowManager, intent, recentsComponent,
1470 recentsUid, callingPid);
1471 if (recentsAnimationRunner == null) {
1472 anim.preloadRecentsActivity();
1473 } else {
1474 anim.startRecentsActivity(recentsAnimationRunner);
1475 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 }
1477 } finally {
1478 Binder.restoreCallingIdentity(origId);
1479 }
1480 }
1481
1482 @Override
1483 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001484 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485 "startActivityFromRecents()");
1486
1487 final int callingPid = Binder.getCallingPid();
1488 final int callingUid = Binder.getCallingUid();
1489 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1490 final long origId = Binder.clearCallingIdentity();
1491 try {
1492 synchronized (mGlobalLock) {
1493 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1494 safeOptions);
1495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001502 * Public API to check if the client is allowed to start an activity on specified display.
1503 *
1504 * If the target display is private or virtual, some restrictions will apply.
1505 *
1506 * @param displayId Target display id.
1507 * @param intent Intent used to launch the activity.
1508 * @param resolvedType The MIME type of the intent.
1509 * @param userId The id of the user for whom the call is made.
1510 * @return {@code true} if a call to start an activity on the target display should succeed and
1511 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1512 */
1513 @Override
1514 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1515 String resolvedType, int userId) {
1516 final int callingUid = Binder.getCallingUid();
1517 final int callingPid = Binder.getCallingPid();
1518 final long origId = Binder.clearCallingIdentity();
1519
1520 try {
1521 // Collect information about the target of the Intent.
1522 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1523 0 /* startFlags */, null /* profilerInfo */, userId,
1524 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1525 UserHandle.USER_NULL));
1526 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1527
1528 synchronized (mGlobalLock) {
1529 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1530 aInfo);
1531 }
1532 } finally {
1533 Binder.restoreCallingIdentity(origId);
1534 }
1535 }
1536
1537 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 * This is the internal entry point for handling Activity.finish().
1539 *
1540 * @param token The Binder token referencing the Activity we want to finish.
1541 * @param resultCode Result code, if any, from this Activity.
1542 * @param resultData Result data (Intent), if any, from this Activity.
1543 * @param finishTask Whether to finish the task associated with this Activity.
1544 *
1545 * @return Returns true if the activity successfully finished, or false if it is still running.
1546 */
1547 @Override
1548 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1549 int finishTask) {
1550 // Refuse possible leaked file descriptors
1551 if (resultData != null && resultData.hasFileDescriptors()) {
1552 throw new IllegalArgumentException("File descriptors passed in Intent");
1553 }
1554
1555 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001556 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 if (r == null) {
1558 return true;
1559 }
1560 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001561 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 ActivityRecord rootR = tr.getRootActivity();
1563 if (rootR == null) {
1564 Slog.w(TAG, "Finishing task with all activities already finished");
1565 }
1566 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1567 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001568 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 return false;
1570 }
1571
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001572 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1573 // We should consolidate.
1574 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001576 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (next != null) {
1578 // ask watcher if this is allowed
1579 boolean resumeOK = true;
1580 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001581 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 Watchdog.getInstance().setActivityController(null);
1585 }
1586
1587 if (!resumeOK) {
1588 Slog.i(TAG, "Not finishing activity because controller resumed");
1589 return false;
1590 }
1591 }
1592 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001593
1594 // note down that the process has finished an activity and is in background activity
1595 // starts grace period
1596 if (r.app != null) {
1597 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1598 }
1599
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 final long origId = Binder.clearCallingIdentity();
1601 try {
1602 boolean res;
1603 final boolean finishWithRootActivity =
1604 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1605 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1606 || (finishWithRootActivity && r == rootR)) {
1607 // If requested, remove the task that is associated to this activity only if it
1608 // was the root activity in the task. The result code and data is ignored
1609 // because we don't support returning them across task boundaries. Also, to
1610 // keep backwards compatibility we remove the task from recents when finishing
1611 // task with root activity.
1612 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1613 finishWithRootActivity, "finish-activity");
1614 if (!res) {
1615 Slog.i(TAG, "Removing task failed to finish activity");
1616 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001617 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001618 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 } else {
1620 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001621 resultData, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 if (!res) {
1623 Slog.i(TAG, "Failed to finish by app-request");
1624 }
1625 }
1626 return res;
1627 } finally {
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630 }
1631 }
1632
1633 @Override
1634 public boolean finishActivityAffinity(IBinder token) {
1635 synchronized (mGlobalLock) {
1636 final long origId = Binder.clearCallingIdentity();
1637 try {
1638 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1639 if (r == null) {
1640 return false;
1641 }
1642
1643 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1644 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001645 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001646 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 return false;
1648 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001649 r.finishActivityAffinity();
1650 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 } finally {
1652 Binder.restoreCallingIdentity(origId);
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1659 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001660 try {
1661 WindowProcessController proc = null;
1662 synchronized (mGlobalLock) {
1663 ActivityStack stack = ActivityRecord.getStackLocked(token);
1664 if (stack == null) {
1665 return;
1666 }
1667 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1668 false /* fromTimeout */, false /* processPausingActivities */, config);
1669 if (r != null) {
1670 proc = r.app;
1671 }
1672 if (stopProfiling && proc != null) {
1673 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
1675 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001676 } finally {
1677 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 }
1680
1681 @Override
1682 public final void activityResumed(IBinder token) {
1683 final long origId = Binder.clearCallingIdentity();
1684 synchronized (mGlobalLock) {
1685 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001686 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 }
1688 Binder.restoreCallingIdentity(origId);
1689 }
1690
1691 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001692 public final void activityTopResumedStateLost() {
1693 final long origId = Binder.clearCallingIdentity();
1694 synchronized (mGlobalLock) {
1695 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1696 }
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699
1700 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 public final void activityPaused(IBinder token) {
1702 final long origId = Binder.clearCallingIdentity();
1703 synchronized (mGlobalLock) {
1704 ActivityStack stack = ActivityRecord.getStackLocked(token);
1705 if (stack != null) {
1706 stack.activityPausedLocked(token, false);
1707 }
1708 }
1709 Binder.restoreCallingIdentity(origId);
1710 }
1711
1712 @Override
1713 public final void activityStopped(IBinder token, Bundle icicle,
1714 PersistableBundle persistentState, CharSequence description) {
1715 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1716
1717 // Refuse possible leaked file descriptors
1718 if (icicle != null && icicle.hasFileDescriptors()) {
1719 throw new IllegalArgumentException("File descriptors passed in Bundle");
1720 }
1721
1722 final long origId = Binder.clearCallingIdentity();
1723
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001724 String restartingName = null;
1725 int restartingUid = 0;
1726 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001728 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 if (r.attachedToProcess()
1731 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1732 // The activity was requested to restart from
1733 // {@link #restartActivityProcessIfVisible}.
1734 restartingName = r.app.mName;
1735 restartingUid = r.app.mUid;
1736 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 r.activityStoppedLocked(icicle, persistentState, description);
1738 }
1739 }
1740
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001741 if (restartingName != null) {
1742 // In order to let the foreground activity can be restarted with its saved state from
1743 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1744 // until the activity reports stopped with the state. And the activity record will be
1745 // kept because the record state is restarting, then the activity will be restarted
1746 // immediately if it is still the top one.
1747 mStackSupervisor.removeRestartTimeouts(r);
1748 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1749 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001750 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751
1752 Binder.restoreCallingIdentity(origId);
1753 }
1754
1755 @Override
1756 public final void activityDestroyed(IBinder token) {
1757 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1758 synchronized (mGlobalLock) {
1759 ActivityStack stack = ActivityRecord.getStackLocked(token);
1760 if (stack != null) {
1761 stack.activityDestroyedLocked(token, "activityDestroyed");
1762 }
1763 }
1764 }
1765
1766 @Override
1767 public final void activityRelaunched(IBinder token) {
1768 final long origId = Binder.clearCallingIdentity();
1769 synchronized (mGlobalLock) {
1770 mStackSupervisor.activityRelaunchedLocked(token);
1771 }
1772 Binder.restoreCallingIdentity(origId);
1773 }
1774
1775 public final void activitySlept(IBinder token) {
1776 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1777
1778 final long origId = Binder.clearCallingIdentity();
1779
1780 synchronized (mGlobalLock) {
1781 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1782 if (r != null) {
1783 mStackSupervisor.activitySleptLocked(r);
1784 }
1785 }
1786
1787 Binder.restoreCallingIdentity(origId);
1788 }
1789
1790 @Override
1791 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1792 synchronized (mGlobalLock) {
1793 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1794 if (r == null) {
1795 return;
1796 }
1797 final long origId = Binder.clearCallingIdentity();
1798 try {
1799 r.setRequestedOrientation(requestedOrientation);
1800 } finally {
1801 Binder.restoreCallingIdentity(origId);
1802 }
1803 }
1804 }
1805
1806 @Override
1807 public int getRequestedOrientation(IBinder token) {
1808 synchronized (mGlobalLock) {
1809 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1810 if (r == null) {
1811 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1812 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001813 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 }
1815 }
1816
1817 @Override
1818 public void setImmersive(IBinder token, boolean immersive) {
1819 synchronized (mGlobalLock) {
1820 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r == null) {
1822 throw new IllegalArgumentException();
1823 }
1824 r.immersive = immersive;
1825
1826 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001827 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001829 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 }
1831 }
1832 }
1833
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001834 void applyUpdateLockStateLocked(ActivityRecord r) {
1835 // Modifications to the UpdateLock state are done on our handler, outside
1836 // the activity manager's locks. The new state is determined based on the
1837 // state *now* of the relevant activity record. The object is passed to
1838 // the handler solely for logging detail, not to be consulted/modified.
1839 final boolean nextState = r != null && r.immersive;
1840 mH.post(() -> {
1841 if (mUpdateLock.isHeld() != nextState) {
1842 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1843 "Applying new update lock state '" + nextState + "' for " + r);
1844 if (nextState) {
1845 mUpdateLock.acquire();
1846 } else {
1847 mUpdateLock.release();
1848 }
1849 }
1850 });
1851 }
1852
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 @Override
1854 public boolean isImmersive(IBinder token) {
1855 synchronized (mGlobalLock) {
1856 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1857 if (r == null) {
1858 throw new IllegalArgumentException();
1859 }
1860 return r.immersive;
1861 }
1862 }
1863
1864 @Override
1865 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001866 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001868 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 return (r != null) ? r.immersive : false;
1870 }
1871 }
1872
1873 @Override
1874 public void overridePendingTransition(IBinder token, String packageName,
1875 int enterAnim, int exitAnim) {
1876 synchronized (mGlobalLock) {
1877 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1878 if (self == null) {
1879 return;
1880 }
1881
1882 final long origId = Binder.clearCallingIdentity();
1883
1884 if (self.isState(
1885 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001886 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001887 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 }
1889
1890 Binder.restoreCallingIdentity(origId);
1891 }
1892 }
1893
1894 @Override
1895 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001896 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001898 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001899 if (r == null) {
1900 return ActivityManager.COMPAT_MODE_UNKNOWN;
1901 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001902 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
1904 }
1905
1906 @Override
1907 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001908 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001912 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001913 if (r == null) {
1914 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1915 return;
1916 }
1917 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001918 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 }
1920 }
1921
1922 @Override
1923 public int getLaunchedFromUid(IBinder activityToken) {
1924 ActivityRecord srec;
1925 synchronized (mGlobalLock) {
1926 srec = ActivityRecord.forTokenLocked(activityToken);
1927 }
1928 if (srec == null) {
1929 return -1;
1930 }
1931 return srec.launchedFromUid;
1932 }
1933
1934 @Override
1935 public String getLaunchedFromPackage(IBinder activityToken) {
1936 ActivityRecord srec;
1937 synchronized (mGlobalLock) {
1938 srec = ActivityRecord.forTokenLocked(activityToken);
1939 }
1940 if (srec == null) {
1941 return null;
1942 }
1943 return srec.launchedFromPackage;
1944 }
1945
1946 @Override
1947 public boolean convertFromTranslucent(IBinder token) {
1948 final long origId = Binder.clearCallingIdentity();
1949 try {
1950 synchronized (mGlobalLock) {
1951 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1952 if (r == null) {
1953 return false;
1954 }
1955 final boolean translucentChanged = r.changeWindowTranslucency(true);
1956 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001957 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001959 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 return translucentChanged;
1961 }
1962 } finally {
1963 Binder.restoreCallingIdentity(origId);
1964 }
1965 }
1966
1967 @Override
1968 public boolean convertToTranslucent(IBinder token, Bundle options) {
1969 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1970 final long origId = Binder.clearCallingIdentity();
1971 try {
1972 synchronized (mGlobalLock) {
1973 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1974 if (r == null) {
1975 return false;
1976 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001977 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 int index = task.mActivities.lastIndexOf(r);
1979 if (index > 0) {
1980 ActivityRecord under = task.mActivities.get(index - 1);
1981 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1982 }
1983 final boolean translucentChanged = r.changeWindowTranslucency(false);
1984 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001985 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001987 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001988 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 return translucentChanged;
1990 }
1991 } finally {
1992 Binder.restoreCallingIdentity(origId);
1993 }
1994 }
1995
1996 @Override
1997 public void notifyActivityDrawn(IBinder token) {
1998 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1999 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002000 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002002 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 }
2005 }
2006
2007 @Override
2008 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2009 synchronized (mGlobalLock) {
2010 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2011 if (r == null) {
2012 return;
2013 }
2014 r.reportFullyDrawnLocked(restoredFromBundle);
2015 }
2016 }
2017
2018 @Override
2019 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2020 synchronized (mGlobalLock) {
2021 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2022 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2023 return stack.mDisplayId;
2024 }
2025 return DEFAULT_DISPLAY;
2026 }
2027 }
2028
2029 @Override
2030 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002031 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 long ident = Binder.clearCallingIdentity();
2033 try {
2034 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002035 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002036 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002037 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 return null;
2040 }
2041 } finally {
2042 Binder.restoreCallingIdentity(ident);
2043 }
2044 }
2045
2046 @Override
2047 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002048 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2050 final long callingId = Binder.clearCallingIdentity();
2051 try {
2052 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 if (stack == null) {
2055 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2056 return;
2057 }
2058 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002059 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002060 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 }
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(callingId);
2065 }
2066 }
2067
2068 @Override
2069 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2072 final long callingId = Binder.clearCallingIdentity();
2073 try {
2074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002076 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 if (task == null) {
2078 return;
2079 }
2080 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002081 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002082 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 }
2084 }
2085 } finally {
2086 Binder.restoreCallingIdentity(callingId);
2087 }
2088 }
2089
2090 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002091 public void restartActivityProcessIfVisible(IBinder activityToken) {
2092 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2093 final long callingId = Binder.clearCallingIdentity();
2094 try {
2095 synchronized (mGlobalLock) {
2096 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2097 if (r == null) {
2098 return;
2099 }
2100 r.restartProcessIfVisible();
2101 }
2102 } finally {
2103 Binder.restoreCallingIdentity(callingId);
2104 }
2105 }
2106
2107 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 synchronized (mGlobalLock) {
2111 final long ident = Binder.clearCallingIdentity();
2112 try {
2113 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2114 "remove-task");
2115 } finally {
2116 Binder.restoreCallingIdentity(ident);
2117 }
2118 }
2119 }
2120
2121 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002122 public void removeAllVisibleRecentTasks() {
2123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002127 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002128 } finally {
2129 Binder.restoreCallingIdentity(ident);
2130 }
2131 }
2132 }
2133
2134 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2136 synchronized (mGlobalLock) {
2137 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2138 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002139 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 }
2141 }
2142 return false;
2143 }
2144
2145 @Override
2146 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2147 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002148
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002149 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002150 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2151 if (r != null) {
2152 return r.getActivityStack().navigateUpToLocked(
2153 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002154 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002155 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 }
2157 }
2158
2159 /**
2160 * Attempts to move a task backwards in z-order (the order of activities within the task is
2161 * unchanged).
2162 *
2163 * There are several possible results of this call:
2164 * - if the task is locked, then we will show the lock toast
2165 * - if there is a task behind the provided task, then that task is made visible and resumed as
2166 * this task is moved to the back
2167 * - otherwise, if there are no other tasks in the stack:
2168 * - if this task is in the pinned stack, then we remove the stack completely, which will
2169 * have the effect of moving the task to the top or bottom of the fullscreen stack
2170 * (depending on whether it is visible)
2171 * - otherwise, we simply return home and hide this task
2172 *
2173 * @param token A reference to the activity we wish to move
2174 * @param nonRoot If false then this only works if the activity is the root
2175 * of a task; if true it will work for any activity in a task.
2176 * @return Returns true if the move completed, false if not.
2177 */
2178 @Override
2179 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002180 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181 synchronized (mGlobalLock) {
2182 final long origId = Binder.clearCallingIdentity();
2183 try {
2184 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002185 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 if (task != null) {
2187 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2188 }
2189 } finally {
2190 Binder.restoreCallingIdentity(origId);
2191 }
2192 }
2193 return false;
2194 }
2195
2196 @Override
2197 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002198 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 long ident = Binder.clearCallingIdentity();
2200 Rect rect = new Rect();
2201 try {
2202 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002203 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2205 if (task == null) {
2206 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2207 return rect;
2208 }
2209 if (task.getStack() != null) {
2210 // Return the bounds from window manager since it will be adjusted for various
2211 // things like the presense of a docked stack for tasks that aren't resizeable.
2212 task.getWindowContainerBounds(rect);
2213 } else {
2214 // Task isn't in window manager yet since it isn't associated with a stack.
2215 // Return the persist value from activity manager
2216 if (!task.matchParentBounds()) {
2217 rect.set(task.getBounds());
2218 } else if (task.mLastNonFullscreenBounds != null) {
2219 rect.set(task.mLastNonFullscreenBounds);
2220 }
2221 }
2222 }
2223 } finally {
2224 Binder.restoreCallingIdentity(ident);
2225 }
2226 return rect;
2227 }
2228
2229 @Override
2230 public ActivityManager.TaskDescription getTaskDescription(int id) {
2231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002232 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002234 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002235 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2236 if (tr != null) {
2237 return tr.lastTaskDescription;
2238 }
2239 }
2240 return null;
2241 }
2242
2243 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002244 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2245 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2246 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2247 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2248 return;
2249 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002251 synchronized (mGlobalLock) {
2252 final long ident = Binder.clearCallingIdentity();
2253 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002254 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002255 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002256 if (task == null) {
2257 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2258 return;
2259 }
2260
2261 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2262 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2263
2264 if (!task.isActivityTypeStandardOrUndefined()) {
2265 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2266 + " non-standard task " + taskId + " to windowing mode="
2267 + windowingMode);
2268 }
2269
2270 final ActivityStack stack = task.getStack();
2271 if (toTop) {
2272 stack.moveToFront("setTaskWindowingMode", task);
2273 }
2274 stack.setWindowingMode(windowingMode);
2275 } finally {
2276 Binder.restoreCallingIdentity(ident);
2277 }
2278 }
2279 }
2280
2281 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002282 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002283 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284 ActivityRecord r = getCallingRecordLocked(token);
2285 return r != null ? r.info.packageName : null;
2286 }
2287 }
2288
2289 @Override
2290 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002291 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 ActivityRecord r = getCallingRecordLocked(token);
2293 return r != null ? r.intent.getComponent() : null;
2294 }
2295 }
2296
2297 private ActivityRecord getCallingRecordLocked(IBinder token) {
2298 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2299 if (r == null) {
2300 return null;
2301 }
2302 return r.resultTo;
2303 }
2304
2305 @Override
2306 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308
2309 synchronized (mGlobalLock) {
2310 final long origId = Binder.clearCallingIdentity();
2311 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002312 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 } finally {
2314 Binder.restoreCallingIdentity(origId);
2315 }
2316 }
2317 }
2318
Mark Renouf446251d2019-04-26 10:22:41 -04002319 @Override
2320 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2321 synchronized (mGlobalLock) {
2322 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2323 if (r == null) {
2324 return;
2325 }
2326 ActivityStack stack = r.getActivityStack();
2327 if (stack != null && stack.isSingleTaskInstance()) {
2328 // Single-task stacks are used for activities which are presented in floating
2329 // windows above full screen activities. Instead of directly finishing the
2330 // task, a task change listener is used to notify SystemUI so the action can be
2331 // handled specially.
2332 final TaskRecord task = r.getTaskRecord();
2333 mTaskChangeNotificationController
2334 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2335 } else {
2336 try {
2337 callback.requestFinish();
2338 } catch (RemoteException e) {
2339 Slog.e(TAG, "Failed to invoke request finish callback", e);
2340 }
2341 }
2342 }
2343 }
2344
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345 /**
2346 * TODO: Add mController hook
2347 */
2348 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002349 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2350 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002351 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002352
2353 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2354 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2356 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357 }
2358 }
2359
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2361 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002362 boolean fromRecents) {
2363
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 final int callingPid = Binder.getCallingPid();
2365 final int callingUid = Binder.getCallingUid();
2366 if (!isSameApp(callingUid, callingPackage)) {
2367 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2368 + Binder.getCallingPid() + " as package " + callingPackage;
2369 Slog.w(TAG, msg);
2370 throw new SecurityException(msg);
2371 }
2372 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 SafeActivityOptions.abort(options);
2374 return;
2375 }
2376 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 WindowProcessController callerApp = null;
2378 if (appThread != null) {
2379 callerApp = getProcessController(appThread);
2380 }
2381 final ActivityStarter starter = getActivityStartController().obtainStarter(
2382 null /* intent */, "moveTaskToFront");
2383 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2384 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002385 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 return;
2387 }
2388 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002390 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 if (task == null) {
2392 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002393 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 return;
2395 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002396 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002398 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 return;
2400 }
2401 ActivityOptions realOptions = options != null
2402 ? options.getOptions(mStackSupervisor)
2403 : null;
2404 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2405 false /* forceNonResizable */);
2406
2407 final ActivityRecord topActivity = task.getTopActivity();
2408 if (topActivity != null) {
2409
2410 // We are reshowing a task, use a starting window to hide the initial draw delay
2411 // so the transition can start earlier.
2412 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2413 true /* taskSwitch */, fromRecents);
2414 }
2415 } finally {
2416 Binder.restoreCallingIdentity(origId);
2417 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002418 }
2419
Ricky Waiaca8a772019-04-04 16:01:06 +01002420 /**
2421 * Return true if callingUid is system, or packageName belongs to that callingUid.
2422 */
2423 boolean isSameApp(int callingUid, @Nullable String packageName) {
2424 try {
2425 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2426 if (packageName == null) {
2427 return false;
2428 }
2429 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2430 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2431 UserHandle.getUserId(callingUid));
2432 return UserHandle.isSameApp(callingUid, uid);
2433 }
2434 } catch (RemoteException e) {
2435 // Should not happen
2436 }
2437 return true;
2438 }
2439
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002440 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2441 int callingPid, int callingUid, String name) {
2442 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2443 return true;
2444 }
2445
2446 if (getRecentTasks().isCallerRecents(sourceUid)) {
2447 return true;
2448 }
2449
2450 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2451 if (perm == PackageManager.PERMISSION_GRANTED) {
2452 return true;
2453 }
2454 if (checkAllowAppSwitchUid(sourceUid)) {
2455 return true;
2456 }
2457
2458 // If the actual IPC caller is different from the logical source, then
2459 // also see if they are allowed to control app switches.
2460 if (callingUid != -1 && callingUid != sourceUid) {
2461 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2462 if (perm == PackageManager.PERMISSION_GRANTED) {
2463 return true;
2464 }
2465 if (checkAllowAppSwitchUid(callingUid)) {
2466 return true;
2467 }
2468 }
2469
2470 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2471 return false;
2472 }
2473
2474 private boolean checkAllowAppSwitchUid(int uid) {
2475 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2476 if (types != null) {
2477 for (int i = types.size() - 1; i >= 0; i--) {
2478 if (types.valueAt(i).intValue() == uid) {
2479 return true;
2480 }
2481 }
2482 }
2483 return false;
2484 }
2485
2486 @Override
2487 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2488 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2489 "setActivityController()");
2490 synchronized (mGlobalLock) {
2491 mController = controller;
2492 mControllerIsAMonkey = imAMonkey;
2493 Watchdog.getInstance().setActivityController(controller);
2494 }
2495 }
2496
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002497 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002498 synchronized (mGlobalLock) {
2499 return mController != null && mControllerIsAMonkey;
2500 }
2501 }
2502
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002503 @Override
2504 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2505 synchronized (mGlobalLock) {
2506 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2507 }
2508 }
2509
2510 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002511 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2512 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2513 }
2514
2515 @Override
2516 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2517 @WindowConfiguration.ActivityType int ignoreActivityType,
2518 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2519 final int callingUid = Binder.getCallingUid();
2520 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2521
2522 synchronized (mGlobalLock) {
2523 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002525 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002527 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002528 ignoreWindowingMode, callingUid, allowed);
2529 }
2530
2531 return list;
2532 }
2533
2534 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2536 synchronized (mGlobalLock) {
2537 final long origId = Binder.clearCallingIdentity();
2538 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2539 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002540 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002541 }
2542 Binder.restoreCallingIdentity(origId);
2543 }
2544 }
2545
2546 @Override
2547 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002548 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 ActivityStack stack = ActivityRecord.getStackLocked(token);
2550 if (stack != null) {
2551 return stack.willActivityBeVisibleLocked(token);
2552 }
2553 return false;
2554 }
2555 }
2556
2557 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002559 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002560 synchronized (mGlobalLock) {
2561 final long ident = Binder.clearCallingIdentity();
2562 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 if (task == null) {
2565 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2566 return;
2567 }
2568
2569 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2570 + " to stackId=" + stackId + " toTop=" + toTop);
2571
Wale Ogunwaled32da472018-11-16 07:19:28 -08002572 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 if (stack == null) {
2574 throw new IllegalStateException(
2575 "moveTaskToStack: No stack for stackId=" + stackId);
2576 }
2577 if (!stack.isActivityTypeStandardOrUndefined()) {
2578 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2579 + taskId + " to stack " + stackId);
2580 }
2581 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2584 }
2585 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2586 "moveTaskToStack");
2587 } finally {
2588 Binder.restoreCallingIdentity(ident);
2589 }
2590 }
2591 }
2592
2593 @Override
2594 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2595 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002596 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002597
2598 final long ident = Binder.clearCallingIdentity();
2599 try {
2600 synchronized (mGlobalLock) {
2601 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002602 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 if (stack == null) {
2604 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2605 return;
2606 }
2607 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2608 throw new IllegalArgumentException("Stack: " + stackId
2609 + " doesn't support animated resize.");
2610 }
2611 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2612 animationDuration, false /* fromFullscreen */);
2613 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002614 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 if (stack == null) {
2616 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2617 return;
2618 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002619 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002620 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2621 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2622 }
2623 }
2624 } finally {
2625 Binder.restoreCallingIdentity(ident);
2626 }
2627 }
2628
wilsonshih5c4cf522019-01-25 09:03:47 +08002629 @Override
2630 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2631 int animationDuration) {
2632 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2633
2634 final long ident = Binder.clearCallingIdentity();
2635 try {
2636 synchronized (mGlobalLock) {
2637 if (xOffset == 0 && yOffset == 0) {
2638 return;
2639 }
2640 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2641 if (stack == null) {
2642 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2643 return;
2644 }
2645 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2646 throw new IllegalArgumentException("Stack: " + stackId
2647 + " doesn't support animated resize.");
2648 }
2649 final Rect destBounds = new Rect();
2650 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002651 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002652 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2653 return;
2654 }
2655 destBounds.offset(xOffset, yOffset);
2656 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2657 animationDuration, false /* fromFullscreen */);
2658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002663 /**
2664 * Moves the specified task to the primary-split-screen stack.
2665 *
2666 * @param taskId Id of task to move.
2667 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2668 * exist already. See
2669 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2670 * and
2671 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2672 * @param toTop If the task and stack should be moved to the top.
2673 * @param animate Whether we should play an animation for the moving the task.
2674 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2675 * stack. Pass {@code null} to use default bounds.
2676 * @param showRecents If the recents activity should be shown on the other side of the task
2677 * going into split-screen mode.
2678 */
2679 @Override
2680 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2681 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002682 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002683 "setTaskWindowingModeSplitScreenPrimary()");
2684 synchronized (mGlobalLock) {
2685 final long ident = Binder.clearCallingIdentity();
2686 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002687 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002688 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 if (task == null) {
2690 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2691 return false;
2692 }
2693 if (DEBUG_STACK) Slog.d(TAG_STACK,
2694 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2695 + " to createMode=" + createMode + " toTop=" + toTop);
2696 if (!task.isActivityTypeStandardOrUndefined()) {
2697 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2698 + " non-standard task " + taskId + " to split-screen windowing mode");
2699 }
2700
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002701 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002702 final int windowingMode = task.getWindowingMode();
2703 final ActivityStack stack = task.getStack();
2704 if (toTop) {
2705 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2706 }
2707 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002708 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2709 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 return windowingMode != task.getWindowingMode();
2711 } finally {
2712 Binder.restoreCallingIdentity(ident);
2713 }
2714 }
2715 }
2716
2717 /**
2718 * Removes stacks in the input windowing modes from the system if they are of activity type
2719 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2720 */
2721 @Override
2722 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002723 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 "removeStacksInWindowingModes()");
2725
2726 synchronized (mGlobalLock) {
2727 final long ident = Binder.clearCallingIdentity();
2728 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002729 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 } finally {
2731 Binder.restoreCallingIdentity(ident);
2732 }
2733 }
2734 }
2735
2736 @Override
2737 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002738 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 "removeStacksWithActivityTypes()");
2740
2741 synchronized (mGlobalLock) {
2742 final long ident = Binder.clearCallingIdentity();
2743 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002744 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002745 } finally {
2746 Binder.restoreCallingIdentity(ident);
2747 }
2748 }
2749 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750
2751 @Override
2752 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2753 int userId) {
2754 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2756 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002758 final boolean detailed = checkGetTasksPermission(
2759 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2760 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 == PackageManager.PERMISSION_GRANTED;
2762
2763 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002764 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 callingUid);
2766 }
2767 }
2768
2769 @Override
2770 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002771 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 long ident = Binder.clearCallingIdentity();
2773 try {
2774 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002775 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 }
2777 } finally {
2778 Binder.restoreCallingIdentity(ident);
2779 }
2780 }
2781
2782 @Override
2783 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002785 long ident = Binder.clearCallingIdentity();
2786 try {
2787 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002788 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 }
2790 } finally {
2791 Binder.restoreCallingIdentity(ident);
2792 }
2793 }
2794
2795 @Override
2796 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002797 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 final long callingUid = Binder.getCallingUid();
2799 final long origId = Binder.clearCallingIdentity();
2800 try {
2801 synchronized (mGlobalLock) {
2802 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2805 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2806 }
2807 } finally {
2808 Binder.restoreCallingIdentity(origId);
2809 }
2810 }
2811
2812 @Override
2813 public void startLockTaskModeByToken(IBinder token) {
2814 synchronized (mGlobalLock) {
2815 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2816 if (r == null) {
2817 return;
2818 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002819 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002820 }
2821 }
2822
2823 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002824 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002825 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 // This makes inner call to look as if it was initiated by system.
2827 long ident = Binder.clearCallingIdentity();
2828 try {
2829 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002830 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002831 MATCH_TASK_IN_STACKS_ONLY);
2832 if (task == null) {
2833 return;
2834 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835
2836 // When starting lock task mode the stack must be in front and focused
2837 task.getStack().moveToFront("startSystemLockTaskMode");
2838 startLockTaskModeLocked(task, true /* isSystemCaller */);
2839 }
2840 } finally {
2841 Binder.restoreCallingIdentity(ident);
2842 }
2843 }
2844
2845 @Override
2846 public void stopLockTaskModeByToken(IBinder token) {
2847 synchronized (mGlobalLock) {
2848 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2849 if (r == null) {
2850 return;
2851 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002852 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 }
2854 }
2855
2856 /**
2857 * This API should be called by SystemUI only when user perform certain action to dismiss
2858 * lock task mode. We should only dismiss pinned lock task mode in this case.
2859 */
2860 @Override
2861 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002862 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2864 }
2865
2866 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2867 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2868 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2869 return;
2870 }
2871
Wale Ogunwaled32da472018-11-16 07:19:28 -08002872 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 if (stack == null || task != stack.topTask()) {
2874 throw new IllegalArgumentException("Invalid task, not in foreground");
2875 }
2876
2877 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2878 // system or a specific app.
2879 // * System-initiated requests will only start the pinned mode (screen pinning)
2880 // * App-initiated requests
2881 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2882 // - will start the pinned mode, otherwise
2883 final int callingUid = Binder.getCallingUid();
2884 long ident = Binder.clearCallingIdentity();
2885 try {
2886 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002887 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002889 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 } finally {
2891 Binder.restoreCallingIdentity(ident);
2892 }
2893 }
2894
2895 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2896 final int callingUid = Binder.getCallingUid();
2897 long ident = Binder.clearCallingIdentity();
2898 try {
2899 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002900 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2903 // task and jumping straight into a call in the case of emergency call back.
2904 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2905 if (tm != null) {
2906 tm.showInCallScreen(false);
2907 }
2908 } finally {
2909 Binder.restoreCallingIdentity(ident);
2910 }
2911 }
2912
2913 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002914 public void updateLockTaskPackages(int userId, String[] packages) {
2915 final int callingUid = Binder.getCallingUid();
2916 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2917 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2918 "updateLockTaskPackages()");
2919 }
2920 synchronized (this) {
2921 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2922 + Arrays.toString(packages));
2923 getLockTaskController().updateLockTaskPackages(userId, packages);
2924 }
2925 }
2926
2927 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928 public boolean isInLockTaskMode() {
2929 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2930 }
2931
2932 @Override
2933 public int getLockTaskModeState() {
2934 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002935 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 }
2937 }
2938
2939 @Override
2940 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2941 synchronized (mGlobalLock) {
2942 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2943 if (r != null) {
2944 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002945 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002947 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 }
2949 }
2950 }
2951
2952 @Override
2953 public Bundle getActivityOptions(IBinder token) {
2954 final long origId = Binder.clearCallingIdentity();
2955 try {
2956 synchronized (mGlobalLock) {
2957 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2958 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002959 final ActivityOptions activityOptions = r.takeOptionsLocked(
2960 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 return activityOptions == null ? null : activityOptions.toBundle();
2962 }
2963 return null;
2964 }
2965 } finally {
2966 Binder.restoreCallingIdentity(origId);
2967 }
2968 }
2969
2970 @Override
2971 public List<IBinder> getAppTasks(String callingPackage) {
2972 int callingUid = Binder.getCallingUid();
2973 long ident = Binder.clearCallingIdentity();
2974 try {
2975 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002976 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 }
2978 } finally {
2979 Binder.restoreCallingIdentity(ident);
2980 }
2981 }
2982
2983 @Override
2984 public void finishVoiceTask(IVoiceInteractionSession session) {
2985 synchronized (mGlobalLock) {
2986 final long origId = Binder.clearCallingIdentity();
2987 try {
2988 // TODO: VI Consider treating local voice interactions and voice tasks
2989 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002990 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002991 } finally {
2992 Binder.restoreCallingIdentity(origId);
2993 }
2994 }
2995
2996 }
2997
2998 @Override
2999 public boolean isTopOfTask(IBinder token) {
3000 synchronized (mGlobalLock) {
3001 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003002 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 }
3004 }
3005
3006 @Override
3007 public void notifyLaunchTaskBehindComplete(IBinder token) {
3008 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3009 }
3010
3011 @Override
3012 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003013 mH.post(() -> {
3014 synchronized (mGlobalLock) {
3015 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003016 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003017 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003018 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003019 } catch (RemoteException e) {
3020 }
3021 }
3022 }
3023
3024 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026
3027 /** Called from an app when assist data is ready. */
3028 @Override
3029 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3030 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003031 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 synchronized (pae) {
3033 pae.result = extras;
3034 pae.structure = structure;
3035 pae.content = content;
3036 if (referrer != null) {
3037 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3038 }
3039 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003040 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003041 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3042 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 structure.setHomeActivity(pae.isHome);
3044 }
3045 pae.haveResult = true;
3046 pae.notifyAll();
3047 if (pae.intent == null && pae.receiver == null) {
3048 // Caller is just waiting for the result.
3049 return;
3050 }
3051 }
3052 // We are now ready to launch the assist activity.
3053 IAssistDataReceiver sendReceiver = null;
3054 Bundle sendBundle = null;
3055 synchronized (mGlobalLock) {
3056 buildAssistBundleLocked(pae, extras);
3057 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003058 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 if (!exists) {
3060 // Timed out.
3061 return;
3062 }
3063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003064 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 // Caller wants result sent back to them.
3066 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003067 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3068 pae.activity.getTaskRecord().taskId);
3069 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3070 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3072 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3073 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3074 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3075 }
3076 }
3077 if (sendReceiver != null) {
3078 try {
3079 sendReceiver.onHandleAssistData(sendBundle);
3080 } catch (RemoteException e) {
3081 }
3082 return;
3083 }
3084
3085 final long ident = Binder.clearCallingIdentity();
3086 try {
3087 if (TextUtils.equals(pae.intent.getAction(),
3088 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003089 // Start voice interaction through VoiceInteractionManagerService.
3090 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3091 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 } else {
3093 pae.intent.replaceExtras(pae.extras);
3094 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3095 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3096 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003097 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098
3099 try {
3100 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3101 } catch (ActivityNotFoundException e) {
3102 Slog.w(TAG, "No activity to handle assist action.", e);
3103 }
3104 }
3105 } finally {
3106 Binder.restoreCallingIdentity(ident);
3107 }
3108 }
3109
3110 @Override
3111 public int addAppTask(IBinder activityToken, Intent intent,
3112 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3113 final int callingUid = Binder.getCallingUid();
3114 final long callingIdent = Binder.clearCallingIdentity();
3115
3116 try {
3117 synchronized (mGlobalLock) {
3118 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3119 if (r == null) {
3120 throw new IllegalArgumentException("Activity does not exist; token="
3121 + activityToken);
3122 }
3123 ComponentName comp = intent.getComponent();
3124 if (comp == null) {
3125 throw new IllegalArgumentException("Intent " + intent
3126 + " must specify explicit component");
3127 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003128 if (thumbnail.getWidth() != mThumbnailWidth
3129 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 throw new IllegalArgumentException("Bad thumbnail size: got "
3131 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003132 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 }
3134 if (intent.getSelector() != null) {
3135 intent.setSelector(null);
3136 }
3137 if (intent.getSourceBounds() != null) {
3138 intent.setSourceBounds(null);
3139 }
3140 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3141 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3142 // The caller has added this as an auto-remove task... that makes no
3143 // sense, so turn off auto-remove.
3144 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3145 }
3146 }
3147 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3148 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3149 if (ainfo.applicationInfo.uid != callingUid) {
3150 throw new SecurityException(
3151 "Can't add task for another application: target uid="
3152 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3153 }
3154
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003155 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003157 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003159 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 // The app has too many tasks already and we can't add any more
3161 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3162 return INVALID_TASK_ID;
3163 }
3164 task.lastTaskDescription.copyFrom(description);
3165
3166 // TODO: Send the thumbnail to WM to store it.
3167
3168 return task.taskId;
3169 }
3170 } finally {
3171 Binder.restoreCallingIdentity(callingIdent);
3172 }
3173 }
3174
3175 @Override
3176 public Point getAppTaskThumbnailSize() {
3177 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003178 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 }
3181
3182 @Override
3183 public void setTaskResizeable(int taskId, int resizeableMode) {
3184 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003185 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3187 if (task == null) {
3188 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3189 return;
3190 }
3191 task.setResizeMode(resizeableMode);
3192 }
3193 }
3194
3195 @Override
3196 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003197 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 long ident = Binder.clearCallingIdentity();
3199 try {
3200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003201 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003202 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 if (task == null) {
3204 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3205 return;
3206 }
3207 // Place the task in the right stack if it isn't there already based on
3208 // the requested bounds.
3209 // The stack transition logic is:
3210 // - a null bounds on a freeform task moves that task to fullscreen
3211 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3212 // that task to freeform
3213 // - otherwise the task is not moved
3214 ActivityStack stack = task.getStack();
3215 if (!task.getWindowConfiguration().canResizeTask()) {
3216 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3217 }
3218 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3219 stack = stack.getDisplay().getOrCreateStack(
3220 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3221 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3222 stack = stack.getDisplay().getOrCreateStack(
3223 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3224 }
3225
3226 // Reparent the task to the right stack if necessary
3227 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3228 if (stack != task.getStack()) {
3229 // Defer resume until the task is resized below
3230 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3231 DEFER_RESUME, "resizeTask");
3232 preserveWindow = false;
3233 }
3234
3235 // After reparenting (which only resizes the task to the stack bounds), resize the
3236 // task to the actual bounds provided
3237 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3238 }
3239 } finally {
3240 Binder.restoreCallingIdentity(ident);
3241 }
3242 }
3243
3244 @Override
3245 public boolean releaseActivityInstance(IBinder token) {
3246 synchronized (mGlobalLock) {
3247 final long origId = Binder.clearCallingIdentity();
3248 try {
3249 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3250 if (r == null) {
3251 return false;
3252 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003253 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 } finally {
3255 Binder.restoreCallingIdentity(origId);
3256 }
3257 }
3258 }
3259
3260 @Override
3261 public void releaseSomeActivities(IApplicationThread appInt) {
3262 synchronized (mGlobalLock) {
3263 final long origId = Binder.clearCallingIdentity();
3264 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003265 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003266 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 } finally {
3268 Binder.restoreCallingIdentity(origId);
3269 }
3270 }
3271 }
3272
3273 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003274 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003275 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 != PackageManager.PERMISSION_GRANTED) {
3277 throw new SecurityException("Requires permission "
3278 + android.Manifest.permission.DEVICE_POWER);
3279 }
3280
3281 synchronized (mGlobalLock) {
3282 long ident = Binder.clearCallingIdentity();
3283 if (mKeyguardShown != keyguardShowing) {
3284 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003285 final Message msg = PooledLambda.obtainMessage(
3286 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3287 keyguardShowing);
3288 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 }
3290 try {
wilsonshih177261f2019-02-22 12:02:18 +08003291 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292 } finally {
3293 Binder.restoreCallingIdentity(ident);
3294 }
3295 }
3296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003297 mH.post(() -> {
3298 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3299 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3300 }
3301 });
3302 }
3303
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003304 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003305 mH.post(() -> {
3306 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3307 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3308 }
3309 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 }
3311
3312 @Override
3313 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3315 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316
3317 final File passedIconFile = new File(filePath);
3318 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3319 passedIconFile.getName());
3320 if (!legitIconFile.getPath().equals(filePath)
3321 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3322 throw new IllegalArgumentException("Bad file path: " + filePath
3323 + " passed for userId " + userId);
3324 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003325 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003326 }
3327
3328 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003329 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003330 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3331 final ActivityOptions activityOptions = safeOptions != null
3332 ? safeOptions.getOptions(mStackSupervisor)
3333 : null;
3334 if (activityOptions == null
3335 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3336 || activityOptions.getCustomInPlaceResId() == 0) {
3337 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3338 "with valid animation");
3339 }
lumark588a3e82018-07-20 18:53:54 +08003340 // Get top display of front most application.
3341 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3342 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003343 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3344 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3345 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003346 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003347 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003348 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 }
3350
3351 @Override
3352 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 synchronized (mGlobalLock) {
3355 final long ident = Binder.clearCallingIdentity();
3356 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003357 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 if (stack == null) {
3359 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3360 return;
3361 }
3362 if (!stack.isActivityTypeStandardOrUndefined()) {
3363 throw new IllegalArgumentException(
3364 "Removing non-standard stack is not allowed.");
3365 }
3366 mStackSupervisor.removeStack(stack);
3367 } finally {
3368 Binder.restoreCallingIdentity(ident);
3369 }
3370 }
3371 }
3372
3373 @Override
3374 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003375 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003376
3377 synchronized (mGlobalLock) {
3378 final long ident = Binder.clearCallingIdentity();
3379 try {
3380 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3381 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003382 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 } finally {
3384 Binder.restoreCallingIdentity(ident);
3385 }
3386 }
3387 }
3388
3389 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003390 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 synchronized (mGlobalLock) {
3392 long ident = Binder.clearCallingIdentity();
3393 try {
3394 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3395 if (r == null) {
3396 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003397 "toggleFreeformWindowingMode: No activity record matching token="
3398 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 }
3400
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003401 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003402 if (stack == null) {
3403 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3404 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405 }
3406
Yunfan Chend967af82019-01-17 18:30:18 +09003407 if (!stack.inFreeformWindowingMode()
3408 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3409 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3410 + "toggle between fullscreen and freeform.");
3411 }
3412
3413 if (stack.inFreeformWindowingMode()) {
3414 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003415 } else if (stack.getParent().inFreeformWindowingMode()) {
3416 // If the window is on a freeform display, set it to undefined. It will be
3417 // resolved to freeform and it can adjust windowing mode when the display mode
3418 // changes in runtime.
3419 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003420 } else {
3421 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3422 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 } finally {
3424 Binder.restoreCallingIdentity(ident);
3425 }
3426 }
3427 }
3428
3429 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3430 @Override
3431 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003434 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 }
3436
3437 /** Unregister a task stack listener so that it stops receiving callbacks. */
3438 @Override
3439 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003440 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003441 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003442 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 }
3444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 @Override
3446 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3447 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3448 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3449 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3450 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3451 }
3452
3453 @Override
3454 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3455 IBinder activityToken, int flags) {
3456 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3457 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3458 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3459 }
3460
3461 @Override
3462 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3463 Bundle args) {
3464 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3465 true /* focused */, true /* newSessionId */, userHandle, args,
3466 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3467 }
3468
3469 @Override
3470 public Bundle getAssistContextExtras(int requestType) {
3471 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3472 null, null, true /* focused */, true /* newSessionId */,
3473 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3474 if (pae == null) {
3475 return null;
3476 }
3477 synchronized (pae) {
3478 while (!pae.haveResult) {
3479 try {
3480 pae.wait();
3481 } catch (InterruptedException e) {
3482 }
3483 }
3484 }
3485 synchronized (mGlobalLock) {
3486 buildAssistBundleLocked(pae, pae.result);
3487 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003488 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 }
3490 return pae.extras;
3491 }
3492
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003493 /**
3494 * Binder IPC calls go through the public entry point.
3495 * This can be called with or without the global lock held.
3496 */
3497 private static int checkCallingPermission(String permission) {
3498 return checkPermission(
3499 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3500 }
3501
3502 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003503 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003504 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3505 mAmInternal.enforceCallingPermission(permission, func);
3506 }
3507 }
3508
3509 @VisibleForTesting
3510 int checkGetTasksPermission(String permission, int pid, int uid) {
3511 return checkPermission(permission, pid, uid);
3512 }
3513
3514 static int checkPermission(String permission, int pid, int uid) {
3515 if (permission == null) {
3516 return PackageManager.PERMISSION_DENIED;
3517 }
3518 return checkComponentPermission(permission, pid, uid, -1, true);
3519 }
3520
Wale Ogunwale214f3482018-10-04 11:00:47 -07003521 public static int checkComponentPermission(String permission, int pid, int uid,
3522 int owningUid, boolean exported) {
3523 return ActivityManagerService.checkComponentPermission(
3524 permission, pid, uid, owningUid, exported);
3525 }
3526
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3528 if (getRecentTasks().isCallerRecents(callingUid)) {
3529 // Always allow the recents component to get tasks
3530 return true;
3531 }
3532
3533 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3534 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3535 if (!allowed) {
3536 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3537 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3538 // Temporary compatibility: some existing apps on the system image may
3539 // still be requesting the old permission and not switched to the new
3540 // one; if so, we'll still allow them full access. This means we need
3541 // to see if they are holding the old permission and are a system app.
3542 try {
3543 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3544 allowed = true;
3545 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3546 + " is using old GET_TASKS but privileged; allowing");
3547 }
3548 } catch (RemoteException e) {
3549 }
3550 }
3551 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3552 + " does not hold REAL_GET_TASKS; limiting output");
3553 }
3554 return allowed;
3555 }
3556
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3558 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3559 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3560 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003561 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 "enqueueAssistContext()");
3563
3564 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003565 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 if (activity == null) {
3567 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3568 return null;
3569 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003570 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3572 return null;
3573 }
3574 if (focused) {
3575 if (activityToken != null) {
3576 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3577 if (activity != caller) {
3578 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3579 + " is not current top " + activity);
3580 return null;
3581 }
3582 }
3583 } else {
3584 activity = ActivityRecord.forTokenLocked(activityToken);
3585 if (activity == null) {
3586 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3587 + " couldn't be found");
3588 return null;
3589 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003590 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3592 return null;
3593 }
3594 }
3595
3596 PendingAssistExtras pae;
3597 Bundle extras = new Bundle();
3598 if (args != null) {
3599 extras.putAll(args);
3600 }
3601 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003602 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603
3604 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3605 userHandle);
3606 pae.isHome = activity.isActivityTypeHome();
3607
3608 // Increment the sessionId if necessary
3609 if (newSessionId) {
3610 mViSessionId++;
3611 }
3612 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003613 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3614 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003615 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003616 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003617 } catch (RemoteException e) {
3618 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3619 return null;
3620 }
3621 return pae;
3622 }
3623 }
3624
3625 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3626 if (result != null) {
3627 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3628 }
3629 if (pae.hint != null) {
3630 pae.extras.putBoolean(pae.hint, true);
3631 }
3632 }
3633
3634 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3635 IAssistDataReceiver receiver;
3636 synchronized (mGlobalLock) {
3637 mPendingAssistExtras.remove(pae);
3638 receiver = pae.receiver;
3639 }
3640 if (receiver != null) {
3641 // Caller wants result sent back to them.
3642 Bundle sendBundle = new Bundle();
3643 // At least return the receiver extras
3644 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3645 try {
3646 pae.receiver.onHandleAssistData(sendBundle);
3647 } catch (RemoteException e) {
3648 }
3649 }
3650 }
3651
3652 public class PendingAssistExtras extends Binder implements Runnable {
3653 public final ActivityRecord activity;
3654 public boolean isHome;
3655 public final Bundle extras;
3656 public final Intent intent;
3657 public final String hint;
3658 public final IAssistDataReceiver receiver;
3659 public final int userHandle;
3660 public boolean haveResult = false;
3661 public Bundle result = null;
3662 public AssistStructure structure = null;
3663 public AssistContent content = null;
3664 public Bundle receiverExtras;
3665
3666 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3667 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3668 int _userHandle) {
3669 activity = _activity;
3670 extras = _extras;
3671 intent = _intent;
3672 hint = _hint;
3673 receiver = _receiver;
3674 receiverExtras = _receiverExtras;
3675 userHandle = _userHandle;
3676 }
3677
3678 @Override
3679 public void run() {
3680 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3681 synchronized (this) {
3682 haveResult = true;
3683 notifyAll();
3684 }
3685 pendingAssistExtrasTimedOut(this);
3686 }
3687 }
3688
3689 @Override
3690 public boolean isAssistDataAllowedOnCurrentActivity() {
3691 int userId;
3692 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003693 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3695 return false;
3696 }
3697
3698 final ActivityRecord activity = focusedStack.getTopActivity();
3699 if (activity == null) {
3700 return false;
3701 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003702 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 }
3704 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3705 }
3706
3707 @Override
3708 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3709 long ident = Binder.clearCallingIdentity();
3710 try {
3711 synchronized (mGlobalLock) {
3712 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003713 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 if (top != caller) {
3715 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3716 + " is not current top " + top);
3717 return false;
3718 }
3719 if (!top.nowVisible) {
3720 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3721 + " is not visible");
3722 return false;
3723 }
3724 }
3725 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3726 token);
3727 } finally {
3728 Binder.restoreCallingIdentity(ident);
3729 }
3730 }
3731
3732 @Override
3733 public boolean isRootVoiceInteraction(IBinder token) {
3734 synchronized (mGlobalLock) {
3735 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3736 if (r == null) {
3737 return false;
3738 }
3739 return r.rootVoiceInteraction;
3740 }
3741 }
3742
Wale Ogunwalef6733932018-06-27 05:14:34 -07003743 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3744 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3745 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3746 if (activityToCallback == null) return;
3747 activityToCallback.setVoiceSessionLocked(voiceSession);
3748
3749 // Inform the activity
3750 try {
3751 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3752 voiceInteractor);
3753 long token = Binder.clearCallingIdentity();
3754 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003755 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003756 } finally {
3757 Binder.restoreCallingIdentity(token);
3758 }
3759 // TODO: VI Should we cache the activity so that it's easier to find later
3760 // rather than scan through all the stacks and activities?
3761 } catch (RemoteException re) {
3762 activityToCallback.clearVoiceSessionLocked();
3763 // TODO: VI Should this terminate the voice session?
3764 }
3765 }
3766
3767 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3768 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3769 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3770 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3771 boolean wasRunningVoice = mRunningVoice != null;
3772 mRunningVoice = session;
3773 if (!wasRunningVoice) {
3774 mVoiceWakeLock.acquire();
3775 updateSleepIfNeededLocked();
3776 }
3777 }
3778 }
3779
3780 void finishRunningVoiceLocked() {
3781 if (mRunningVoice != null) {
3782 mRunningVoice = null;
3783 mVoiceWakeLock.release();
3784 updateSleepIfNeededLocked();
3785 }
3786 }
3787
3788 @Override
3789 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3790 synchronized (mGlobalLock) {
3791 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3792 if (keepAwake) {
3793 mVoiceWakeLock.acquire();
3794 } else {
3795 mVoiceWakeLock.release();
3796 }
3797 }
3798 }
3799 }
3800
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 @Override
3802 public ComponentName getActivityClassForToken(IBinder token) {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return null;
3807 }
3808 return r.intent.getComponent();
3809 }
3810 }
3811
3812 @Override
3813 public String getPackageForToken(IBinder token) {
3814 synchronized (mGlobalLock) {
3815 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3816 if (r == null) {
3817 return null;
3818 }
3819 return r.packageName;
3820 }
3821 }
3822
3823 @Override
3824 public void showLockTaskEscapeMessage(IBinder token) {
3825 synchronized (mGlobalLock) {
3826 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3827 if (r == null) {
3828 return;
3829 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003830 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 }
3832 }
3833
3834 @Override
3835 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003836 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 final long token = Binder.clearCallingIdentity();
3838 try {
3839 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003840 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(token);
3844 }
3845 }
3846
3847 /**
3848 * Try to place task to provided position. The final position might be different depending on
3849 * current user and stacks state. The task will be moved to target stack if it's currently in
3850 * different stack.
3851 */
3852 @Override
3853 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003854 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 synchronized (mGlobalLock) {
3856 long ident = Binder.clearCallingIdentity();
3857 try {
3858 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3859 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003860 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861 if (task == null) {
3862 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3863 + taskId);
3864 }
3865
Wale Ogunwaled32da472018-11-16 07:19:28 -08003866 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003867
3868 if (stack == null) {
3869 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3870 + stackId);
3871 }
3872 if (!stack.isActivityTypeStandardOrUndefined()) {
3873 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3874 + " the position of task " + taskId + " in/to non-standard stack");
3875 }
3876
3877 // TODO: Have the callers of this API call a separate reparent method if that is
3878 // what they intended to do vs. having this method also do reparenting.
3879 if (task.getStack() == stack) {
3880 // Change position in current stack.
3881 stack.positionChildAt(task, position);
3882 } else {
3883 // Reparent to new stack.
3884 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3885 !DEFER_RESUME, "positionTaskInStack");
3886 }
3887 } finally {
3888 Binder.restoreCallingIdentity(ident);
3889 }
3890 }
3891 }
3892
3893 @Override
3894 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3895 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3896 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003897 + Arrays.toString(horizontalSizeConfiguration) + " "
3898 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003899 synchronized (mGlobalLock) {
3900 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3901 if (record == null) {
3902 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3903 + "found for: " + token);
3904 }
3905 record.setSizeConfigurations(horizontalSizeConfiguration,
3906 verticalSizeConfigurations, smallestSizeConfigurations);
3907 }
3908 }
3909
3910 /**
3911 * Dismisses split-screen multi-window mode.
3912 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3913 */
3914 @Override
3915 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003916 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3918 final long ident = Binder.clearCallingIdentity();
3919 try {
3920 synchronized (mGlobalLock) {
3921 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003922 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 if (stack == null) {
3924 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3925 return;
3926 }
3927
3928 if (toTop) {
3929 // Caller wants the current split-screen primary stack to be the top stack after
3930 // it goes fullscreen, so move it to the front.
3931 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003932 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003934 // stack after it goes fullscreen, so we move the focus to the top-most
3935 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3937 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3938 if (otherStack != null) {
3939 otherStack.moveToFront("dismissSplitScreenMode_other");
3940 }
3941 }
3942
Evan Rosky10475742018-09-05 19:02:48 -07003943 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 }
3945 } finally {
3946 Binder.restoreCallingIdentity(ident);
3947 }
3948 }
3949
3950 /**
3951 * Dismisses Pip
3952 * @param animate True if the dismissal should be animated.
3953 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3954 * default animation duration should be used.
3955 */
3956 @Override
3957 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003958 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 final long ident = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003962 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003963 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 if (stack == null) {
3965 Slog.w(TAG, "dismissPip: pinned stack not found.");
3966 return;
3967 }
3968 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3969 throw new IllegalArgumentException("Stack: " + stack
3970 + " doesn't support animated resize.");
3971 }
3972 if (animate) {
3973 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3974 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3975 } else {
3976 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3977 }
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983
3984 @Override
3985 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 synchronized (mGlobalLock) {
3988 mSuppressResizeConfigChanges = suppress;
3989 }
3990 }
3991
3992 /**
3993 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3994 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3995 * activity and clearing the task at the same time.
3996 */
3997 @Override
3998 // TODO: API should just be about changing windowing modes...
3999 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 "moveTasksToFullscreenStack()");
4002 synchronized (mGlobalLock) {
4003 final long origId = Binder.clearCallingIdentity();
4004 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004005 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 if (stack != null){
4007 if (!stack.isActivityTypeStandardOrUndefined()) {
4008 throw new IllegalArgumentException(
4009 "You can't move tasks from non-standard stacks.");
4010 }
4011 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(origId);
4015 }
4016 }
4017 }
4018
4019 /**
4020 * Moves the top activity in the input stackId to the pinned stack.
4021 *
4022 * @param stackId Id of stack to move the top activity to pinned stack.
4023 * @param bounds Bounds to use for pinned stack.
4024 *
4025 * @return True if the top activity of the input stack was successfully moved to the pinned
4026 * stack.
4027 */
4028 @Override
4029 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 "moveTopActivityToPinnedStack()");
4032 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4035 + "Device doesn't support picture-in-picture mode");
4036 }
4037
4038 long ident = Binder.clearCallingIdentity();
4039 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004040 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 } finally {
4042 Binder.restoreCallingIdentity(ident);
4043 }
4044 }
4045 }
4046
4047 @Override
4048 public boolean isInMultiWindowMode(IBinder token) {
4049 final long origId = Binder.clearCallingIdentity();
4050 try {
4051 synchronized (mGlobalLock) {
4052 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4053 if (r == null) {
4054 return false;
4055 }
4056 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4057 return r.inMultiWindowMode();
4058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(origId);
4061 }
4062 }
4063
4064 @Override
4065 public boolean isInPictureInPictureMode(IBinder token) {
4066 final long origId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4070 }
4071 } finally {
4072 Binder.restoreCallingIdentity(origId);
4073 }
4074 }
4075
4076 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004077 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4078 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 return false;
4080 }
4081
4082 // If we are animating to fullscreen then we have already dispatched the PIP mode
4083 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004084 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4085 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 }
4087
4088 @Override
4089 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4090 final long origId = Binder.clearCallingIdentity();
4091 try {
4092 synchronized (mGlobalLock) {
4093 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4094 "enterPictureInPictureMode", token, params);
4095
4096 // If the activity is already in picture in picture mode, then just return early
4097 if (isInPictureInPictureMode(r)) {
4098 return true;
4099 }
4100
4101 // Activity supports picture-in-picture, now check that we can enter PiP at this
4102 // point, if it is
4103 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4104 false /* beforeStopping */)) {
4105 return false;
4106 }
4107
4108 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004109 synchronized (mGlobalLock) {
4110 // Only update the saved args from the args that are set
4111 r.pictureInPictureArgs.copyOnlySet(params);
4112 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4113 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4114 // Adjust the source bounds by the insets for the transition down
4115 final Rect sourceBounds = new Rect(
4116 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004117 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004118 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004119 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 stack.setPictureInPictureAspectRatio(aspectRatio);
4121 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004122 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4123 r.info.applicationInfo.uid, r.shortComponentName,
4124 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004125 logPictureInPictureArgs(params);
4126 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 };
4128
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004129 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 // If the keyguard is showing or occluded, then try and dismiss it before
4131 // entering picture-in-picture (this will prompt the user to authenticate if the
4132 // device is currently locked).
4133 dismissKeyguard(token, new KeyguardDismissCallback() {
4134 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 public void onDismissSucceeded() {
4136 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 }
4138 }, null /* message */);
4139 } else {
4140 // Enter picture in picture immediately otherwise
4141 enterPipRunnable.run();
4142 }
4143 return true;
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(origId);
4147 }
4148 }
4149
4150 @Override
4151 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 synchronized (mGlobalLock) {
4155 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4156 "setPictureInPictureParams", token, params);
4157
4158 // Only update the saved args from the args that are set
4159 r.pictureInPictureArgs.copyOnlySet(params);
4160 if (r.inPinnedWindowingMode()) {
4161 // If the activity is already in picture-in-picture, update the pinned stack now
4162 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4163 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004164 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 if (!stack.isAnimatingBoundsToFullscreen()) {
4166 stack.setPictureInPictureAspectRatio(
4167 r.pictureInPictureArgs.getAspectRatio());
4168 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4169 }
4170 }
4171 logPictureInPictureArgs(params);
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(origId);
4175 }
4176 }
4177
4178 @Override
4179 public int getMaxNumPictureInPictureActions(IBinder token) {
4180 // Currently, this is a static constant, but later, we may change this to be dependent on
4181 // the context of the activity
4182 return 3;
4183 }
4184
4185 private void logPictureInPictureArgs(PictureInPictureParams params) {
4186 if (params.hasSetActions()) {
4187 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4188 params.getActions().size());
4189 }
4190 if (params.hasSetAspectRatio()) {
4191 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4192 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4193 MetricsLogger.action(lm);
4194 }
4195 }
4196
4197 /**
4198 * Checks the state of the system and the activity associated with the given {@param token} to
4199 * verify that picture-in-picture is supported for that activity.
4200 *
4201 * @return the activity record for the given {@param token} if all the checks pass.
4202 */
4203 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4204 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 throw new IllegalStateException(caller
4207 + ": Device doesn't support picture-in-picture mode.");
4208 }
4209
4210 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4211 if (r == null) {
4212 throw new IllegalStateException(caller
4213 + ": Can't find activity for token=" + token);
4214 }
4215
4216 if (!r.supportsPictureInPicture()) {
4217 throw new IllegalStateException(caller
4218 + ": Current activity does not support picture-in-picture.");
4219 }
4220
4221 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004222 && !mWindowManager.isValidPictureInPictureAspectRatio(
4223 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 final float minAspectRatio = mContext.getResources().getFloat(
4225 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4226 final float maxAspectRatio = mContext.getResources().getFloat(
4227 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4228 throw new IllegalArgumentException(String.format(caller
4229 + ": Aspect ratio is too extreme (must be between %f and %f).",
4230 minAspectRatio, maxAspectRatio));
4231 }
4232
4233 // Truncate the number of actions if necessary
4234 params.truncateActions(getMaxNumPictureInPictureActions(token));
4235
4236 return r;
4237 }
4238
4239 @Override
4240 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 synchronized (mGlobalLock) {
4243 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4244 if (r == null) {
4245 throw new IllegalArgumentException("Activity does not exist; token="
4246 + activityToken);
4247 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004248 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 }
4250 }
4251
4252 @Override
4253 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4254 Rect tempDockedTaskInsetBounds,
4255 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 long ident = Binder.clearCallingIdentity();
4258 try {
4259 synchronized (mGlobalLock) {
4260 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4261 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4262 PRESERVE_WINDOWS);
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(ident);
4266 }
4267 }
4268
4269 @Override
4270 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 final long ident = Binder.clearCallingIdentity();
4273 try {
4274 synchronized (mGlobalLock) {
4275 mStackSupervisor.setSplitScreenResizing(resizing);
4276 }
4277 } finally {
4278 Binder.restoreCallingIdentity(ident);
4279 }
4280 }
4281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 /**
4283 * Check that we have the features required for VR-related API calls, and throw an exception if
4284 * not.
4285 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004286 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 if (!mContext.getPackageManager().hasSystemFeature(
4288 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4289 throw new UnsupportedOperationException("VR mode not supported on this device!");
4290 }
4291 }
4292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 @Override
4294 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296
4297 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4298
4299 ActivityRecord r;
4300 synchronized (mGlobalLock) {
4301 r = ActivityRecord.isInStackLocked(token);
4302 }
4303
4304 if (r == null) {
4305 throw new IllegalArgumentException();
4306 }
4307
4308 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004309 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 VrManagerInternal.NO_ERROR) {
4311 return err;
4312 }
4313
4314 // Clear the binder calling uid since this path may call moveToTask().
4315 final long callingId = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 r.requestedVrComponent = (enabled) ? packageName : null;
4319
4320 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004321 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324 return 0;
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(callingId);
4328 }
4329 }
4330
4331 @Override
4332 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4333 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4334 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004335 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004336 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4337 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4338 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004339 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 || activity.voiceSession != null) {
4341 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4342 return;
4343 }
4344 if (activity.pendingVoiceInteractionStart) {
4345 Slog.w(TAG, "Pending start of voice interaction already.");
4346 return;
4347 }
4348 activity.pendingVoiceInteractionStart = true;
4349 }
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .startLocalVoiceInteraction(callingActivity, options);
4352 }
4353
4354 @Override
4355 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4356 LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .stopLocalVoiceInteraction(callingActivity);
4358 }
4359
4360 @Override
4361 public boolean supportsLocalVoiceInteraction() {
4362 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .supportsLocalVoiceInteraction();
4364 }
4365
4366 /** Notifies all listeners when the pinned stack animation starts. */
4367 @Override
4368 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004369 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371
4372 /** Notifies all listeners when the pinned stack animation ends. */
4373 @Override
4374 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 }
4377
4378 @Override
4379 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 final long ident = Binder.clearCallingIdentity();
4382 try {
4383 synchronized (mGlobalLock) {
4384 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4385 }
4386 } finally {
4387 Binder.restoreCallingIdentity(ident);
4388 }
4389 }
4390
4391 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394
4395 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004396 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 }
4400
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004402 final Message msg = PooledLambda.obtainMessage(
4403 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4404 DEFAULT_DISPLAY);
4405 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 }
4407
4408 final long origId = Binder.clearCallingIdentity();
4409 try {
4410 if (values != null) {
4411 Settings.System.clearConfiguration(values);
4412 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 UserHandle.USER_NULL, false /* deferResume */,
4415 mTmpUpdateConfigurationResult);
4416 return mTmpUpdateConfigurationResult.changes != 0;
4417 } finally {
4418 Binder.restoreCallingIdentity(origId);
4419 }
4420 }
4421 }
4422
4423 @Override
4424 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4425 CharSequence message) {
4426 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004427 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4429 }
4430 final long callingId = Binder.clearCallingIdentity();
4431 try {
4432 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004433 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 }
4435 } finally {
4436 Binder.restoreCallingIdentity(callingId);
4437 }
4438 }
4439
4440 @Override
4441 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 "cancelTaskWindowTransition()");
4444 final long ident = Binder.clearCallingIdentity();
4445 try {
4446 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004447 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 MATCH_TASK_IN_STACKS_ONLY);
4449 if (task == null) {
4450 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4451 return;
4452 }
4453 task.cancelWindowTransition();
4454 }
4455 } finally {
4456 Binder.restoreCallingIdentity(ident);
4457 }
4458 }
4459
4460 @Override
4461 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004462 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 final long ident = Binder.clearCallingIdentity();
4464 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004465 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 } finally {
4467 Binder.restoreCallingIdentity(ident);
4468 }
4469 }
4470
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004471 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4472 boolean restoreFromDisk) {
4473 final TaskRecord task;
4474 synchronized (mGlobalLock) {
4475 task = mRootActivityContainer.anyTaskForId(taskId,
4476 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4477 if (task == null) {
4478 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4479 return null;
4480 }
4481 }
4482 // Don't call this while holding the lock as this operation might hit the disk.
4483 return task.getSnapshot(reducedResolution, restoreFromDisk);
4484 }
4485
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 @Override
4487 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4488 synchronized (mGlobalLock) {
4489 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4490 if (r == null) {
4491 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4492 + token);
4493 return;
4494 }
4495 final long origId = Binder.clearCallingIdentity();
4496 try {
4497 r.setDisablePreviewScreenshots(disable);
4498 } finally {
4499 Binder.restoreCallingIdentity(origId);
4500 }
4501 }
4502 }
4503
4504 /** Return the user id of the last resumed activity. */
4505 @Override
4506 public @UserIdInt
4507 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4510 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004511 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004512 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004514 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
4516 }
4517
4518 @Override
4519 public void updateLockTaskFeatures(int userId, int flags) {
4520 final int callingUid = Binder.getCallingUid();
4521 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 "updateLockTaskFeatures()");
4524 }
4525 synchronized (mGlobalLock) {
4526 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4527 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004528 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 }
4530 }
4531
4532 @Override
4533 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4534 synchronized (mGlobalLock) {
4535 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4536 if (r == null) {
4537 return;
4538 }
4539 final long origId = Binder.clearCallingIdentity();
4540 try {
4541 r.setShowWhenLocked(showWhenLocked);
4542 } finally {
4543 Binder.restoreCallingIdentity(origId);
4544 }
4545 }
4546 }
4547
4548 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004549 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4550 synchronized (mGlobalLock) {
4551 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4552 if (r == null) {
4553 return;
4554 }
4555 final long origId = Binder.clearCallingIdentity();
4556 try {
4557 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4558 } finally {
4559 Binder.restoreCallingIdentity(origId);
4560 }
4561 }
4562 }
4563
4564 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4566 synchronized (mGlobalLock) {
4567 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4568 if (r == null) {
4569 return;
4570 }
4571 final long origId = Binder.clearCallingIdentity();
4572 try {
4573 r.setTurnScreenOn(turnScreenOn);
4574 } finally {
4575 Binder.restoreCallingIdentity(origId);
4576 }
4577 }
4578 }
4579
4580 @Override
4581 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 "registerRemoteAnimations");
4584 definition.setCallingPid(Binder.getCallingPid());
4585 synchronized (mGlobalLock) {
4586 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4587 if (r == null) {
4588 return;
4589 }
4590 final long origId = Binder.clearCallingIdentity();
4591 try {
4592 r.registerRemoteAnimations(definition);
4593 } finally {
4594 Binder.restoreCallingIdentity(origId);
4595 }
4596 }
4597 }
4598
4599 @Override
4600 public void registerRemoteAnimationForNextActivityStart(String packageName,
4601 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004602 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 "registerRemoteAnimationForNextActivityStart");
4604 adapter.setCallingPid(Binder.getCallingPid());
4605 synchronized (mGlobalLock) {
4606 final long origId = Binder.clearCallingIdentity();
4607 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004608 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 packageName, adapter);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
Evan Rosky966759f2019-01-15 10:33:58 -08004616 @Override
4617 public void registerRemoteAnimationsForDisplay(int displayId,
4618 RemoteAnimationDefinition definition) {
4619 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4620 "registerRemoteAnimations");
4621 definition.setCallingPid(Binder.getCallingPid());
4622 synchronized (mGlobalLock) {
4623 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4624 if (display == null) {
4625 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4626 return;
4627 }
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
4630 display.mDisplayContent.registerRemoteAnimations(definition);
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
4636
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4638 @Override
4639 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4640 synchronized (mGlobalLock) {
4641 final long origId = Binder.clearCallingIdentity();
4642 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004643 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 } finally {
4645 Binder.restoreCallingIdentity(origId);
4646 }
4647 }
4648 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004649
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 @Override
4651 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004652 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004653 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004654 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004655 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004656 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004657 }
4658 }
4659
4660 @Override
4661 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004662 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 != PERMISSION_GRANTED) {
4664 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4665 + Binder.getCallingPid()
4666 + ", uid=" + Binder.getCallingUid()
4667 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4668 Slog.w(TAG, msg);
4669 throw new SecurityException(msg);
4670 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004671 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004672 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004673 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004674 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004675 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004676 }
4677 }
4678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 @Override
4680 public void stopAppSwitches() {
4681 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4682 synchronized (mGlobalLock) {
4683 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004684 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004685 mDidAppSwitch = false;
4686 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4687 }
4688 }
4689
4690 @Override
4691 public void resumeAppSwitches() {
4692 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4693 synchronized (mGlobalLock) {
4694 // Note that we don't execute any pending app switches... we will
4695 // let those wait until either the timeout, or the next start
4696 // activity request.
4697 mAppSwitchesAllowedTime = 0;
4698 }
4699 }
4700
Ricky Wai906af482019-06-03 17:25:28 +01004701 long getLastStopAppSwitchesTime() {
4702 return mLastStopAppSwitchesTime;
4703 }
4704
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004705 void onStartActivitySetDidAppSwitch() {
4706 if (mDidAppSwitch) {
4707 // This is the second allowed switch since we stopped switches, so now just generally
4708 // allow switches. Use case:
4709 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4710 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4711 // anyone to switch again).
4712 mAppSwitchesAllowedTime = 0;
4713 } else {
4714 mDidAppSwitch = true;
4715 }
4716 }
4717
4718 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 boolean shouldDisableNonVrUiLocked() {
4720 return mVrController.shouldDisableNonVrUiLocked();
4721 }
4722
Wale Ogunwale53783742018-09-16 10:21:51 -07004723 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004725 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004727 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4728 + " to main display for VR");
4729 mRootActivityContainer.moveStackToDisplay(
4730 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 mH.post(() -> {
4733 if (!mVrController.onVrModeChanged(r)) {
4734 return;
4735 }
4736 synchronized (mGlobalLock) {
4737 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4738 mWindowManager.disableNonVrUi(disableNonVrUi);
4739 if (disableNonVrUi) {
4740 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4741 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004742 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 }
4744 }
4745 });
4746 }
4747
Wale Ogunwale53783742018-09-16 10:21:51 -07004748 @Override
4749 public int getPackageScreenCompatMode(String packageName) {
4750 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4751 synchronized (mGlobalLock) {
4752 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4753 }
4754 }
4755
4756 @Override
4757 public void setPackageScreenCompatMode(String packageName, int mode) {
4758 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4759 "setPackageScreenCompatMode");
4760 synchronized (mGlobalLock) {
4761 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4762 }
4763 }
4764
4765 @Override
4766 public boolean getPackageAskScreenCompat(String packageName) {
4767 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4768 synchronized (mGlobalLock) {
4769 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4770 }
4771 }
4772
4773 @Override
4774 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4775 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4776 "setPackageAskScreenCompat");
4777 synchronized (mGlobalLock) {
4778 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4779 }
4780 }
4781
Wale Ogunwale64258362018-10-16 15:13:37 -07004782 public static String relaunchReasonToString(int relaunchReason) {
4783 switch (relaunchReason) {
4784 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4785 return "window_resize";
4786 case RELAUNCH_REASON_FREE_RESIZE:
4787 return "free_resize";
4788 default:
4789 return null;
4790 }
4791 }
4792
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004793 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004794 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004795 }
4796
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 /** Pokes the task persister. */
4798 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4799 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4800 }
4801
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 boolean isKeyguardLocked() {
4803 return mKeyguardController.isKeyguardLocked();
4804 }
4805
Garfield Tan01548632018-11-27 10:15:48 -08004806 /**
4807 * Clears launch params for the given package.
4808 * @param packageNames the names of the packages of which the launch params are to be cleared
4809 */
4810 @Override
4811 public void clearLaunchParamsForPackages(List<String> packageNames) {
4812 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4813 "clearLaunchParamsForPackages");
4814 synchronized (mGlobalLock) {
4815 for (int i = 0; i < packageNames.size(); ++i) {
4816 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4817 }
4818 }
4819 }
4820
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004821 /**
4822 * Makes the display with the given id a single task instance display. I.e the display can only
4823 * contain one task.
4824 */
4825 @Override
4826 public void setDisplayToSingleTaskInstance(int displayId) {
4827 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4828 "setDisplayToSingleTaskInstance");
4829 final long origId = Binder.clearCallingIdentity();
4830 try {
4831 final ActivityDisplay display =
4832 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4833 if (display != null) {
4834 display.setDisplayToSingleTaskInstance();
4835 }
4836 } finally {
4837 Binder.restoreCallingIdentity(origId);
4838 }
4839 }
4840
Wale Ogunwale31913b52018-10-13 08:29:31 -07004841 void dumpLastANRLocked(PrintWriter pw) {
4842 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4843 if (mLastANRState == null) {
4844 pw.println(" <no ANR has occurred since boot>");
4845 } else {
4846 pw.println(mLastANRState);
4847 }
4848 }
4849
4850 void dumpLastANRTracesLocked(PrintWriter pw) {
4851 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4852
4853 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4854 if (ArrayUtils.isEmpty(files)) {
4855 pw.println(" <no ANR has occurred since boot>");
4856 return;
4857 }
4858 // Find the latest file.
4859 File latest = null;
4860 for (File f : files) {
4861 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4862 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004863 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004864 }
4865 pw.print("File: ");
4866 pw.print(latest.getName());
4867 pw.println();
4868 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4869 String line;
4870 while ((line = in.readLine()) != null) {
4871 pw.println(line);
4872 }
4873 } catch (IOException e) {
4874 pw.print("Unable to read: ");
4875 pw.print(e);
4876 pw.println();
4877 }
4878 }
4879
4880 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4881 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4882 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4883 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4884 }
4885
4886 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4887 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4888 pw.println(header);
4889
Wale Ogunwaled32da472018-11-16 07:19:28 -08004890 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004891 dumpPackage);
4892 boolean needSep = printedAnything;
4893
4894 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004895 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004896 " ResumedActivity: ");
4897 if (printed) {
4898 printedAnything = true;
4899 needSep = false;
4900 }
4901
4902 if (dumpPackage == null) {
4903 if (needSep) {
4904 pw.println();
4905 }
4906 printedAnything = true;
4907 mStackSupervisor.dump(pw, " ");
4908 }
4909
4910 if (!printedAnything) {
4911 pw.println(" (nothing)");
4912 }
4913 }
4914
4915 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004916 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004917 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004918 pw.println(" ");
4919 }
4920
4921 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4922 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4923 getActivityStartController().dump(pw, "", dumpPackage);
4924 }
4925
4926 /**
4927 * There are three things that cmd can be:
4928 * - a flattened component name that matches an existing activity
4929 * - the cmd arg isn't the flattened component name of an existing activity:
4930 * dump all activity whose component contains the cmd as a substring
4931 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004932 * <p>
4933 * The caller should not hold lock when calling this method because it will wait for the
4934 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 *
4936 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4937 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4938 */
4939 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4940 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4941 ArrayList<ActivityRecord> activities;
4942
4943 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004944 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004945 dumpFocusedStackOnly);
4946 }
4947
4948 if (activities.size() <= 0) {
4949 return false;
4950 }
4951
4952 String[] newArgs = new String[args.length - opti];
4953 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4954
4955 TaskRecord lastTask = null;
4956 boolean needSep = false;
4957 for (int i = activities.size() - 1; i >= 0; i--) {
4958 ActivityRecord r = activities.get(i);
4959 if (needSep) {
4960 pw.println();
4961 }
4962 needSep = true;
4963 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004964 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 if (lastTask != task) {
4966 lastTask = task;
4967 pw.print("TASK "); pw.print(lastTask.affinity);
4968 pw.print(" id="); pw.print(lastTask.taskId);
4969 pw.print(" userId="); pw.println(lastTask.userId);
4970 if (dumpAll) {
4971 lastTask.dump(pw, " ");
4972 }
4973 }
4974 }
4975 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4976 }
4977 return true;
4978 }
4979
4980 /**
4981 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4982 * there is a thread associated with the activity.
4983 */
4984 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4985 final ActivityRecord r, String[] args, boolean dumpAll) {
4986 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004987 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004988 synchronized (mGlobalLock) {
4989 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4990 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4991 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004992 if (r.hasProcess()) {
4993 pw.println(r.app.getPid());
4994 appThread = r.app.getThread();
4995 } else {
4996 pw.println("(not running)");
4997 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004998 if (dumpAll) {
4999 r.dump(pw, innerPrefix);
5000 }
5001 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005002 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 // flush anything that is already in the PrintWriter since the thread is going
5004 // to write to the file descriptor directly
5005 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005006 try (TransferPipe tp = new TransferPipe()) {
5007 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5008 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 } catch (IOException e) {
5010 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5011 } catch (RemoteException e) {
5012 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5013 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005014 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005015 }
5016
sanryhuang498e77e2018-12-06 14:57:01 +08005017 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5018 boolean testPssMode) {
5019 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5020 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5021 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005022 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005023 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5024 st.toString());
5025 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005026 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5027 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5028 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005029 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5030 testPssMode);
5031 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005032 }
5033
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005034 int getCurrentUserId() {
5035 return mAmInternal.getCurrentUserId();
5036 }
5037
5038 private void enforceNotIsolatedCaller(String caller) {
5039 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5040 throw new SecurityException("Isolated process not allowed to call " + caller);
5041 }
5042 }
5043
Wale Ogunwalef6733932018-06-27 05:14:34 -07005044 public Configuration getConfiguration() {
5045 Configuration ci;
5046 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005047 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005048 ci.userSetLocale = false;
5049 }
5050 return ci;
5051 }
5052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005053 /**
5054 * Current global configuration information. Contains general settings for the entire system,
5055 * also corresponds to the merged configuration of the default display.
5056 */
5057 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005058 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 }
5060
5061 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5062 boolean initLocale) {
5063 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5064 }
5065
5066 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5067 boolean initLocale, boolean deferResume) {
5068 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5069 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5070 UserHandle.USER_NULL, deferResume);
5071 }
5072
Wale Ogunwale59507092018-10-29 09:00:30 -07005073 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005074 final long origId = Binder.clearCallingIdentity();
5075 try {
5076 synchronized (mGlobalLock) {
5077 updateConfigurationLocked(values, null, false, true, userId,
5078 false /* deferResume */);
5079 }
5080 } finally {
5081 Binder.restoreCallingIdentity(origId);
5082 }
5083 }
5084
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005085 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5086 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5087 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5088 deferResume, null /* result */);
5089 }
5090
5091 /**
5092 * Do either or both things: (1) change the current configuration, and (2)
5093 * make sure the given activity is running with the (now) current
5094 * configuration. Returns true if the activity has been left running, or
5095 * false if <var>starting</var> is being destroyed to match the new
5096 * configuration.
5097 *
5098 * @param userId is only used when persistent parameter is set to true to persist configuration
5099 * for that particular user
5100 */
5101 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5102 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5103 ActivityTaskManagerService.UpdateConfigurationResult result) {
5104 int changes = 0;
5105 boolean kept = true;
5106
5107 if (mWindowManager != null) {
5108 mWindowManager.deferSurfaceLayout();
5109 }
5110 try {
5111 if (values != null) {
5112 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5113 deferResume);
5114 }
5115
5116 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5117 } finally {
5118 if (mWindowManager != null) {
5119 mWindowManager.continueSurfaceLayout();
5120 }
5121 }
5122
5123 if (result != null) {
5124 result.changes = changes;
5125 result.activityRelaunched = !kept;
5126 }
5127 return kept;
5128 }
5129
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005131 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005133
5134 final ActivityDisplay defaultDisplay =
5135 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 mTempConfig.setTo(getGlobalConfiguration());
5138 final int changes = mTempConfig.updateFrom(values);
5139 if (changes == 0) {
5140 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5141 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5142 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5143 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005144 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005145 return 0;
5146 }
5147
5148 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5149 "Updating global configuration to: " + values);
5150
5151 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5152 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5153 values.colorMode,
5154 values.densityDpi,
5155 values.fontScale,
5156 values.hardKeyboardHidden,
5157 values.keyboard,
5158 values.keyboardHidden,
5159 values.mcc,
5160 values.mnc,
5161 values.navigation,
5162 values.navigationHidden,
5163 values.orientation,
5164 values.screenHeightDp,
5165 values.screenLayout,
5166 values.screenWidthDp,
5167 values.smallestScreenWidthDp,
5168 values.touchscreen,
5169 values.uiMode);
5170
5171
5172 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5173 final LocaleList locales = values.getLocales();
5174 int bestLocaleIndex = 0;
5175 if (locales.size() > 1) {
5176 if (mSupportedSystemLocales == null) {
5177 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5178 }
5179 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5180 }
5181 SystemProperties.set("persist.sys.locale",
5182 locales.get(bestLocaleIndex).toLanguageTag());
5183 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005184
5185 final Message m = PooledLambda.obtainMessage(
5186 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5187 locales.get(bestLocaleIndex));
5188 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 }
5190
Yunfan Chen75157d72018-07-27 14:47:21 +09005191 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005192
5193 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005194 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195
5196 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5197 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005198 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199
5200 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005201 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202
5203 AttributeCache ac = AttributeCache.instance();
5204 if (ac != null) {
5205 ac.updateConfiguration(mTempConfig);
5206 }
5207
5208 // Make sure all resources in our process are updated right now, so that anyone who is going
5209 // to retrieve resource values after we return will be sure to get the new ones. This is
5210 // especially important during boot, where the first config change needs to guarantee all
5211 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005212 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213
5214 // We need another copy of global config because we're scheduling some calls instead of
5215 // running them in place. We need to be sure that object we send will be handled unchanged.
5216 final Configuration configCopy = new Configuration(mTempConfig);
5217 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005218 final Message msg = PooledLambda.obtainMessage(
5219 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5220 this, userId, configCopy);
5221 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 }
5223
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005224 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5225 for (int i = pidMap.size() - 1; i >= 0; i--) {
5226 final int pid = pidMap.keyAt(i);
5227 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005228 if (DEBUG_CONFIGURATION) {
5229 Slog.v(TAG_CONFIGURATION, "Update process config of "
5230 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005232 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 }
5234
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005235 final Message msg = PooledLambda.obtainMessage(
5236 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5237 mAmInternal, changes, initLocale);
5238 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 // Override configuration of the default display duplicates global config, so we need to
5241 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005242 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5243 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244
5245 return changes;
5246 }
5247
Wale Ogunwalef6733932018-06-27 05:14:34 -07005248 private void updateEventDispatchingLocked(boolean booted) {
5249 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5250 }
5251
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005252 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5253 final ContentResolver resolver = mContext.getContentResolver();
5254 Settings.System.putConfigurationForUser(resolver, config, userId);
5255 }
5256
5257 private void sendLocaleToMountDaemonMsg(Locale l) {
5258 try {
5259 IBinder service = ServiceManager.getService("mount");
5260 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5261 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5262 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5263 } catch (RemoteException e) {
5264 Log.e(TAG, "Error storing locale for decryption UI", e);
5265 }
5266 }
5267
Alison Cichowlas3e340502018-08-07 17:15:01 -04005268 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5269 mStartActivitySources.remove(permissionToken);
5270 mExpiredStartAsCallerTokens.add(permissionToken);
5271 }
5272
5273 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5274 mExpiredStartAsCallerTokens.remove(permissionToken);
5275 }
5276
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005277 boolean isActivityStartsLoggingEnabled() {
5278 return mAmInternal.isActivityStartsLoggingEnabled();
5279 }
5280
Michal Karpinski8596ded2018-11-14 14:43:48 +00005281 boolean isBackgroundActivityStartsEnabled() {
5282 return mAmInternal.isBackgroundActivityStartsEnabled();
5283 }
5284
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 void enableScreenAfterBoot(boolean booted) {
5286 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5287 SystemClock.uptimeMillis());
5288 mWindowManager.enableScreenAfterBoot();
5289
5290 synchronized (mGlobalLock) {
5291 updateEventDispatchingLocked(booted);
5292 }
5293 }
5294
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005295 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5296 if (r == null || !r.hasProcess()) {
5297 return KEY_DISPATCHING_TIMEOUT_MS;
5298 }
5299 return getInputDispatchingTimeoutLocked(r.app);
5300 }
5301
5302 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005303 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005304 }
5305
Wale Ogunwalef6733932018-06-27 05:14:34 -07005306 /**
5307 * Decide based on the configuration whether we should show the ANR,
5308 * crash, etc dialogs. The idea is that if there is no affordance to
5309 * press the on-screen buttons, or the user experience would be more
5310 * greatly impacted than the crash itself, we shouldn't show the dialog.
5311 *
5312 * A thought: SystemUI might also want to get told about this, the Power
5313 * dialog / global actions also might want different behaviors.
5314 */
5315 private void updateShouldShowDialogsLocked(Configuration config) {
5316 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5317 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5318 && config.navigation == Configuration.NAVIGATION_NONAV);
5319 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5320 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5321 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5322 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5323 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5324 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5325 HIDE_ERROR_DIALOGS, 0) != 0;
5326 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5327 }
5328
5329 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5330 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5331 FONT_SCALE, 1.0f, userId);
5332
5333 synchronized (this) {
5334 if (getGlobalConfiguration().fontScale == scaleFactor) {
5335 return;
5336 }
5337
5338 final Configuration configuration
5339 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5340 configuration.fontScale = scaleFactor;
5341 updatePersistentConfiguration(configuration, userId);
5342 }
5343 }
5344
5345 // Actually is sleeping or shutting down or whatever else in the future
5346 // is an inactive state.
5347 boolean isSleepingOrShuttingDownLocked() {
5348 return isSleepingLocked() || mShuttingDown;
5349 }
5350
5351 boolean isSleepingLocked() {
5352 return mSleeping;
5353 }
5354
Riddle Hsu16567132018-08-16 21:37:47 +08005355 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005357 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 if (task.isActivityTypeStandard()) {
5359 if (mCurAppTimeTracker != r.appTimeTracker) {
5360 // We are switching app tracking. Complete the current one.
5361 if (mCurAppTimeTracker != null) {
5362 mCurAppTimeTracker.stop();
5363 mH.obtainMessage(
5364 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005365 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005366 mCurAppTimeTracker = null;
5367 }
5368 if (r.appTimeTracker != null) {
5369 mCurAppTimeTracker = r.appTimeTracker;
5370 startTimeTrackingFocusedActivityLocked();
5371 }
5372 } else {
5373 startTimeTrackingFocusedActivityLocked();
5374 }
5375 } else {
5376 r.appTimeTracker = null;
5377 }
5378 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5379 // TODO: Probably not, because we don't want to resume voice on switching
5380 // back to this activity
5381 if (task.voiceInteractor != null) {
5382 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5383 } else {
5384 finishRunningVoiceLocked();
5385
5386 if (mLastResumedActivity != null) {
5387 final IVoiceInteractionSession session;
5388
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005389 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005390 if (lastResumedActivityTask != null
5391 && lastResumedActivityTask.voiceSession != null) {
5392 session = lastResumedActivityTask.voiceSession;
5393 } else {
5394 session = mLastResumedActivity.voiceSession;
5395 }
5396
5397 if (session != null) {
5398 // We had been in a voice interaction session, but now focused has
5399 // move to something different. Just finish the session, we can't
5400 // return to it and retain the proper state and synchronization with
5401 // the voice interaction service.
5402 finishVoiceTask(session);
5403 }
5404 }
5405 }
5406
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005407 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5408 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005409 }
5410 updateResumedAppTrace(r);
5411 mLastResumedActivity = r;
5412
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005413 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414
5415 applyUpdateLockStateLocked(r);
5416 applyUpdateVrModeLocked(r);
5417
5418 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005419 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005420 r == null ? "NULL" : r.shortComponentName,
5421 reason);
5422 }
5423
5424 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5425 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005426 final ActivityTaskManagerInternal.SleepToken token =
5427 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 updateSleepIfNeededLocked();
5429 return token;
5430 }
5431 }
5432
5433 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005434 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 final boolean wasSleeping = mSleeping;
5436 boolean updateOomAdj = false;
5437
5438 if (!shouldSleep) {
5439 // If wasSleeping is true, we need to wake up activity manager state from when
5440 // we started sleeping. In either case, we need to apply the sleep tokens, which
5441 // will wake up stacks or put them to sleep as appropriate.
5442 if (wasSleeping) {
5443 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005444 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5445 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 startTimeTrackingFocusedActivityLocked();
5447 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005448 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5450 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005451 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005452 if (wasSleeping) {
5453 updateOomAdj = true;
5454 }
5455 } else if (!mSleeping && shouldSleep) {
5456 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005457 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5458 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 if (mCurAppTimeTracker != null) {
5460 mCurAppTimeTracker.stop();
5461 }
5462 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005463 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005464 mStackSupervisor.goingToSleepLocked();
5465 updateResumedAppTrace(null /* resumed */);
5466 updateOomAdj = true;
5467 }
5468 if (updateOomAdj) {
5469 mH.post(mAmInternal::updateOomAdj);
5470 }
5471 }
5472
5473 void updateOomAdj() {
5474 mH.post(mAmInternal::updateOomAdj);
5475 }
5476
Wale Ogunwale53783742018-09-16 10:21:51 -07005477 void updateCpuStats() {
5478 mH.post(mAmInternal::updateCpuStats);
5479 }
5480
Hui Yu03d12402018-12-06 18:00:37 -08005481 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5482 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005483 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5484 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005485 mH.sendMessage(m);
5486 }
5487
Hui Yu03d12402018-12-06 18:00:37 -08005488 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005489 ComponentName taskRoot = null;
5490 final TaskRecord task = activity.getTaskRecord();
5491 if (task != null) {
5492 final ActivityRecord rootActivity = task.getRootActivity();
5493 if (rootActivity != null) {
5494 taskRoot = rootActivity.mActivityComponent;
5495 }
5496 }
5497
Hui Yu03d12402018-12-06 18:00:37 -08005498 final Message m = PooledLambda.obtainMessage(
5499 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005500 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005501 mH.sendMessage(m);
5502 }
5503
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005504 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5505 String hostingType) {
5506 try {
5507 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5508 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5509 + activity.processName);
5510 }
5511 // Post message to start process to avoid possible deadlock of calling into AMS with the
5512 // ATMS lock held.
5513 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5514 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5515 isTop, hostingType, activity.intent.getComponent());
5516 mH.sendMessage(m);
5517 } finally {
5518 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5519 }
5520 }
5521
Wale Ogunwale53783742018-09-16 10:21:51 -07005522 void setBooting(boolean booting) {
5523 mAmInternal.setBooting(booting);
5524 }
5525
5526 boolean isBooting() {
5527 return mAmInternal.isBooting();
5528 }
5529
5530 void setBooted(boolean booted) {
5531 mAmInternal.setBooted(booted);
5532 }
5533
5534 boolean isBooted() {
5535 return mAmInternal.isBooted();
5536 }
5537
5538 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5539 mH.post(() -> {
5540 if (finishBooting) {
5541 mAmInternal.finishBooting();
5542 }
5543 if (enableScreen) {
5544 mInternal.enableScreenAfterBoot(isBooted());
5545 }
5546 });
5547 }
5548
5549 void setHeavyWeightProcess(ActivityRecord root) {
5550 mHeavyWeightProcess = root.app;
5551 final Message m = PooledLambda.obtainMessage(
5552 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005553 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005554 mH.sendMessage(m);
5555 }
5556
5557 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5558 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5559 return;
5560 }
5561
5562 mHeavyWeightProcess = null;
5563 final Message m = PooledLambda.obtainMessage(
5564 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5565 proc.mUserId);
5566 mH.sendMessage(m);
5567 }
5568
5569 private void cancelHeavyWeightProcessNotification(int userId) {
5570 final INotificationManager inm = NotificationManager.getService();
5571 if (inm == null) {
5572 return;
5573 }
5574 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005575 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005576 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5577 } catch (RuntimeException e) {
5578 Slog.w(TAG, "Error canceling notification for service", e);
5579 } catch (RemoteException e) {
5580 }
5581
5582 }
5583
5584 private void postHeavyWeightProcessNotification(
5585 WindowProcessController proc, Intent intent, int userId) {
5586 if (proc == null) {
5587 return;
5588 }
5589
5590 final INotificationManager inm = NotificationManager.getService();
5591 if (inm == null) {
5592 return;
5593 }
5594
5595 try {
5596 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5597 String text = mContext.getString(R.string.heavy_weight_notification,
5598 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5599 Notification notification =
5600 new Notification.Builder(context,
5601 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5602 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5603 .setWhen(0)
5604 .setOngoing(true)
5605 .setTicker(text)
5606 .setColor(mContext.getColor(
5607 com.android.internal.R.color.system_notification_accent_color))
5608 .setContentTitle(text)
5609 .setContentText(
5610 mContext.getText(R.string.heavy_weight_notification_detail))
5611 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5612 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5613 new UserHandle(userId)))
5614 .build();
5615 try {
5616 inm.enqueueNotificationWithTag("android", "android", null,
5617 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5618 } catch (RuntimeException e) {
5619 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5620 } catch (RemoteException e) {
5621 }
5622 } catch (PackageManager.NameNotFoundException e) {
5623 Slog.w(TAG, "Unable to create context for heavy notification", e);
5624 }
5625
5626 }
5627
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005628 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5629 IBinder token, String resultWho, int requestCode, Intent[] intents,
5630 String[] resolvedTypes, int flags, Bundle bOptions) {
5631
5632 ActivityRecord activity = null;
5633 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5634 activity = ActivityRecord.isInStackLocked(token);
5635 if (activity == null) {
5636 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5637 return null;
5638 }
5639 if (activity.finishing) {
5640 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5641 return null;
5642 }
5643 }
5644
5645 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5646 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5647 bOptions);
5648 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5649 if (noCreate) {
5650 return rec;
5651 }
5652 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5653 if (activity.pendingResults == null) {
5654 activity.pendingResults = new HashSet<>();
5655 }
5656 activity.pendingResults.add(rec.ref);
5657 }
5658 return rec;
5659 }
5660
Andrii Kulian52d255c2018-07-13 11:32:19 -07005661 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005662 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005663 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005664 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5665 mCurAppTimeTracker.start(resumedActivity.packageName);
5666 }
5667 }
5668
5669 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5670 if (mTracedResumedActivity != null) {
5671 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5672 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5673 }
5674 if (resumed != null) {
5675 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5676 constructResumedTraceName(resumed.packageName), 0);
5677 }
5678 mTracedResumedActivity = resumed;
5679 }
5680
5681 private String constructResumedTraceName(String packageName) {
5682 return "focused app: " + packageName;
5683 }
5684
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005685 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005686 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005687 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005688 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005689 // mainStack is null during startup.
5690 if (mainStack != null) {
5691 if (changes != 0 && starting == null) {
5692 // If the configuration changed, and the caller is not already
5693 // in the process of starting an activity, then find the top
5694 // activity to check if its configuration needs to change.
5695 starting = mainStack.topRunningActivityLocked();
5696 }
5697
5698 if (starting != null) {
5699 kept = starting.ensureActivityConfiguration(changes,
5700 false /* preserveWindow */);
5701 // And we need to make sure at this point that all other activities
5702 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005703 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005704 !PRESERVE_WINDOWS);
5705 }
5706 }
5707
5708 return kept;
5709 }
5710
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005711 void scheduleAppGcsLocked() {
5712 mH.post(() -> mAmInternal.scheduleAppGcs());
5713 }
5714
Wale Ogunwale53783742018-09-16 10:21:51 -07005715 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5716 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5717 }
5718
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005719 /**
5720 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5721 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5722 * on demand.
5723 */
5724 IPackageManager getPackageManager() {
5725 return AppGlobals.getPackageManager();
5726 }
5727
5728 PackageManagerInternal getPackageManagerInternalLocked() {
5729 if (mPmInternal == null) {
5730 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5731 }
5732 return mPmInternal;
5733 }
5734
Hai Zhangf4da9be2019-05-01 13:46:06 +08005735 PermissionPolicyInternal getPermissionPolicyInternal() {
5736 if (mPermissionPolicyInternal == null) {
5737 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5738 }
5739 return mPermissionPolicyInternal;
5740 }
5741
Wale Ogunwale008163e2018-07-23 23:11:08 -07005742 AppWarnings getAppWarningsLocked() {
5743 return mAppWarnings;
5744 }
5745
Wale Ogunwale214f3482018-10-04 11:00:47 -07005746 Intent getHomeIntent() {
5747 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5748 intent.setComponent(mTopComponent);
5749 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5750 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5751 intent.addCategory(Intent.CATEGORY_HOME);
5752 }
5753 return intent;
5754 }
5755
Chilun2ef71f72018-11-16 17:57:15 +08005756 /**
5757 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5758 * activities.
5759 *
5760 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5761 * component defined in config_secondaryHomeComponent.
5762 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5763 */
5764 Intent getSecondaryHomeIntent(String preferredPackage) {
5765 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005766 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5767 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5768 if (preferredPackage == null || useSystemProvidedLauncher) {
5769 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005770 final String secondaryHomeComponent = mContext.getResources().getString(
5771 com.android.internal.R.string.config_secondaryHomeComponent);
5772 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5773 } else {
5774 intent.setPackage(preferredPackage);
5775 }
5776 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5777 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5778 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5779 }
5780 return intent;
5781 }
5782
Wale Ogunwale214f3482018-10-04 11:00:47 -07005783 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5784 if (info == null) return null;
5785 ApplicationInfo newInfo = new ApplicationInfo(info);
5786 newInfo.initForUser(userId);
5787 return newInfo;
5788 }
5789
Wale Ogunwale9c103022018-10-18 07:44:54 -07005790 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005791 if (uid == SYSTEM_UID) {
5792 // The system gets to run in any process. If there are multiple processes with the same
5793 // uid, just pick the first (this should never happen).
5794 final SparseArray<WindowProcessController> procs =
5795 mProcessNames.getMap().get(processName);
5796 if (procs == null) return null;
5797 final int procCount = procs.size();
5798 for (int i = 0; i < procCount; i++) {
5799 final int procUid = procs.keyAt(i);
5800 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5801 // Don't use an app process or different user process for system component.
5802 continue;
5803 }
5804 return procs.valueAt(i);
5805 }
5806 }
5807
5808 return mProcessNames.get(processName, uid);
5809 }
5810
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005811 WindowProcessController getProcessController(IApplicationThread thread) {
5812 if (thread == null) {
5813 return null;
5814 }
5815
5816 final IBinder threadBinder = thread.asBinder();
5817 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5818 for (int i = pmap.size()-1; i >= 0; i--) {
5819 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5820 for (int j = procs.size() - 1; j >= 0; j--) {
5821 final WindowProcessController proc = procs.valueAt(j);
5822 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5823 return proc;
5824 }
5825 }
5826 }
5827
5828 return null;
5829 }
5830
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005831 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005832 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005833 if (proc == null) return null;
5834 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5835 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005836 }
5837 return null;
5838 }
5839
Riddle Hsua0536432019-02-16 00:38:59 +08005840 int getUidState(int uid) {
5841 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005842 }
5843
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005844 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005845 // A uid is considered to be foreground if it has a visible non-toast window.
5846 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005847 }
5848
Ricky Wai96f5c352019-04-10 18:40:17 +01005849 boolean isDeviceOwner(int uid) {
5850 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005851 }
5852
Ricky Wai96f5c352019-04-10 18:40:17 +01005853 void setDeviceOwnerUid(int uid) {
5854 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005855 }
5856
Wale Ogunwale9de19442018-10-18 19:05:03 -07005857 /**
5858 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5859 * the whitelist
5860 */
5861 String getPendingTempWhitelistTagForUidLocked(int uid) {
5862 return mPendingTempWhitelist.get(uid);
5863 }
5864
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005865 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5866 if (true || Build.IS_USER) {
5867 return;
5868 }
5869
5870 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5871 StrictMode.allowThreadDiskWrites();
5872 try {
5873 File tracesDir = new File("/data/anr");
5874 File tracesFile = null;
5875 try {
5876 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5877
5878 StringBuilder sb = new StringBuilder();
5879 Time tobj = new Time();
5880 tobj.set(System.currentTimeMillis());
5881 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5882 sb.append(": ");
5883 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5884 sb.append(" since ");
5885 sb.append(msg);
5886 FileOutputStream fos = new FileOutputStream(tracesFile);
5887 fos.write(sb.toString().getBytes());
5888 if (app == null) {
5889 fos.write("\n*** No application process!".getBytes());
5890 }
5891 fos.close();
5892 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5893 } catch (IOException e) {
5894 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5895 return;
5896 }
5897
5898 if (app != null && app.getPid() > 0) {
5899 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5900 firstPids.add(app.getPid());
5901 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5902 }
5903
5904 File lastTracesFile = null;
5905 File curTracesFile = null;
5906 for (int i=9; i>=0; i--) {
5907 String name = String.format(Locale.US, "slow%02d.txt", i);
5908 curTracesFile = new File(tracesDir, name);
5909 if (curTracesFile.exists()) {
5910 if (lastTracesFile != null) {
5911 curTracesFile.renameTo(lastTracesFile);
5912 } else {
5913 curTracesFile.delete();
5914 }
5915 }
5916 lastTracesFile = curTracesFile;
5917 }
5918 tracesFile.renameTo(curTracesFile);
5919 } finally {
5920 StrictMode.setThreadPolicy(oldPolicy);
5921 }
5922 }
5923
Michal Karpinskida34cd42019-04-02 19:46:52 +01005924 boolean isAssociatedCompanionApp(int userId, int uid) {
5925 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5926 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005927 return false;
5928 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005929 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005930 }
5931
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005932 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005933 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005934
5935
Wale Ogunwale98875612018-10-12 07:53:02 -07005936 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5937 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005938
Riddle Hsud93a6c42018-11-29 21:50:06 +08005939 H(Looper looper) {
5940 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005941 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005942
5943 @Override
5944 public void handleMessage(Message msg) {
5945 switch (msg.what) {
5946 case REPORT_TIME_TRACKER_MSG: {
5947 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5948 tracker.deliverResult(mContext);
5949 } break;
5950 }
5951 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005952 }
5953
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005954 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005955 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005956
5957 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005958 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005959 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005960
5961 @Override
5962 public void handleMessage(Message msg) {
5963 switch (msg.what) {
5964 case DISMISS_DIALOG_UI_MSG: {
5965 final Dialog d = (Dialog) msg.obj;
5966 d.dismiss();
5967 break;
5968 }
5969 }
5970 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005971 }
5972
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 final class LocalService extends ActivityTaskManagerInternal {
5974 @Override
5975 public SleepToken acquireSleepToken(String tag, int displayId) {
5976 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005977 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005978 }
5979
5980 @Override
5981 public ComponentName getHomeActivityForUser(int userId) {
5982 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005983 final ActivityRecord homeActivity =
5984 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005985 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005986 }
5987 }
5988
5989 @Override
5990 public void onLocalVoiceInteractionStarted(IBinder activity,
5991 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5992 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005993 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005994 }
5995 }
5996
5997 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005998 public void notifyAppTransitionStarting(SparseIntArray reasons,
5999 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000 synchronized (mGlobalLock) {
6001 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6002 reasons, timestamp);
6003 }
6004 }
6005
6006 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006007 public void notifySingleTaskDisplayDrawn(int displayId) {
6008 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6009 }
6010
6011 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006012 public void notifyAppTransitionFinished() {
6013 synchronized (mGlobalLock) {
6014 mStackSupervisor.notifyAppTransitionDone();
6015 }
6016 }
6017
6018 @Override
6019 public void notifyAppTransitionCancelled() {
6020 synchronized (mGlobalLock) {
6021 mStackSupervisor.notifyAppTransitionDone();
6022 }
6023 }
6024
6025 @Override
6026 public List<IBinder> getTopVisibleActivities() {
6027 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006028 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006029 }
6030 }
6031
6032 @Override
6033 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6034 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006035 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006036 }
6037 }
6038
6039 @Override
6040 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6041 Bundle bOptions) {
6042 Preconditions.checkNotNull(intents, "intents");
6043 final String[] resolvedTypes = new String[intents.length];
6044
6045 // UID of the package on user userId.
6046 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6047 // packageUid may not be initialized.
6048 int packageUid = 0;
6049 final long ident = Binder.clearCallingIdentity();
6050
6051 try {
6052 for (int i = 0; i < intents.length; i++) {
6053 resolvedTypes[i] =
6054 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6055 }
6056
6057 packageUid = AppGlobals.getPackageManager().getPackageUid(
6058 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6059 } catch (RemoteException e) {
6060 // Shouldn't happen.
6061 } finally {
6062 Binder.restoreCallingIdentity(ident);
6063 }
6064
Riddle Hsu591bf612019-02-14 17:55:31 +08006065 return getActivityStartController().startActivitiesInPackage(
6066 packageUid, packageName,
6067 intents, resolvedTypes, null /* resultTo */,
6068 SafeActivityOptions.fromBundle(bOptions), userId,
6069 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6070 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006071 }
6072
6073 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006074 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6075 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6076 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6077 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006078 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006079 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006080 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6081 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6082 userId, validateIncomingUser, originatingPendingIntent,
6083 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006084 }
6085 }
6086
6087 @Override
6088 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6089 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6090 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6091 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006092 PendingIntentRecord originatingPendingIntent,
6093 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006094 synchronized (mGlobalLock) {
6095 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6096 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6097 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006098 validateIncomingUser, originatingPendingIntent,
6099 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006100 }
6101 }
6102
6103 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6105 Intent intent, Bundle options, int userId) {
6106 return ActivityTaskManagerService.this.startActivityAsUser(
6107 caller, callerPacakge, intent,
6108 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6109 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6110 false /*validateIncomingUser*/);
6111 }
6112
6113 @Override
lumark588a3e82018-07-20 18:53:54 +08006114 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 synchronized (mGlobalLock) {
6116
6117 // We might change the visibilities here, so prepare an empty app transition which
6118 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006119 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006120 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006121 if (activityDisplay == null) {
6122 return;
6123 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006124 final DisplayContent dc = activityDisplay.mDisplayContent;
6125 final boolean wasTransitionSet =
6126 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006128 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006130 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131
6132 // If there was a transition set already we don't want to interfere with it as we
6133 // might be starting it too early.
6134 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006135 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006136 }
6137 }
6138 if (callback != null) {
6139 callback.run();
6140 }
6141 }
6142
6143 @Override
6144 public void notifyKeyguardTrustedChanged() {
6145 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006146 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006147 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150 }
6151
6152 /**
6153 * Called after virtual display Id is updated by
6154 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6155 * {@param vrVr2dDisplayId}.
6156 */
6157 @Override
6158 public void setVr2dDisplayId(int vr2dDisplayId) {
6159 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6160 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006161 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 }
6163 }
6164
6165 @Override
6166 public void setFocusedActivity(IBinder token) {
6167 synchronized (mGlobalLock) {
6168 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6169 if (r == null) {
6170 throw new IllegalArgumentException(
6171 "setFocusedActivity: No activity record matching token=" + token);
6172 }
Louis Chang19443452018-10-09 12:10:21 +08006173 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006174 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176 }
6177 }
6178
6179 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006180 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006181 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 }
6183
6184 @Override
6185 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006186 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006187 }
6188
6189 @Override
6190 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006191 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 }
6193
6194 @Override
6195 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6196 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6197 }
6198
6199 @Override
6200 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006201 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006203
6204 @Override
6205 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6206 synchronized (mGlobalLock) {
6207 mActiveVoiceInteractionServiceComponent = component;
6208 }
6209 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006210
6211 @Override
6212 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6213 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6214 return;
6215 }
6216 synchronized (mGlobalLock) {
6217 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6218 if (types == null) {
6219 if (uid < 0) {
6220 return;
6221 }
6222 types = new ArrayMap<>();
6223 mAllowAppSwitchUids.put(userId, types);
6224 }
6225 if (uid < 0) {
6226 types.remove(type);
6227 } else {
6228 types.put(type, uid);
6229 }
6230 }
6231 }
6232
6233 @Override
6234 public void onUserStopped(int userId) {
6235 synchronized (mGlobalLock) {
6236 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6237 mAllowAppSwitchUids.remove(userId);
6238 }
6239 }
6240
6241 @Override
6242 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6243 synchronized (mGlobalLock) {
6244 return ActivityTaskManagerService.this.isGetTasksAllowed(
6245 caller, callingPid, callingUid);
6246 }
6247 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006248
Riddle Hsua0536432019-02-16 00:38:59 +08006249 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006250 @Override
6251 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006252 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006253 mProcessNames.put(proc.mName, proc.mUid, proc);
6254 }
6255 }
6256
Riddle Hsua0536432019-02-16 00:38:59 +08006257 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006258 @Override
6259 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006260 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006261 mProcessNames.remove(name, uid);
6262 }
6263 }
6264
Riddle Hsua0536432019-02-16 00:38:59 +08006265 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006266 @Override
6267 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006268 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006269 if (proc == mHomeProcess) {
6270 mHomeProcess = null;
6271 }
6272 if (proc == mPreviousProcess) {
6273 mPreviousProcess = null;
6274 }
6275 }
6276 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006277
Riddle Hsua0536432019-02-16 00:38:59 +08006278 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006279 @Override
6280 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006281 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006282 return mTopProcessState;
6283 }
6284 }
6285
Riddle Hsua0536432019-02-16 00:38:59 +08006286 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006287 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006288 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006289 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006290 return proc == mHeavyWeightProcess;
6291 }
6292 }
6293
Riddle Hsua0536432019-02-16 00:38:59 +08006294 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006295 @Override
6296 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006298 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6299 }
6300 }
6301
6302 @Override
6303 public void finishHeavyWeightApp() {
6304 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006305 if (mHeavyWeightProcess != null) {
6306 mHeavyWeightProcess.finishActivities();
6307 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006308 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6309 mHeavyWeightProcess);
6310 }
6311 }
6312
Riddle Hsua0536432019-02-16 00:38:59 +08006313 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006315 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006316 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006317 return isSleepingLocked();
6318 }
6319 }
6320
6321 @Override
6322 public boolean isShuttingDown() {
6323 synchronized (mGlobalLock) {
6324 return mShuttingDown;
6325 }
6326 }
6327
6328 @Override
6329 public boolean shuttingDown(boolean booted, int timeout) {
6330 synchronized (mGlobalLock) {
6331 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006332 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006333 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006334 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006335 return mStackSupervisor.shutdownLocked(timeout);
6336 }
6337 }
6338
6339 @Override
6340 public void enableScreenAfterBoot(boolean booted) {
6341 synchronized (mGlobalLock) {
6342 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6343 SystemClock.uptimeMillis());
6344 mWindowManager.enableScreenAfterBoot();
6345 updateEventDispatchingLocked(booted);
6346 }
6347 }
6348
6349 @Override
6350 public boolean showStrictModeViolationDialog() {
6351 synchronized (mGlobalLock) {
6352 return mShowDialogs && !mSleeping && !mShuttingDown;
6353 }
6354 }
6355
6356 @Override
6357 public void showSystemReadyErrorDialogsIfNeeded() {
6358 synchronized (mGlobalLock) {
6359 try {
6360 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6361 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6362 + " data partition or your device will be unstable.");
6363 mUiHandler.post(() -> {
6364 if (mShowDialogs) {
6365 AlertDialog d = new BaseErrorDialog(mUiContext);
6366 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6367 d.setCancelable(false);
6368 d.setTitle(mUiContext.getText(R.string.android_system_label));
6369 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6370 d.setButton(DialogInterface.BUTTON_POSITIVE,
6371 mUiContext.getText(R.string.ok),
6372 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6373 d.show();
6374 }
6375 });
6376 }
6377 } catch (RemoteException e) {
6378 }
6379
6380 if (!Build.isBuildConsistent()) {
6381 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6382 mUiHandler.post(() -> {
6383 if (mShowDialogs) {
6384 AlertDialog d = new BaseErrorDialog(mUiContext);
6385 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6386 d.setCancelable(false);
6387 d.setTitle(mUiContext.getText(R.string.android_system_label));
6388 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6389 d.setButton(DialogInterface.BUTTON_POSITIVE,
6390 mUiContext.getText(R.string.ok),
6391 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6392 d.show();
6393 }
6394 });
6395 }
6396 }
6397 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006398
6399 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006400 public void onProcessMapped(int pid, WindowProcessController proc) {
6401 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006402 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006403 }
6404 }
6405
6406 @Override
6407 public void onProcessUnMapped(int pid) {
6408 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006409 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006410 }
6411 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006412
6413 @Override
6414 public void onPackageDataCleared(String name) {
6415 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006416 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006417 mAppWarnings.onPackageDataCleared(name);
6418 }
6419 }
6420
6421 @Override
6422 public void onPackageUninstalled(String name) {
6423 synchronized (mGlobalLock) {
6424 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006425 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006426 }
6427 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006428
6429 @Override
6430 public void onPackageAdded(String name, boolean replacing) {
6431 synchronized (mGlobalLock) {
6432 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6433 }
6434 }
6435
6436 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006437 public void onPackageReplaced(ApplicationInfo aInfo) {
6438 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006439 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006440 }
6441 }
6442
6443 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006444 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6445 synchronized (mGlobalLock) {
6446 return compatibilityInfoForPackageLocked(ai);
6447 }
6448 }
6449
Yunfan Chen75157d72018-07-27 14:47:21 +09006450 /**
6451 * Set the corresponding display information for the process global configuration. To be
6452 * called when we need to show IME on a different display.
6453 *
6454 * @param pid The process id associated with the IME window.
6455 * @param displayId The ID of the display showing the IME.
6456 */
6457 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006458 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006459 // Don't update process-level configuration for Multi-Client IME process since other
6460 // IMEs on other displays will also receive this configuration change due to IME
6461 // services use the same application config/context.
6462 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006463
Yunfan Chen75157d72018-07-27 14:47:21 +09006464 if (pid == MY_PID || pid < 0) {
6465 if (DEBUG_CONFIGURATION) {
6466 Slog.w(TAG,
6467 "Trying to update display configuration for system/invalid process.");
6468 }
6469 return;
6470 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006471 synchronized (mGlobalLock) {
6472 final ActivityDisplay activityDisplay =
6473 mRootActivityContainer.getActivityDisplay(displayId);
6474 if (activityDisplay == null) {
6475 // Call might come when display is not yet added or has been removed.
6476 if (DEBUG_CONFIGURATION) {
6477 Slog.w(TAG, "Trying to update display configuration for non-existing "
6478 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006479 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006480 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006481 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006482 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006483 if (process == null) {
6484 if (DEBUG_CONFIGURATION) {
6485 Slog.w(TAG, "Trying to update display configuration for invalid "
6486 + "process, pid=" + pid);
6487 }
6488 return;
6489 }
6490 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6491 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006492 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006493
6494 @Override
6495 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006496 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006497 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006498 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6499 if (r != null && r.getActivityStack() != null) {
6500 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6501 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006502 }
6503 }
6504 }
6505
6506 @Override
6507 public void clearPendingResultForActivity(IBinder activityToken,
6508 WeakReference<PendingIntentRecord> pir) {
6509 synchronized (mGlobalLock) {
6510 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6511 if (r != null && r.pendingResults != null) {
6512 r.pendingResults.remove(pir);
6513 }
6514 }
6515 }
6516
6517 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006518 public ActivityTokens getTopActivityForTask(int taskId) {
6519 synchronized (mGlobalLock) {
6520 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6521 if (taskRecord == null) {
6522 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6523 + " Requested task not found");
6524 return null;
6525 }
6526 final ActivityRecord activity = taskRecord.getTopActivity();
6527 if (activity == null) {
6528 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6529 + " Requested activity not found");
6530 return null;
6531 }
6532 if (!activity.attachedToProcess()) {
6533 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6534 + activity);
6535 return null;
6536 }
6537 return new ActivityTokens(activity.appToken, activity.assistToken,
6538 activity.app.getThread());
6539 }
6540 }
6541
6542 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006543 public IIntentSender getIntentSender(int type, String packageName,
6544 int callingUid, int userId, IBinder token, String resultWho,
6545 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6546 Bundle bOptions) {
6547 synchronized (mGlobalLock) {
6548 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6549 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6550 }
6551 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006552
6553 @Override
6554 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6555 synchronized (mGlobalLock) {
6556 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6557 if (r == null) {
6558 return null;
6559 }
6560 if (r.mServiceConnectionsHolder == null) {
6561 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6562 ActivityTaskManagerService.this, r);
6563 }
6564
6565 return r.mServiceConnectionsHolder;
6566 }
6567 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006568
6569 @Override
6570 public Intent getHomeIntent() {
6571 synchronized (mGlobalLock) {
6572 return ActivityTaskManagerService.this.getHomeIntent();
6573 }
6574 }
6575
6576 @Override
6577 public boolean startHomeActivity(int userId, String reason) {
6578 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006579 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006580 }
6581 }
6582
6583 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006584 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006585 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006586 synchronized (mGlobalLock) {
6587 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006588 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006589 }
Chilun8b1f1be2019-03-13 17:14:36 +08006590 }
6591
6592 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006593 public boolean startHomeOnAllDisplays(int userId, String reason) {
6594 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006595 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006596 }
6597 }
6598
Riddle Hsua0536432019-02-16 00:38:59 +08006599 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006600 @Override
6601 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006602 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006603 if (mFactoryTest == FACTORY_TEST_OFF) {
6604 return false;
6605 }
6606 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6607 && wpc.mName.equals(mTopComponent.getPackageName())) {
6608 return true;
6609 }
6610 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6611 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6612 }
6613 }
6614
6615 @Override
6616 public void updateTopComponentForFactoryTest() {
6617 synchronized (mGlobalLock) {
6618 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6619 return;
6620 }
6621 final ResolveInfo ri = mContext.getPackageManager()
6622 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6623 final CharSequence errorMsg;
6624 if (ri != null) {
6625 final ActivityInfo ai = ri.activityInfo;
6626 final ApplicationInfo app = ai.applicationInfo;
6627 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6628 mTopAction = Intent.ACTION_FACTORY_TEST;
6629 mTopData = null;
6630 mTopComponent = new ComponentName(app.packageName, ai.name);
6631 errorMsg = null;
6632 } else {
6633 errorMsg = mContext.getResources().getText(
6634 com.android.internal.R.string.factorytest_not_system);
6635 }
6636 } else {
6637 errorMsg = mContext.getResources().getText(
6638 com.android.internal.R.string.factorytest_no_action);
6639 }
6640 if (errorMsg == null) {
6641 return;
6642 }
6643
6644 mTopAction = null;
6645 mTopData = null;
6646 mTopComponent = null;
6647 mUiHandler.post(() -> {
6648 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6649 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006650 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006651 });
6652 }
6653 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654
Riddle Hsua0536432019-02-16 00:38:59 +08006655 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006656 @Override
6657 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6658 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006659 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006661 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006662
6663 wpc.clearRecentTasks();
6664 wpc.clearActivities();
6665
6666 if (wpc.isInstrumenting()) {
6667 finishInstrumentationCallback.run();
6668 }
6669
Jorim Jaggid0752812018-10-16 16:07:20 +02006670 if (!restarting && hasVisibleActivities) {
6671 mWindowManager.deferSurfaceLayout();
6672 try {
6673 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6674 // If there was nothing to resume, and we are not already restarting
6675 // this process, but there is a visible activity that is hosted by the
6676 // process...then make sure all visible activities are running, taking
6677 // care of restarting this process.
6678 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6679 !PRESERVE_WINDOWS);
6680 }
6681 } finally {
6682 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006684 }
6685 }
6686 }
6687
6688 @Override
6689 public void closeSystemDialogs(String reason) {
6690 enforceNotIsolatedCaller("closeSystemDialogs");
6691
6692 final int pid = Binder.getCallingPid();
6693 final int uid = Binder.getCallingUid();
6694 final long origId = Binder.clearCallingIdentity();
6695 try {
6696 synchronized (mGlobalLock) {
6697 // Only allow this from foreground processes, so that background
6698 // applications can't abuse it to prevent system UI from being shown.
6699 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006700 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 if (!proc.isPerceptible()) {
6702 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6703 + " from background process " + proc);
6704 return;
6705 }
6706 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 mWindowManager.closeSystemDialogs(reason);
6708
Wale Ogunwaled32da472018-11-16 07:19:28 -08006709 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006710 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006711 // Call into AM outside the synchronized block.
6712 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 } finally {
6714 Binder.restoreCallingIdentity(origId);
6715 }
6716 }
6717
6718 @Override
6719 public void cleanupDisabledPackageComponents(
6720 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6721 synchronized (mGlobalLock) {
6722 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006723 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006724 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006725 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006726 mStackSupervisor.scheduleIdleLocked();
6727 }
6728
6729 // Clean-up disabled tasks
6730 getRecentTasks().cleanupDisabledPackageTasksLocked(
6731 packageName, disabledClasses, userId);
6732 }
6733 }
6734
6735 @Override
6736 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6737 int userId) {
6738 synchronized (mGlobalLock) {
6739
6740 boolean didSomething =
6741 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006742 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 null, doit, evenPersistent, userId);
6744 return didSomething;
6745 }
6746 }
6747
6748 @Override
6749 public void resumeTopActivities(boolean scheduleIdle) {
6750 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006751 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 if (scheduleIdle) {
6753 mStackSupervisor.scheduleIdleLocked();
6754 }
6755 }
6756 }
6757
Riddle Hsua0536432019-02-16 00:38:59 +08006758 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 @Override
6760 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006761 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006762 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6763 }
6764 }
6765
Riddle Hsua0536432019-02-16 00:38:59 +08006766 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 @Override
6768 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006769 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 }
6772 }
6773
6774 @Override
6775 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6776 try {
6777 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6778 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6779 }
6780 } catch (RemoteException ex) {
6781 throw new SecurityException("Fail to check is caller a privileged app", ex);
6782 }
6783
6784 synchronized (mGlobalLock) {
6785 final long ident = Binder.clearCallingIdentity();
6786 try {
6787 if (mAmInternal.shouldConfirmCredentials(userId)) {
6788 if (mKeyguardController.isKeyguardLocked()) {
6789 // Showing launcher to avoid user entering credential twice.
6790 startHomeActivity(currentUserId, "notifyLockedProfile");
6791 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006792 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 }
6794 } finally {
6795 Binder.restoreCallingIdentity(ident);
6796 }
6797 }
6798 }
6799
6800 @Override
6801 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6802 mAmInternal.enforceCallingPermission(
6803 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6804
6805 synchronized (mGlobalLock) {
6806 final long ident = Binder.clearCallingIdentity();
6807 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006808 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6809 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006811 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6812 UserHandle.CURRENT);
6813 } finally {
6814 Binder.restoreCallingIdentity(ident);
6815 }
6816 }
6817 }
6818
6819 @Override
6820 public void writeActivitiesToProto(ProtoOutputStream proto) {
6821 synchronized (mGlobalLock) {
6822 // The output proto of "activity --proto activities"
6823 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006824 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006825 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6826 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 }
6828 }
6829
6830 @Override
6831 public void saveANRState(String reason) {
6832 synchronized (mGlobalLock) {
6833 final StringWriter sw = new StringWriter();
6834 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6835 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6836 if (reason != null) {
6837 pw.println(" Reason: " + reason);
6838 }
6839 pw.println();
6840 getActivityStartController().dump(pw, " ", null);
6841 pw.println();
6842 pw.println("-------------------------------------------------------------------------------");
6843 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6844 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6845 "" /* header */);
6846 pw.println();
6847 pw.close();
6848
6849 mLastANRState = sw.toString();
6850 }
6851 }
6852
6853 @Override
6854 public void clearSavedANRState() {
6855 synchronized (mGlobalLock) {
6856 mLastANRState = null;
6857 }
6858 }
6859
6860 @Override
6861 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6862 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6863 synchronized (mGlobalLock) {
6864 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6865 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6866 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6867 dumpLastANRLocked(pw);
6868 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6869 dumpLastANRTracesLocked(pw);
6870 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6871 dumpActivityStarterLocked(pw, dumpPackage);
6872 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6873 dumpActivityContainersLocked(pw);
6874 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6875 if (getRecentTasks() != null) {
6876 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6877 }
6878 }
6879 }
6880 }
6881
6882 @Override
6883 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6884 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6885 int wakefulness) {
6886 synchronized (mGlobalLock) {
6887 if (mHomeProcess != null && (dumpPackage == null
6888 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6889 if (needSep) {
6890 pw.println();
6891 needSep = false;
6892 }
6893 pw.println(" mHomeProcess: " + mHomeProcess);
6894 }
6895 if (mPreviousProcess != null && (dumpPackage == null
6896 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6897 if (needSep) {
6898 pw.println();
6899 needSep = false;
6900 }
6901 pw.println(" mPreviousProcess: " + mPreviousProcess);
6902 }
6903 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6904 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6905 StringBuilder sb = new StringBuilder(128);
6906 sb.append(" mPreviousProcessVisibleTime: ");
6907 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6908 pw.println(sb);
6909 }
6910 if (mHeavyWeightProcess != null && (dumpPackage == null
6911 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6912 if (needSep) {
6913 pw.println();
6914 needSep = false;
6915 }
6916 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6917 }
6918 if (dumpPackage == null) {
6919 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006920 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 }
6922 if (dumpAll) {
6923 if (dumpPackage == null) {
6924 pw.println(" mConfigWillChange: "
6925 + getTopDisplayFocusedStack().mConfigWillChange);
6926 }
6927 if (mCompatModePackages.getPackages().size() > 0) {
6928 boolean printed = false;
6929 for (Map.Entry<String, Integer> entry
6930 : mCompatModePackages.getPackages().entrySet()) {
6931 String pkg = entry.getKey();
6932 int mode = entry.getValue();
6933 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6934 continue;
6935 }
6936 if (!printed) {
6937 pw.println(" mScreenCompatPackages:");
6938 printed = true;
6939 }
6940 pw.println(" " + pkg + ": " + mode);
6941 }
6942 }
6943 }
6944
6945 if (dumpPackage == null) {
6946 pw.println(" mWakefulness="
6947 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006948 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006949 if (mRunningVoice != null) {
6950 pw.println(" mRunningVoice=" + mRunningVoice);
6951 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6952 }
6953 pw.println(" mSleeping=" + mSleeping);
6954 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6955 pw.println(" mVrController=" + mVrController);
6956 }
6957 if (mCurAppTimeTracker != null) {
6958 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6959 }
6960 if (mAllowAppSwitchUids.size() > 0) {
6961 boolean printed = false;
6962 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6963 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6964 for (int j = 0; j < types.size(); j++) {
6965 if (dumpPackage == null ||
6966 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6967 if (needSep) {
6968 pw.println();
6969 needSep = false;
6970 }
6971 if (!printed) {
6972 pw.println(" mAllowAppSwitchUids:");
6973 printed = true;
6974 }
6975 pw.print(" User ");
6976 pw.print(mAllowAppSwitchUids.keyAt(i));
6977 pw.print(": Type ");
6978 pw.print(types.keyAt(j));
6979 pw.print(" = ");
6980 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6981 pw.println();
6982 }
6983 }
6984 }
6985 }
6986 if (dumpPackage == null) {
6987 if (mController != null) {
6988 pw.println(" mController=" + mController
6989 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6990 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006991 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6992 pw.println(" mLaunchingActivityWakeLock="
6993 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 }
6995
6996 return needSep;
6997 }
6998 }
6999
7000 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007001 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7002 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007003 synchronized (mGlobalLock) {
7004 if (dumpPackage == null) {
7005 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7006 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007007 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7008 if (mRunningVoice != null) {
7009 final long vrToken = proto.start(
7010 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7011 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7012 mRunningVoice.toString());
7013 mVoiceWakeLock.writeToProto(
7014 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7015 proto.end(vrToken);
7016 }
7017 mVrController.writeToProto(proto,
7018 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007019 if (mController != null) {
7020 final long token = proto.start(CONTROLLER);
7021 proto.write(CONTROLLER, mController.toString());
7022 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7023 proto.end(token);
7024 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007025 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7026 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7027 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007028 }
7029
7030 if (mHomeProcess != null && (dumpPackage == null
7031 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007032 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034
7035 if (mPreviousProcess != null && (dumpPackage == null
7036 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007037 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7039 }
7040
7041 if (mHeavyWeightProcess != null && (dumpPackage == null
7042 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007043 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 }
7045
7046 for (Map.Entry<String, Integer> entry
7047 : mCompatModePackages.getPackages().entrySet()) {
7048 String pkg = entry.getKey();
7049 int mode = entry.getValue();
7050 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7051 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7052 proto.write(PACKAGE, pkg);
7053 proto.write(MODE, mode);
7054 proto.end(compatToken);
7055 }
7056 }
7057
7058 if (mCurAppTimeTracker != null) {
7059 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7060 }
7061
7062 }
7063 }
7064
7065 @Override
7066 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7067 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7068 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007069 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7070 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007071 }
7072
7073 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007074 public void dumpForOom(PrintWriter pw) {
7075 synchronized (mGlobalLock) {
7076 pw.println(" mHomeProcess: " + mHomeProcess);
7077 pw.println(" mPreviousProcess: " + mPreviousProcess);
7078 if (mHeavyWeightProcess != null) {
7079 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7080 }
7081 }
7082 }
7083
7084 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007085 public boolean canGcNow() {
7086 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007087 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 }
7089 }
7090
Riddle Hsua0536432019-02-16 00:38:59 +08007091 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 @Override
7093 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007094 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007095 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007096 return top != null ? top.app : null;
7097 }
7098 }
7099
Riddle Hsua0536432019-02-16 00:38:59 +08007100 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 @Override
7102 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007103 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007104 if (mRootActivityContainer != null) {
7105 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 }
7107 }
7108 }
7109
7110 @Override
7111 public void scheduleDestroyAllActivities(String reason) {
7112 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007113 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 }
7115 }
7116
7117 @Override
7118 public void removeUser(int userId) {
7119 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007120 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122 }
7123
7124 @Override
7125 public boolean switchUser(int userId, UserState userState) {
7126 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007127 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007128 }
7129 }
7130
7131 @Override
7132 public void onHandleAppCrash(WindowProcessController wpc) {
7133 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007134 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 }
7136 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007137
7138 @Override
7139 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7140 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007141 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007142 }
7143 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007144
Riddle Hsua0536432019-02-16 00:38:59 +08007145 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007146 @Override
7147 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007148 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007149 }
7150
Riddle Hsua0536432019-02-16 00:38:59 +08007151 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152 @Override
7153 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007154 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007155 }
7156
Riddle Hsua0536432019-02-16 00:38:59 +08007157 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007158 @Override
7159 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007160 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007161 }
7162
Riddle Hsua0536432019-02-16 00:38:59 +08007163 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007164 @Override
7165 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007166 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007167 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007168
7169 @Override
7170 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007171 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007172 mPendingTempWhitelist.put(uid, tag);
7173 }
7174 }
7175
7176 @Override
7177 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007178 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007179 mPendingTempWhitelist.remove(uid);
7180 }
7181 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007182
7183 @Override
7184 public boolean handleAppCrashInActivityController(String processName, int pid,
7185 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7186 Runnable killCrashingAppCallback) {
7187 synchronized (mGlobalLock) {
7188 if (mController == null) {
7189 return false;
7190 }
7191
7192 try {
7193 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7194 stackTrace)) {
7195 killCrashingAppCallback.run();
7196 return true;
7197 }
7198 } catch (RemoteException e) {
7199 mController = null;
7200 Watchdog.getInstance().setActivityController(null);
7201 }
7202 return false;
7203 }
7204 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007205
7206 @Override
7207 public void removeRecentTasksByPackageName(String packageName, int userId) {
7208 synchronized (mGlobalLock) {
7209 mRecentTasks.removeTasksByPackageName(packageName, userId);
7210 }
7211 }
7212
7213 @Override
7214 public void cleanupRecentTasksForUser(int userId) {
7215 synchronized (mGlobalLock) {
7216 mRecentTasks.cleanupLocked(userId);
7217 }
7218 }
7219
7220 @Override
7221 public void loadRecentTasksForUser(int userId) {
7222 synchronized (mGlobalLock) {
7223 mRecentTasks.loadUserRecentsLocked(userId);
7224 }
7225 }
7226
7227 @Override
7228 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7229 synchronized (mGlobalLock) {
7230 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7231 }
7232 }
7233
7234 @Override
7235 public void flushRecentTasks() {
7236 mRecentTasks.flush();
7237 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007238
7239 @Override
7240 public WindowProcessController getHomeProcess() {
7241 synchronized (mGlobalLock) {
7242 return mHomeProcess;
7243 }
7244 }
7245
7246 @Override
7247 public WindowProcessController getPreviousProcess() {
7248 synchronized (mGlobalLock) {
7249 return mPreviousProcess;
7250 }
7251 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007252
7253 @Override
7254 public void clearLockedTasks(String reason) {
7255 synchronized (mGlobalLock) {
7256 getLockTaskController().clearLockedTasks(reason);
7257 }
7258 }
7259
7260 @Override
7261 public void updateUserConfiguration() {
7262 synchronized (mGlobalLock) {
7263 final Configuration configuration = new Configuration(getGlobalConfiguration());
7264 final int currentUserId = mAmInternal.getCurrentUserId();
7265 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7266 configuration, currentUserId, Settings.System.canWrite(mContext));
7267 updateConfigurationLocked(configuration, null /* starting */,
7268 false /* initLocale */, false /* persistent */, currentUserId,
7269 false /* deferResume */);
7270 }
7271 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007272
7273 @Override
7274 public boolean canShowErrorDialogs() {
7275 synchronized (mGlobalLock) {
7276 return mShowDialogs && !mSleeping && !mShuttingDown
7277 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7278 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7279 mAmInternal.getCurrentUserId())
7280 && !(UserManager.isDeviceInDemoMode(mContext)
7281 && mAmInternal.getCurrentUser().isDemo());
7282 }
7283 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007284
7285 @Override
7286 public void setProfileApp(String profileApp) {
7287 synchronized (mGlobalLock) {
7288 mProfileApp = profileApp;
7289 }
7290 }
7291
7292 @Override
7293 public void setProfileProc(WindowProcessController wpc) {
7294 synchronized (mGlobalLock) {
7295 mProfileProc = wpc;
7296 }
7297 }
7298
7299 @Override
7300 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7301 synchronized (mGlobalLock) {
7302 mProfilerInfo = profilerInfo;
7303 }
7304 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007305
7306 @Override
7307 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7308 synchronized (mGlobalLock) {
7309 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7310 }
7311 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007312
7313 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007314 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7315 boolean reducedResolution) {
7316 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7317 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007318 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007319
7320 @Override
7321 public boolean isUidForeground(int uid) {
7322 synchronized (mGlobalLock) {
7323 return ActivityTaskManagerService.this.isUidForeground(uid);
7324 }
7325 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007326
7327 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007328 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007329 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007330 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007331 }
7332 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007333
7334 @Override
7335 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007336 // Translate package names into UIDs
7337 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007338 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007339 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7340 if (uid >= 0) {
7341 result.add(uid);
7342 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007343 }
7344 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007345 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007346 }
7347 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007348 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007349}