blob: f661ac0d48002d91b000951e3e13fb248c78d581 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314
Wale Ogunwale98875612018-10-12 07:53:02 -0700315 /** Used to indicate that an app transition should be animated. */
316 static final boolean ANIMATE = true;
317
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700318 /** Hardware-reported OpenGLES version. */
319 final int GL_ES_VERSION;
320
Wale Ogunwale31913b52018-10-13 08:29:31 -0700321 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
322 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
323 public static final String DUMP_LASTANR_CMD = "lastanr" ;
324 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
325 public static final String DUMP_STARTER_CMD = "starter" ;
326 public static final String DUMP_CONTAINERS_CMD = "containers" ;
327 public static final String DUMP_RECENTS_CMD = "recents" ;
328 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
329
Wale Ogunwale64258362018-10-16 15:13:37 -0700330 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
331 public static final int RELAUNCH_REASON_NONE = 0;
332 /** This activity is being relaunched due to windowing mode change. */
333 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
334 /** This activity is being relaunched due to a free-resize operation. */
335 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
336
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700337 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700338
Wale Ogunwalef6733932018-06-27 05:14:34 -0700339 /**
340 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
341 * change at runtime. Use mContext for non-UI purposes.
342 */
343 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700345 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700348 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700349 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800350 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800351 @VisibleForTesting
352 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 PowerManagerInternal mPowerManagerInternal;
354 private UsageStatsManagerInternal mUsageStatsInternal;
355
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700356 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 IntentFirewall mIntentFirewall;
358
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700359 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800360 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800361 /**
362 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
363 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
364 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
365 *
366 * @see WindowManagerThreadPriorityBooster
367 */
368 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700369 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800370 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700371 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700372 private UserManagerService mUserManager;
373 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700374 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800375 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700376 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /** All processes currently running that might have a window organized by name. */
378 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100379 /** All processes we currently have running mapped by pid and uid */
380 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** This is the process holding what we currently consider to be the "home" activity. */
382 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700383 /** The currently running heavy-weight process, if any. */
384 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700385 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /**
387 * This is the process holding the activity the user last visited that is in a different process
388 * from the one they are currently in.
389 */
390 WindowProcessController mPreviousProcess;
391 /** The time at which the previous process was last visible. */
392 long mPreviousProcessVisibleTime;
393
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700394 /** List of intents that were used to start the most recent tasks. */
395 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700396 /** State of external calls telling us if the device is awake or asleep. */
397 private boolean mKeyguardShown = false;
398
399 // Wrapper around VoiceInteractionServiceManager
400 private AssistUtils mAssistUtils;
401
402 // VoiceInteraction session ID that changes for each new request except when
403 // being called for multi-window assist in a single session.
404 private int mViSessionId = 1000;
405
406 // How long to wait in getAssistContextExtras for the activity and foreground services
407 // to respond with the result.
408 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
409
410 // How long top wait when going through the modern assist (which doesn't need to block
411 // on getting this result before starting to launch its UI).
412 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
413
414 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
415 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
416
Alison Cichowlas3e340502018-08-07 17:15:01 -0400417 // Permission tokens are used to temporarily granted a trusted app the ability to call
418 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
419 // showing any appropriate error messages to the user.
420 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
421 10 * MINUTE_IN_MILLIS;
422
423 // How long before the service actually expires a token. This is slightly longer than
424 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
425 // expiration exception.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
427 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
428
429 // How long the service will remember expired tokens, for the purpose of providing error
430 // messaging when a client uses an expired token.
431 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
432 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
433
Marvin Ramin830d4e32019-03-12 13:16:58 +0100434 // How long to whitelist the Services for when requested.
435 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
436
Alison Cichowlas3e340502018-08-07 17:15:01 -0400437 // Activity tokens of system activities that are delegating their call to
438 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
439 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
440
441 // Permission tokens that have expired, but we remember for error reporting.
442 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
443
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700444 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
445
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700446 // Keeps track of the active voice interaction service component, notified from
447 // VoiceInteractionManagerService
448 ComponentName mActiveVoiceInteractionServiceComponent;
449
Michal Karpinskida34cd42019-04-02 19:46:52 +0100450 // A map userId and all its companion app uids
451 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000452
Wale Ogunwalee2172292018-10-25 10:11:10 -0700453 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 KeyguardController mKeyguardController;
455 private final ClientLifecycleManager mLifecycleManager;
456 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700457 /** The controller for all operations related to locktask. */
458 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700459 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700461 boolean mSuppressResizeConfigChanges;
462
463 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
464 new UpdateConfigurationResult();
465
466 static final class UpdateConfigurationResult {
467 // Configuration changes that were updated.
468 int changes;
469 // If the activity was relaunched to match the new configuration.
470 boolean activityRelaunched;
471
472 void reset() {
473 changes = 0;
474 activityRelaunched = false;
475 }
476 }
477
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 private int mConfigurationSeq;
480 // To cache the list of supported system locales
481 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482
483 /**
484 * Temp object used when global and/or display override configuration is updated. It is also
485 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
486 * anyone...
487 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private Configuration mTempConfig = new Configuration();
489
Wale Ogunwalef6733932018-06-27 05:14:34 -0700490 /** Temporary to avoid allocations. */
491 final StringBuilder mStringBuilder = new StringBuilder(256);
492
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 // Amount of time after a call to stopAppSwitches() during which we will
494 // prevent further untrusted switches from happening.
495 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
496
497 /**
498 * The time at which we will allow normal application switches again,
499 * after a call to {@link #stopAppSwitches()}.
500 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
503 * This is set to true after the first switch after mAppSwitchesAllowedTime
504 * is set; any switches after that will clear the time.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507
508 IActivityController mController = null;
509 boolean mControllerIsAMonkey = false;
510
Wale Ogunwale214f3482018-10-04 11:00:47 -0700511 final int mFactoryTest;
512
513 /** Used to control how we initialize the service. */
514 ComponentName mTopComponent;
515 String mTopAction = Intent.ACTION_MAIN;
516 String mTopData;
517
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800518 /** Profiling app information. */
519 String mProfileApp = null;
520 WindowProcessController mProfileProc = null;
521 ProfilerInfo mProfilerInfo = null;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700524 * Dump of the activity state at the time of the last ANR. Cleared after
525 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
526 */
527 String mLastANRState;
528
529 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 * Used to retain an update lock when the foreground activity is in
531 * immersive mode.
532 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700533 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534
535 /**
536 * Packages that are being allowed to perform unrestricted app switches. Mapping is
537 * User -> Type -> uid.
538 */
539 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
540
541 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private int mThumbnailWidth;
543 private int mThumbnailHeight;
544 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Flag that indicates if multi-window is enabled.
548 *
549 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
550 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
551 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
552 * At least one of the forms of multi-window must be enabled in order for this flag to be
553 * initialized to 'true'.
554 *
555 * @see #mSupportsSplitScreenMultiWindow
556 * @see #mSupportsFreeformWindowManagement
557 * @see #mSupportsPictureInPicture
558 * @see #mSupportsMultiDisplay
559 */
560 boolean mSupportsMultiWindow;
561 boolean mSupportsSplitScreenMultiWindow;
562 boolean mSupportsFreeformWindowManagement;
563 boolean mSupportsPictureInPicture;
564 boolean mSupportsMultiDisplay;
565 boolean mForceResizableActivities;
566
567 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
568
569 // VR Vr2d Display Id.
570 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700571
Wale Ogunwalef6733932018-06-27 05:14:34 -0700572 /**
573 * Set while we are wanting to sleep, to prevent any
574 * activities from being started/resumed.
575 *
576 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
577 *
578 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
579 * while in the sleep state until there is a pending transition out of sleep, in which case
580 * mSleeping is set to false, and remains false while awake.
581 *
582 * Whether mSleeping can quickly toggled between true/false without the device actually
583 * display changing states is undefined.
584 */
585 private boolean mSleeping = false;
586
587 /**
588 * The process state used for processes that are running the top activities.
589 * This changes between TOP and TOP_SLEEPING to following mSleeping.
590 */
591 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
592
593 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
594 // automatically. Important for devices without direct input devices.
595 private boolean mShowDialogs = true;
596
597 /** Set if we are shutting down the system, similar to sleeping. */
598 boolean mShuttingDown = false;
599
600 /**
601 * We want to hold a wake lock while running a voice interaction session, since
602 * this may happen with the screen off and we need to keep the CPU running to
603 * be able to continue to interact with the user.
604 */
605 PowerManager.WakeLock mVoiceWakeLock;
606
607 /**
608 * Set while we are running a voice interaction. This overrides sleeping while it is active.
609 */
610 IVoiceInteractionSession mRunningVoice;
611
612 /**
613 * The last resumed activity. This is identical to the current resumed activity most
614 * of the time but could be different when we're pausing one activity before we resume
615 * another activity.
616 */
617 ActivityRecord mLastResumedActivity;
618
619 /**
620 * The activity that is currently being traced as the active resumed activity.
621 *
622 * @see #updateResumedAppTrace
623 */
624 private @Nullable ActivityRecord mTracedResumedActivity;
625
626 /** If non-null, we are tracking the time the user spends in the currently focused app. */
627 AppTimeTracker mCurAppTimeTracker;
628
Wale Ogunwale008163e2018-07-23 23:11:08 -0700629 private AppWarnings mAppWarnings;
630
Wale Ogunwale53783742018-09-16 10:21:51 -0700631 /**
632 * Packages that the user has asked to have run in screen size
633 * compatibility mode instead of filling the screen.
634 */
635 CompatModePackages mCompatModePackages;
636
Wale Ogunwalef6733932018-06-27 05:14:34 -0700637 private FontScaleSettingObserver mFontScaleSettingObserver;
638
Ricky Wai96f5c352019-04-10 18:40:17 +0100639 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private final class FontScaleSettingObserver extends ContentObserver {
642 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
643 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
644
645 public FontScaleSettingObserver() {
646 super(mH);
647 final ContentResolver resolver = mContext.getContentResolver();
648 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
649 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
650 UserHandle.USER_ALL);
651 }
652
653 @Override
654 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
655 if (mFontScaleUri.equals(uri)) {
656 updateFontScaleIfNeeded(userId);
657 } else if (mHideErrorDialogsUri.equals(uri)) {
658 synchronized (mGlobalLock) {
659 updateShouldShowDialogsLocked(getGlobalConfiguration());
660 }
661 }
662 }
663 }
664
Riddle Hsua0536432019-02-16 00:38:59 +0800665 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
666 @Target(ElementType.METHOD)
667 @Retention(RetentionPolicy.SOURCE)
668 @interface HotPath {
669 int NONE = 0;
670 int OOM_ADJUSTMENT = 1;
671 int LRU_UPDATE = 2;
672 int PROCESS_CHANGE = 3;
673 int caller() default NONE;
674 }
675
Charles Chen8d98dd22018-12-26 17:36:54 +0800676 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
677 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700678 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700679 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700680 mSystemThread = ActivityThread.currentActivityThread();
681 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700682 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800683 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700685 }
686
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700687 public void onSystemReady() {
688 synchronized (mGlobalLock) {
689 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
690 PackageManager.FEATURE_CANT_SAVE_STATE);
691 mAssistUtils = new AssistUtils(mContext);
692 mVrController.onSystemReady();
693 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700694 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700696 }
697
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700698 public void onInitPowerManagement() {
699 synchronized (mGlobalLock) {
700 mStackSupervisor.initPowerManagement();
701 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
702 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
703 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
704 mVoiceWakeLock.setReferenceCounted(false);
705 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700709 mFontScaleSettingObserver = new FontScaleSettingObserver();
710 }
711
Wale Ogunwale59507092018-10-29 09:00:30 -0700712 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700713 final boolean freeformWindowManagement =
714 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
715 || Settings.Global.getInt(
716 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
717
718 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
719 final boolean supportsPictureInPicture = supportsMultiWindow &&
720 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
721 final boolean supportsSplitScreenMultiWindow =
722 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
723 final boolean supportsMultiDisplay = mContext.getPackageManager()
724 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
726 final boolean forceResizable = Settings.Global.getInt(
727 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700728 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729
730 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900731 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732
733 final Configuration configuration = new Configuration();
734 Settings.System.getConfiguration(resolver, configuration);
735 if (forceRtl) {
736 // This will take care of setting the correct layout direction flags
737 configuration.setLayoutDirection(configuration.locale);
738 }
739
740 synchronized (mGlobalLock) {
741 mForceResizableActivities = forceResizable;
742 final boolean multiWindowFormEnabled = freeformWindowManagement
743 || supportsSplitScreenMultiWindow
744 || supportsPictureInPicture
745 || supportsMultiDisplay;
746 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
747 mSupportsMultiWindow = true;
748 mSupportsFreeformWindowManagement = freeformWindowManagement;
749 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
750 mSupportsPictureInPicture = supportsPictureInPicture;
751 mSupportsMultiDisplay = supportsMultiDisplay;
752 } else {
753 mSupportsMultiWindow = false;
754 mSupportsFreeformWindowManagement = false;
755 mSupportsSplitScreenMultiWindow = false;
756 mSupportsPictureInPicture = false;
757 mSupportsMultiDisplay = false;
758 }
759 mWindowManager.setForceResizableTasks(mForceResizableActivities);
760 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700761 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
762 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700763 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 // This happens before any activities are started, so we can change global configuration
765 // in-place.
766 updateConfigurationLocked(configuration, null, true);
767 final Configuration globalConfig = getGlobalConfiguration();
768 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
769
770 // Load resources only after the current configuration has been set.
771 final Resources res = mContext.getResources();
772 mThumbnailWidth = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_width);
774 mThumbnailHeight = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_height);
776
777 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
778 mFullscreenThumbnailScale = (float) res
779 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
780 (float) globalConfig.screenWidthDp;
781 } else {
782 mFullscreenThumbnailScale = res.getFraction(
783 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
784 }
785 }
786 }
787
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800788 public WindowManagerGlobalLock getGlobalLock() {
789 return mGlobalLock;
790 }
791
Yunfan Chen585f2932019-01-29 16:04:45 +0900792 /** For test purpose only. */
793 @VisibleForTesting
794 public ActivityTaskManagerInternal getAtmInternal() {
795 return mInternal;
796 }
797
Riddle Hsud93a6c42018-11-29 21:50:06 +0800798 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
799 Looper looper) {
800 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700803 final File systemDir = SystemServiceManager.ensureSystemDir();
804 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
805 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
808 mTempConfig.setToDefaults();
809 mTempConfig.setLocales(LocaleList.getDefault());
810 mConfigurationSeq = mTempConfig.seq = 1;
811 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800812 mRootActivityContainer = new RootActivityContainer(this);
813 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700817 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700819 mRecentTasks = createRecentTasks();
820 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700822 mKeyguardController = mStackSupervisor.getKeyguardController();
823 }
824
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700825 public void onActivityManagerInternalAdded() {
826 synchronized (mGlobalLock) {
827 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
828 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
829 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700830 }
831
Yunfan Chen75157d72018-07-27 14:47:21 +0900832 int increaseConfigurationSeqLocked() {
833 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
834 return mConfigurationSeq;
835 }
836
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 protected ActivityStackSupervisor createStackSupervisor() {
838 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
839 supervisor.initialize();
840 return supervisor;
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void setWindowManager(WindowManagerService wm) {
844 synchronized (mGlobalLock) {
845 mWindowManager = wm;
846 mLockTaskController.setWindowManager(wm);
847 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800848 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
853 synchronized (mGlobalLock) {
854 mUsageStatsInternal = usageStatsManager;
855 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700856 }
857
Wale Ogunwalef6733932018-06-27 05:14:34 -0700858 UserManagerService getUserManager() {
859 if (mUserManager == null) {
860 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
861 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
862 }
863 return mUserManager;
864 }
865
866 AppOpsService getAppOpsService() {
867 if (mAppOpsService == null) {
868 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
869 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
870 }
871 return mAppOpsService;
872 }
873
874 boolean hasUserRestriction(String restriction, int userId) {
875 return getUserManager().hasUserRestriction(restriction, userId);
876 }
877
Michal Karpinski15486842019-04-25 17:33:42 +0100878 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
879 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
880 callingUid, callingPackage);
881 if (mode == AppOpsManager.MODE_DEFAULT) {
882 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
883 == PERMISSION_GRANTED;
884 }
885 return mode == AppOpsManager.MODE_ALLOWED;
886 }
887
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700888 protected RecentTasks createRecentTasks() {
889 return new RecentTasks(this, mStackSupervisor);
890 }
891
892 RecentTasks getRecentTasks() {
893 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700894 }
895
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700896 ClientLifecycleManager getLifecycleManager() {
897 return mLifecycleManager;
898 }
899
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700900 ActivityStartController getActivityStartController() {
901 return mActivityStartController;
902 }
903
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700904 TaskChangeNotificationController getTaskChangeNotificationController() {
905 return mTaskChangeNotificationController;
906 }
907
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700908 LockTaskController getLockTaskController() {
909 return mLockTaskController;
910 }
911
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 /**
913 * Return the global configuration used by the process corresponding to the input pid. This is
914 * usually the global configuration with some overrides specific to that process.
915 */
916 Configuration getGlobalConfigurationForCallingPid() {
917 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800918 return getGlobalConfigurationForPid(pid);
919 }
920
921 /**
922 * Return the global configuration used by the process corresponding to the given pid.
923 */
924 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900925 if (pid == MY_PID || pid < 0) {
926 return getGlobalConfiguration();
927 }
928 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100929 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 return app != null ? app.getConfiguration() : getGlobalConfiguration();
931 }
932 }
933
934 /**
935 * Return the device configuration info used by the process corresponding to the input pid.
936 * The value is consistent with the global configuration for the process.
937 */
938 @Override
939 public ConfigurationInfo getDeviceConfigurationInfo() {
940 ConfigurationInfo config = new ConfigurationInfo();
941 synchronized (mGlobalLock) {
942 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
943 config.reqTouchScreen = globalConfig.touchscreen;
944 config.reqKeyboardType = globalConfig.keyboard;
945 config.reqNavigation = globalConfig.navigation;
946 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
947 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
948 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
949 }
950 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
951 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
953 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700954 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 }
956 return config;
957 }
958
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700959 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700960 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 }
962
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700963 public static final class Lifecycle extends SystemService {
964 private final ActivityTaskManagerService mService;
965
966 public Lifecycle(Context context) {
967 super(context);
968 mService = new ActivityTaskManagerService(context);
969 }
970
971 @Override
972 public void onStart() {
973 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700974 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700975 }
976
Garfield Tan891146c2018-10-09 12:14:00 -0700977 @Override
978 public void onUnlockUser(int userId) {
979 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800980 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700981 }
982 }
983
984 @Override
985 public void onCleanupUser(int userId) {
986 synchronized (mService.getGlobalLock()) {
987 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
988 }
989 }
990
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 public ActivityTaskManagerService getService() {
992 return mService;
993 }
994 }
995
996 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997 public final int startActivity(IApplicationThread caller, String callingPackage,
998 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
999 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1000 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1001 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1002 UserHandle.getCallingUserId());
1003 }
1004
1005 @Override
1006 public final int startActivities(IApplicationThread caller, String callingPackage,
1007 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1008 int userId) {
1009 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001010 enforceNotIsolatedCaller(reason);
1011 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001013 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1014 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1015 reason, null /* originatingPendingIntent */,
1016 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1021 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1022 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1023 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1024 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1025 true /*validateIncomingUser*/);
1026 }
1027
1028 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1029 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1030 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1031 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001034 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1036
1037 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 .setCaller(caller)
1040 .setCallingPackage(callingPackage)
1041 .setResolvedType(resolvedType)
1042 .setResultTo(resultTo)
1043 .setResultWho(resultWho)
1044 .setRequestCode(requestCode)
1045 .setStartFlags(startFlags)
1046 .setProfilerInfo(profilerInfo)
1047 .setActivityOptions(bOptions)
1048 .setMayWait(userId)
1049 .execute();
1050
1051 }
1052
1053 @Override
1054 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1055 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001056 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1057 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058 // Refuse possible leaked file descriptors
1059 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1060 throw new IllegalArgumentException("File descriptors passed in Intent");
1061 }
1062
1063 if (!(target instanceof PendingIntentRecord)) {
1064 throw new IllegalArgumentException("Bad PendingIntent object");
1065 }
1066
1067 PendingIntentRecord pir = (PendingIntentRecord)target;
1068
1069 synchronized (mGlobalLock) {
1070 // If this is coming from the currently resumed activity, it is
1071 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001072 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 if (stack.mResumedActivity != null &&
1074 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001075 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 }
1077 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081
1082 @Override
1083 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1084 Bundle bOptions) {
1085 // Refuse possible leaked file descriptors
1086 if (intent != null && intent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1090
1091 synchronized (mGlobalLock) {
1092 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1093 if (r == null) {
1094 SafeActivityOptions.abort(options);
1095 return false;
1096 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001097 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 // The caller is not running... d'oh!
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
1102 intent = new Intent(intent);
1103 // The caller is not allowed to change the data.
1104 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1105 // And we are resetting to find the next component...
1106 intent.setComponent(null);
1107
1108 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1109
1110 ActivityInfo aInfo = null;
1111 try {
1112 List<ResolveInfo> resolves =
1113 AppGlobals.getPackageManager().queryIntentActivities(
1114 intent, r.resolvedType,
1115 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1116 UserHandle.getCallingUserId()).getList();
1117
1118 // Look for the original activity in the list...
1119 final int N = resolves != null ? resolves.size() : 0;
1120 for (int i=0; i<N; i++) {
1121 ResolveInfo rInfo = resolves.get(i);
1122 if (rInfo.activityInfo.packageName.equals(r.packageName)
1123 && rInfo.activityInfo.name.equals(r.info.name)) {
1124 // We found the current one... the next matching is
1125 // after it.
1126 i++;
1127 if (i<N) {
1128 aInfo = resolves.get(i).activityInfo;
1129 }
1130 if (debug) {
1131 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1132 + "/" + r.info.name);
1133 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1134 ? "null" : aInfo.packageName + "/" + aInfo.name));
1135 }
1136 break;
1137 }
1138 }
1139 } catch (RemoteException e) {
1140 }
1141
1142 if (aInfo == null) {
1143 // Nobody who is next!
1144 SafeActivityOptions.abort(options);
1145 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1146 return false;
1147 }
1148
1149 intent.setComponent(new ComponentName(
1150 aInfo.applicationInfo.packageName, aInfo.name));
1151 intent.setFlags(intent.getFlags()&~(
1152 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1153 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1154 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1155 FLAG_ACTIVITY_NEW_TASK));
1156
1157 // Okay now we need to start the new activity, replacing the currently running activity.
1158 // This is a little tricky because we want to start the new one as if the current one is
1159 // finished, but not finish the current one first so that there is no flicker.
1160 // And thus...
1161 final boolean wasFinishing = r.finishing;
1162 r.finishing = true;
1163
1164 // Propagate reply information over to the new activity.
1165 final ActivityRecord resultTo = r.resultTo;
1166 final String resultWho = r.resultWho;
1167 final int requestCode = r.requestCode;
1168 r.resultTo = null;
1169 if (resultTo != null) {
1170 resultTo.removeResultsLocked(r, resultWho, requestCode);
1171 }
1172
1173 final long origId = Binder.clearCallingIdentity();
1174 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001175 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001177 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001178 .setResolvedType(r.resolvedType)
1179 .setActivityInfo(aInfo)
1180 .setResultTo(resultTo != null ? resultTo.appToken : null)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setCallingPid(-1)
1184 .setCallingUid(r.launchedFromUid)
1185 .setCallingPackage(r.launchedFromPackage)
1186 .setRealCallingPid(-1)
1187 .setRealCallingUid(r.launchedFromUid)
1188 .setActivityOptions(options)
1189 .execute();
1190 Binder.restoreCallingIdentity(origId);
1191
1192 r.finishing = wasFinishing;
1193 if (res != ActivityManager.START_SUCCESS) {
1194 return false;
1195 }
1196 return true;
1197 }
1198 }
1199
1200 @Override
1201 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1202 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1203 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1204 final WaitResult res = new WaitResult();
1205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001206 enforceNotIsolatedCaller("startActivityAndWait");
1207 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1208 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001210 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setCaller(caller)
1212 .setCallingPackage(callingPackage)
1213 .setResolvedType(resolvedType)
1214 .setResultTo(resultTo)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setStartFlags(startFlags)
1218 .setActivityOptions(bOptions)
1219 .setMayWait(userId)
1220 .setProfilerInfo(profilerInfo)
1221 .setWaitResult(res)
1222 .execute();
1223 }
1224 return res;
1225 }
1226
1227 @Override
1228 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, Configuration config, Bundle bOptions, int userId) {
1231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001232 enforceNotIsolatedCaller("startActivityWithConfig");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1234 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001236 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setGlobalConfiguration(config)
1245 .setActivityOptions(bOptions)
1246 .setMayWait(userId)
1247 .execute();
1248 }
1249 }
1250
Alison Cichowlas3e340502018-08-07 17:15:01 -04001251
1252 @Override
1253 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1254 int callingUid = Binder.getCallingUid();
1255 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1256 throw new SecurityException("Only the system process can request a permission token, "
1257 + "received request from uid: " + callingUid);
1258 }
1259 IBinder permissionToken = new Binder();
1260 synchronized (mGlobalLock) {
1261 mStartActivitySources.put(permissionToken, delegatorToken);
1262 }
1263
1264 Message expireMsg = PooledLambda.obtainMessage(
1265 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1266 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1267
1268 Message forgetMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1271
1272 return permissionToken;
1273 }
1274
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 @Override
1276 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1277 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001278 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1279 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 // permission grants) as any app that may launch one of your own activities. So we only
1282 // allow this in two cases:
1283 // 1) The caller is an activity that is part of the core framework, and then only when it
1284 // is running as the system.
1285 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1286 // can only be requested by a system activity, which may then delegate this call to
1287 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 final ActivityRecord sourceRecord;
1289 final int targetUid;
1290 final String targetPackage;
1291 final boolean isResolver;
1292 synchronized (mGlobalLock) {
1293 if (resultTo == null) {
1294 throw new SecurityException("Must be called from an activity");
1295 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 final IBinder sourceToken;
1297 if (permissionToken != null) {
1298 // To even attempt to use a permissionToken, an app must also have this signature
1299 // permission.
1300 mAmInternal.enforceCallingPermission(
1301 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1302 "startActivityAsCaller");
1303 // If called with a permissionToken, we want the sourceRecord from the delegator
1304 // activity that requested this token.
1305 sourceToken = mStartActivitySources.remove(permissionToken);
1306 if (sourceToken == null) {
1307 // Invalid permissionToken, check if it recently expired.
1308 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1309 throw new SecurityException("Called with expired permission token: "
1310 + permissionToken);
1311 } else {
1312 throw new SecurityException("Called with invalid permission token: "
1313 + permissionToken);
1314 }
1315 }
1316 } else {
1317 // This method was called directly by the source.
1318 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001320
Wale Ogunwaled32da472018-11-16 07:19:28 -08001321 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 if (sourceRecord == null) {
1323 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
1325 if (sourceRecord.app == null) {
1326 throw new SecurityException("Called without a process attached to activity");
1327 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001328
1329 // Whether called directly or from a delegate, the source activity must be from the
1330 // android package.
1331 if (!sourceRecord.info.packageName.equals("android")) {
1332 throw new SecurityException("Must be called from an activity that is "
1333 + "declared in the android package");
1334 }
1335
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001336 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 // This is still okay, as long as this activity is running under the
1338 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 + " must be system uid or original calling uid "
1343 + sourceRecord.launchedFromUid);
1344 }
1345 }
1346 if (ignoreTargetSecurity) {
1347 if (intent.getComponent() == null) {
1348 throw new SecurityException(
1349 "Component must be specified with ignoreTargetSecurity");
1350 }
1351 if (intent.getSelector() != null) {
1352 throw new SecurityException(
1353 "Selector not allowed with ignoreTargetSecurity");
1354 }
1355 }
1356 targetUid = sourceRecord.launchedFromUid;
1357 targetPackage = sourceRecord.launchedFromPackage;
1358 isResolver = sourceRecord.isResolverOrChildActivity();
1359 }
1360
1361 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 }
1364
1365 // TODO: Switch to user app stacks here.
1366 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(targetUid)
1369 .setCallingPackage(targetPackage)
1370 .setResolvedType(resolvedType)
1371 .setResultTo(resultTo)
1372 .setResultWho(resultWho)
1373 .setRequestCode(requestCode)
1374 .setStartFlags(startFlags)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1378 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001379 // The target may well be in the background, which would normally prevent it
1380 // from starting an activity. Here we definitely want the start to succeed.
1381 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 .execute();
1383 } catch (SecurityException e) {
1384 // XXX need to figure out how to propagate to original app.
1385 // A SecurityException here is generally actually a fault of the original
1386 // calling activity (such as a fairly granting permissions), so propagate it
1387 // back to them.
1388 /*
1389 StringBuilder msg = new StringBuilder();
1390 msg.append("While launching");
1391 msg.append(intent.toString());
1392 msg.append(": ");
1393 msg.append(e.getMessage());
1394 */
1395 throw e;
1396 }
1397 }
1398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1400 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1401 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1402 }
1403
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 @Override
1405 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1406 Intent intent, String resolvedType, IVoiceInteractionSession session,
1407 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1408 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 if (session == null || interactor == null) {
1411 throw new NullPointerException("null session or interactor");
1412 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001415 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 .setCallingUid(callingUid)
1417 .setCallingPackage(callingPackage)
1418 .setResolvedType(resolvedType)
1419 .setVoiceSession(session)
1420 .setVoiceInteractor(interactor)
1421 .setStartFlags(startFlags)
1422 .setProfilerInfo(profilerInfo)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1431 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1433 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001435 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .setCallingUid(callingUid)
1437 .setCallingPackage(callingPackage)
1438 .setResolvedType(resolvedType)
1439 .setActivityOptions(bOptions)
1440 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001441 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .execute();
1443 }
1444
1445 @Override
1446 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1447 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 final int callingPid = Binder.getCallingPid();
1450 final long origId = Binder.clearCallingIdentity();
1451 try {
1452 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001453 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1454 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455
1456 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1458 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1460 recentsUid, assistDataReceiver);
1461 }
1462 } finally {
1463 Binder.restoreCallingIdentity(origId);
1464 }
1465 }
1466
1467 @Override
1468 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001469 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470 "startActivityFromRecents()");
1471
1472 final int callingPid = Binder.getCallingPid();
1473 final int callingUid = Binder.getCallingUid();
1474 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1475 final long origId = Binder.clearCallingIdentity();
1476 try {
1477 synchronized (mGlobalLock) {
1478 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1479 safeOptions);
1480 }
1481 } finally {
1482 Binder.restoreCallingIdentity(origId);
1483 }
1484 }
1485
1486 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001487 * Public API to check if the client is allowed to start an activity on specified display.
1488 *
1489 * If the target display is private or virtual, some restrictions will apply.
1490 *
1491 * @param displayId Target display id.
1492 * @param intent Intent used to launch the activity.
1493 * @param resolvedType The MIME type of the intent.
1494 * @param userId The id of the user for whom the call is made.
1495 * @return {@code true} if a call to start an activity on the target display should succeed and
1496 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1497 */
1498 @Override
1499 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1500 String resolvedType, int userId) {
1501 final int callingUid = Binder.getCallingUid();
1502 final int callingPid = Binder.getCallingPid();
1503 final long origId = Binder.clearCallingIdentity();
1504
1505 try {
1506 // Collect information about the target of the Intent.
1507 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1508 0 /* startFlags */, null /* profilerInfo */, userId,
1509 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1510 UserHandle.USER_NULL));
1511 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1512
1513 synchronized (mGlobalLock) {
1514 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1515 aInfo);
1516 }
1517 } finally {
1518 Binder.restoreCallingIdentity(origId);
1519 }
1520 }
1521
1522 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 * This is the internal entry point for handling Activity.finish().
1524 *
1525 * @param token The Binder token referencing the Activity we want to finish.
1526 * @param resultCode Result code, if any, from this Activity.
1527 * @param resultData Result data (Intent), if any, from this Activity.
1528 * @param finishTask Whether to finish the task associated with this Activity.
1529 *
1530 * @return Returns true if the activity successfully finished, or false if it is still running.
1531 */
1532 @Override
1533 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1534 int finishTask) {
1535 // Refuse possible leaked file descriptors
1536 if (resultData != null && resultData.hasFileDescriptors()) {
1537 throw new IllegalArgumentException("File descriptors passed in Intent");
1538 }
1539
1540 synchronized (mGlobalLock) {
1541 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1542 if (r == null) {
1543 return true;
1544 }
1545 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001546 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 ActivityRecord rootR = tr.getRootActivity();
1548 if (rootR == null) {
1549 Slog.w(TAG, "Finishing task with all activities already finished");
1550 }
1551 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1552 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001553 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 return false;
1555 }
1556
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001557 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1558 // We should consolidate.
1559 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001561 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 if (next != null) {
1563 // ask watcher if this is allowed
1564 boolean resumeOK = true;
1565 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001566 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001568 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 Watchdog.getInstance().setActivityController(null);
1570 }
1571
1572 if (!resumeOK) {
1573 Slog.i(TAG, "Not finishing activity because controller resumed");
1574 return false;
1575 }
1576 }
1577 }
1578 final long origId = Binder.clearCallingIdentity();
1579 try {
1580 boolean res;
1581 final boolean finishWithRootActivity =
1582 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1583 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1584 || (finishWithRootActivity && r == rootR)) {
1585 // If requested, remove the task that is associated to this activity only if it
1586 // was the root activity in the task. The result code and data is ignored
1587 // because we don't support returning them across task boundaries. Also, to
1588 // keep backwards compatibility we remove the task from recents when finishing
1589 // task with root activity.
1590 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1591 finishWithRootActivity, "finish-activity");
1592 if (!res) {
1593 Slog.i(TAG, "Removing task failed to finish activity");
1594 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001595 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001596 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 } else {
1598 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1599 resultData, "app-request", true);
1600 if (!res) {
1601 Slog.i(TAG, "Failed to finish by app-request");
1602 }
1603 }
1604 return res;
1605 } finally {
1606 Binder.restoreCallingIdentity(origId);
1607 }
1608 }
1609 }
1610
1611 @Override
1612 public boolean finishActivityAffinity(IBinder token) {
1613 synchronized (mGlobalLock) {
1614 final long origId = Binder.clearCallingIdentity();
1615 try {
1616 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1617 if (r == null) {
1618 return false;
1619 }
1620
1621 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1622 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001623 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001624 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 return false;
1626 }
1627 return task.getStack().finishActivityAffinityLocked(r);
1628 } finally {
1629 Binder.restoreCallingIdentity(origId);
1630 }
1631 }
1632 }
1633
1634 @Override
1635 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1636 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001637 try {
1638 WindowProcessController proc = null;
1639 synchronized (mGlobalLock) {
1640 ActivityStack stack = ActivityRecord.getStackLocked(token);
1641 if (stack == null) {
1642 return;
1643 }
1644 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1645 false /* fromTimeout */, false /* processPausingActivities */, config);
1646 if (r != null) {
1647 proc = r.app;
1648 }
1649 if (stopProfiling && proc != null) {
1650 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
1652 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001653 } finally {
1654 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 }
1657
1658 @Override
1659 public final void activityResumed(IBinder token) {
1660 final long origId = Binder.clearCallingIdentity();
1661 synchronized (mGlobalLock) {
1662 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001663 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001664 }
1665 Binder.restoreCallingIdentity(origId);
1666 }
1667
1668 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001669 public final void activityTopResumedStateLost() {
1670 final long origId = Binder.clearCallingIdentity();
1671 synchronized (mGlobalLock) {
1672 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1673 }
1674 Binder.restoreCallingIdentity(origId);
1675 }
1676
1677 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 public final void activityPaused(IBinder token) {
1679 final long origId = Binder.clearCallingIdentity();
1680 synchronized (mGlobalLock) {
1681 ActivityStack stack = ActivityRecord.getStackLocked(token);
1682 if (stack != null) {
1683 stack.activityPausedLocked(token, false);
1684 }
1685 }
1686 Binder.restoreCallingIdentity(origId);
1687 }
1688
1689 @Override
1690 public final void activityStopped(IBinder token, Bundle icicle,
1691 PersistableBundle persistentState, CharSequence description) {
1692 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1693
1694 // Refuse possible leaked file descriptors
1695 if (icicle != null && icicle.hasFileDescriptors()) {
1696 throw new IllegalArgumentException("File descriptors passed in Bundle");
1697 }
1698
1699 final long origId = Binder.clearCallingIdentity();
1700
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001701 String restartingName = null;
1702 int restartingUid = 0;
1703 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001705 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001707 if (r.attachedToProcess()
1708 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1709 // The activity was requested to restart from
1710 // {@link #restartActivityProcessIfVisible}.
1711 restartingName = r.app.mName;
1712 restartingUid = r.app.mUid;
1713 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 r.activityStoppedLocked(icicle, persistentState, description);
1715 }
1716 }
1717
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001718 if (restartingName != null) {
1719 // In order to let the foreground activity can be restarted with its saved state from
1720 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1721 // until the activity reports stopped with the state. And the activity record will be
1722 // kept because the record state is restarting, then the activity will be restarted
1723 // immediately if it is still the top one.
1724 mStackSupervisor.removeRestartTimeouts(r);
1725 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1726 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001727 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
1733 public final void activityDestroyed(IBinder token) {
1734 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1735 synchronized (mGlobalLock) {
1736 ActivityStack stack = ActivityRecord.getStackLocked(token);
1737 if (stack != null) {
1738 stack.activityDestroyedLocked(token, "activityDestroyed");
1739 }
1740 }
1741 }
1742
1743 @Override
1744 public final void activityRelaunched(IBinder token) {
1745 final long origId = Binder.clearCallingIdentity();
1746 synchronized (mGlobalLock) {
1747 mStackSupervisor.activityRelaunchedLocked(token);
1748 }
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 public final void activitySlept(IBinder token) {
1753 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1754
1755 final long origId = Binder.clearCallingIdentity();
1756
1757 synchronized (mGlobalLock) {
1758 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1759 if (r != null) {
1760 mStackSupervisor.activitySleptLocked(r);
1761 }
1762 }
1763
1764 Binder.restoreCallingIdentity(origId);
1765 }
1766
1767 @Override
1768 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1769 synchronized (mGlobalLock) {
1770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1771 if (r == null) {
1772 return;
1773 }
1774 final long origId = Binder.clearCallingIdentity();
1775 try {
1776 r.setRequestedOrientation(requestedOrientation);
1777 } finally {
1778 Binder.restoreCallingIdentity(origId);
1779 }
1780 }
1781 }
1782
1783 @Override
1784 public int getRequestedOrientation(IBinder token) {
1785 synchronized (mGlobalLock) {
1786 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r == null) {
1788 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1789 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001790 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792 }
1793
1794 @Override
1795 public void setImmersive(IBinder token, boolean immersive) {
1796 synchronized (mGlobalLock) {
1797 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1798 if (r == null) {
1799 throw new IllegalArgumentException();
1800 }
1801 r.immersive = immersive;
1802
1803 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001804 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
1808 }
1809 }
1810
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 void applyUpdateLockStateLocked(ActivityRecord r) {
1812 // Modifications to the UpdateLock state are done on our handler, outside
1813 // the activity manager's locks. The new state is determined based on the
1814 // state *now* of the relevant activity record. The object is passed to
1815 // the handler solely for logging detail, not to be consulted/modified.
1816 final boolean nextState = r != null && r.immersive;
1817 mH.post(() -> {
1818 if (mUpdateLock.isHeld() != nextState) {
1819 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1820 "Applying new update lock state '" + nextState + "' for " + r);
1821 if (nextState) {
1822 mUpdateLock.acquire();
1823 } else {
1824 mUpdateLock.release();
1825 }
1826 }
1827 });
1828 }
1829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 @Override
1831 public boolean isImmersive(IBinder token) {
1832 synchronized (mGlobalLock) {
1833 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1834 if (r == null) {
1835 throw new IllegalArgumentException();
1836 }
1837 return r.immersive;
1838 }
1839 }
1840
1841 @Override
1842 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001843 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001845 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 return (r != null) ? r.immersive : false;
1847 }
1848 }
1849
1850 @Override
1851 public void overridePendingTransition(IBinder token, String packageName,
1852 int enterAnim, int exitAnim) {
1853 synchronized (mGlobalLock) {
1854 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1855 if (self == null) {
1856 return;
1857 }
1858
1859 final long origId = Binder.clearCallingIdentity();
1860
1861 if (self.isState(
1862 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001863 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001864 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866
1867 Binder.restoreCallingIdentity(origId);
1868 }
1869 }
1870
1871 @Override
1872 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001875 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 if (r == null) {
1877 return ActivityManager.COMPAT_MODE_UNKNOWN;
1878 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001879 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 }
1881 }
1882
1883 @Override
1884 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001887 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001889 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001890 if (r == null) {
1891 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1892 return;
1893 }
1894 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001895 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
1897 }
1898
1899 @Override
1900 public int getLaunchedFromUid(IBinder activityToken) {
1901 ActivityRecord srec;
1902 synchronized (mGlobalLock) {
1903 srec = ActivityRecord.forTokenLocked(activityToken);
1904 }
1905 if (srec == null) {
1906 return -1;
1907 }
1908 return srec.launchedFromUid;
1909 }
1910
1911 @Override
1912 public String getLaunchedFromPackage(IBinder activityToken) {
1913 ActivityRecord srec;
1914 synchronized (mGlobalLock) {
1915 srec = ActivityRecord.forTokenLocked(activityToken);
1916 }
1917 if (srec == null) {
1918 return null;
1919 }
1920 return srec.launchedFromPackage;
1921 }
1922
1923 @Override
1924 public boolean convertFromTranslucent(IBinder token) {
1925 final long origId = Binder.clearCallingIdentity();
1926 try {
1927 synchronized (mGlobalLock) {
1928 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1929 if (r == null) {
1930 return false;
1931 }
1932 final boolean translucentChanged = r.changeWindowTranslucency(true);
1933 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001934 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 return translucentChanged;
1938 }
1939 } finally {
1940 Binder.restoreCallingIdentity(origId);
1941 }
1942 }
1943
1944 @Override
1945 public boolean convertToTranslucent(IBinder token, Bundle options) {
1946 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1947 final long origId = Binder.clearCallingIdentity();
1948 try {
1949 synchronized (mGlobalLock) {
1950 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1951 if (r == null) {
1952 return false;
1953 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001954 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 int index = task.mActivities.lastIndexOf(r);
1956 if (index > 0) {
1957 ActivityRecord under = task.mActivities.get(index - 1);
1958 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1959 }
1960 final boolean translucentChanged = r.changeWindowTranslucency(false);
1961 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001962 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001964 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001965 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 return translucentChanged;
1967 }
1968 } finally {
1969 Binder.restoreCallingIdentity(origId);
1970 }
1971 }
1972
1973 @Override
1974 public void notifyActivityDrawn(IBinder token) {
1975 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1976 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001977 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 }
1981 }
1982 }
1983
1984 @Override
1985 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1986 synchronized (mGlobalLock) {
1987 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return;
1990 }
1991 r.reportFullyDrawnLocked(restoredFromBundle);
1992 }
1993 }
1994
1995 @Override
1996 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1997 synchronized (mGlobalLock) {
1998 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1999 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2000 return stack.mDisplayId;
2001 }
2002 return DEFAULT_DISPLAY;
2003 }
2004 }
2005
2006 @Override
2007 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002008 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 long ident = Binder.clearCallingIdentity();
2010 try {
2011 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002012 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 return null;
2017 }
2018 } finally {
2019 Binder.restoreCallingIdentity(ident);
2020 }
2021 }
2022
2023 @Override
2024 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002025 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2027 final long callingId = Binder.clearCallingIdentity();
2028 try {
2029 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 if (stack == null) {
2032 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2033 return;
2034 }
2035 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002036 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002037 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 }
2040 } finally {
2041 Binder.restoreCallingIdentity(callingId);
2042 }
2043 }
2044
2045 @Override
2046 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002047 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2049 final long callingId = Binder.clearCallingIdentity();
2050 try {
2051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002052 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002053 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 if (task == null) {
2055 return;
2056 }
2057 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002058 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 }
2062 } finally {
2063 Binder.restoreCallingIdentity(callingId);
2064 }
2065 }
2066
2067 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002068 public void restartActivityProcessIfVisible(IBinder activityToken) {
2069 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2070 final long callingId = Binder.clearCallingIdentity();
2071 try {
2072 synchronized (mGlobalLock) {
2073 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2074 if (r == null) {
2075 return;
2076 }
2077 r.restartProcessIfVisible();
2078 }
2079 } finally {
2080 Binder.restoreCallingIdentity(callingId);
2081 }
2082 }
2083
2084 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002086 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 synchronized (mGlobalLock) {
2088 final long ident = Binder.clearCallingIdentity();
2089 try {
2090 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2091 "remove-task");
2092 } finally {
2093 Binder.restoreCallingIdentity(ident);
2094 }
2095 }
2096 }
2097
2098 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002099 public void removeAllVisibleRecentTasks() {
2100 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2101 synchronized (mGlobalLock) {
2102 final long ident = Binder.clearCallingIdentity();
2103 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002104 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002105 } finally {
2106 Binder.restoreCallingIdentity(ident);
2107 }
2108 }
2109 }
2110
2111 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2113 synchronized (mGlobalLock) {
2114 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2115 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002116 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 }
2118 }
2119 return false;
2120 }
2121
2122 @Override
2123 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2124 Intent resultData) {
2125
2126 synchronized (mGlobalLock) {
2127 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2128 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002129 return r.getActivityStack().navigateUpToLocked(
2130 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 }
2132 return false;
2133 }
2134 }
2135
2136 /**
2137 * Attempts to move a task backwards in z-order (the order of activities within the task is
2138 * unchanged).
2139 *
2140 * There are several possible results of this call:
2141 * - if the task is locked, then we will show the lock toast
2142 * - if there is a task behind the provided task, then that task is made visible and resumed as
2143 * this task is moved to the back
2144 * - otherwise, if there are no other tasks in the stack:
2145 * - if this task is in the pinned stack, then we remove the stack completely, which will
2146 * have the effect of moving the task to the top or bottom of the fullscreen stack
2147 * (depending on whether it is visible)
2148 * - otherwise, we simply return home and hide this task
2149 *
2150 * @param token A reference to the activity we wish to move
2151 * @param nonRoot If false then this only works if the activity is the root
2152 * of a task; if true it will work for any activity in a task.
2153 * @return Returns true if the move completed, false if not.
2154 */
2155 @Override
2156 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 synchronized (mGlobalLock) {
2159 final long origId = Binder.clearCallingIdentity();
2160 try {
2161 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002162 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (task != null) {
2164 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2165 }
2166 } finally {
2167 Binder.restoreCallingIdentity(origId);
2168 }
2169 }
2170 return false;
2171 }
2172
2173 @Override
2174 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002175 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 long ident = Binder.clearCallingIdentity();
2177 Rect rect = new Rect();
2178 try {
2179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002180 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2182 if (task == null) {
2183 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2184 return rect;
2185 }
2186 if (task.getStack() != null) {
2187 // Return the bounds from window manager since it will be adjusted for various
2188 // things like the presense of a docked stack for tasks that aren't resizeable.
2189 task.getWindowContainerBounds(rect);
2190 } else {
2191 // Task isn't in window manager yet since it isn't associated with a stack.
2192 // Return the persist value from activity manager
2193 if (!task.matchParentBounds()) {
2194 rect.set(task.getBounds());
2195 } else if (task.mLastNonFullscreenBounds != null) {
2196 rect.set(task.mLastNonFullscreenBounds);
2197 }
2198 }
2199 }
2200 } finally {
2201 Binder.restoreCallingIdentity(ident);
2202 }
2203 return rect;
2204 }
2205
2206 @Override
2207 public ActivityManager.TaskDescription getTaskDescription(int id) {
2208 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002211 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2213 if (tr != null) {
2214 return tr.lastTaskDescription;
2215 }
2216 }
2217 return null;
2218 }
2219
2220 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002221 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2222 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2223 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2224 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2225 return;
2226 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002227 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002228 synchronized (mGlobalLock) {
2229 final long ident = Binder.clearCallingIdentity();
2230 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002231 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002232 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002233 if (task == null) {
2234 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2235 return;
2236 }
2237
2238 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2239 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2240
2241 if (!task.isActivityTypeStandardOrUndefined()) {
2242 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2243 + " non-standard task " + taskId + " to windowing mode="
2244 + windowingMode);
2245 }
2246
2247 final ActivityStack stack = task.getStack();
2248 if (toTop) {
2249 stack.moveToFront("setTaskWindowingMode", task);
2250 }
2251 stack.setWindowingMode(windowingMode);
2252 } finally {
2253 Binder.restoreCallingIdentity(ident);
2254 }
2255 }
2256 }
2257
2258 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002259 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002260 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002261 ActivityRecord r = getCallingRecordLocked(token);
2262 return r != null ? r.info.packageName : null;
2263 }
2264 }
2265
2266 @Override
2267 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 ActivityRecord r = getCallingRecordLocked(token);
2270 return r != null ? r.intent.getComponent() : null;
2271 }
2272 }
2273
2274 private ActivityRecord getCallingRecordLocked(IBinder token) {
2275 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2276 if (r == null) {
2277 return null;
2278 }
2279 return r.resultTo;
2280 }
2281
2282 @Override
2283 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285
2286 synchronized (mGlobalLock) {
2287 final long origId = Binder.clearCallingIdentity();
2288 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002289 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 } finally {
2291 Binder.restoreCallingIdentity(origId);
2292 }
2293 }
2294 }
2295
Mark Renouf446251d2019-04-26 10:22:41 -04002296 @Override
2297 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2298 synchronized (mGlobalLock) {
2299 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2300 if (r == null) {
2301 return;
2302 }
2303 ActivityStack stack = r.getActivityStack();
2304 if (stack != null && stack.isSingleTaskInstance()) {
2305 // Single-task stacks are used for activities which are presented in floating
2306 // windows above full screen activities. Instead of directly finishing the
2307 // task, a task change listener is used to notify SystemUI so the action can be
2308 // handled specially.
2309 final TaskRecord task = r.getTaskRecord();
2310 mTaskChangeNotificationController
2311 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2312 } else {
2313 try {
2314 callback.requestFinish();
2315 } catch (RemoteException e) {
2316 Slog.e(TAG, "Failed to invoke request finish callback", e);
2317 }
2318 }
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 /**
2323 * TODO: Add mController hook
2324 */
2325 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002326 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2327 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329
2330 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2331 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002332 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2333 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 }
2335 }
2336
Ricky Waiaca8a772019-04-04 16:01:06 +01002337 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2338 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 boolean fromRecents) {
2340
Ricky Waiaca8a772019-04-04 16:01:06 +01002341 final int callingPid = Binder.getCallingPid();
2342 final int callingUid = Binder.getCallingUid();
2343 if (!isSameApp(callingUid, callingPackage)) {
2344 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2345 + Binder.getCallingPid() + " as package " + callingPackage;
2346 Slog.w(TAG, msg);
2347 throw new SecurityException(msg);
2348 }
2349 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 SafeActivityOptions.abort(options);
2351 return;
2352 }
2353 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 WindowProcessController callerApp = null;
2355 if (appThread != null) {
2356 callerApp = getProcessController(appThread);
2357 }
2358 final ActivityStarter starter = getActivityStartController().obtainStarter(
2359 null /* intent */, "moveTaskToFront");
2360 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2361 -1, callerApp, null, false, null)) {
2362 boolean abort = !isBackgroundActivityStartsEnabled();
2363 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2364 if (abort) {
2365 return;
2366 }
2367 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002369 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 if (task == null) {
2371 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002372 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 return;
2374 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002375 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002377 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 return;
2379 }
2380 ActivityOptions realOptions = options != null
2381 ? options.getOptions(mStackSupervisor)
2382 : null;
2383 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2384 false /* forceNonResizable */);
2385
2386 final ActivityRecord topActivity = task.getTopActivity();
2387 if (topActivity != null) {
2388
2389 // We are reshowing a task, use a starting window to hide the initial draw delay
2390 // so the transition can start earlier.
2391 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2392 true /* taskSwitch */, fromRecents);
2393 }
2394 } finally {
2395 Binder.restoreCallingIdentity(origId);
2396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 }
2398
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 /**
2400 * Return true if callingUid is system, or packageName belongs to that callingUid.
2401 */
2402 boolean isSameApp(int callingUid, @Nullable String packageName) {
2403 try {
2404 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2405 if (packageName == null) {
2406 return false;
2407 }
2408 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2409 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2410 UserHandle.getUserId(callingUid));
2411 return UserHandle.isSameApp(callingUid, uid);
2412 }
2413 } catch (RemoteException e) {
2414 // Should not happen
2415 }
2416 return true;
2417 }
2418
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2420 int callingPid, int callingUid, String name) {
2421 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2422 return true;
2423 }
2424
2425 if (getRecentTasks().isCallerRecents(sourceUid)) {
2426 return true;
2427 }
2428
2429 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2430 if (perm == PackageManager.PERMISSION_GRANTED) {
2431 return true;
2432 }
2433 if (checkAllowAppSwitchUid(sourceUid)) {
2434 return true;
2435 }
2436
2437 // If the actual IPC caller is different from the logical source, then
2438 // also see if they are allowed to control app switches.
2439 if (callingUid != -1 && callingUid != sourceUid) {
2440 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2441 if (perm == PackageManager.PERMISSION_GRANTED) {
2442 return true;
2443 }
2444 if (checkAllowAppSwitchUid(callingUid)) {
2445 return true;
2446 }
2447 }
2448
2449 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2450 return false;
2451 }
2452
2453 private boolean checkAllowAppSwitchUid(int uid) {
2454 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2455 if (types != null) {
2456 for (int i = types.size() - 1; i >= 0; i--) {
2457 if (types.valueAt(i).intValue() == uid) {
2458 return true;
2459 }
2460 }
2461 }
2462 return false;
2463 }
2464
2465 @Override
2466 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2467 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2468 "setActivityController()");
2469 synchronized (mGlobalLock) {
2470 mController = controller;
2471 mControllerIsAMonkey = imAMonkey;
2472 Watchdog.getInstance().setActivityController(controller);
2473 }
2474 }
2475
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002476 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002477 synchronized (mGlobalLock) {
2478 return mController != null && mControllerIsAMonkey;
2479 }
2480 }
2481
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 @Override
2483 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2484 synchronized (mGlobalLock) {
2485 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2486 }
2487 }
2488
2489 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002490 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2491 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2492 }
2493
2494 @Override
2495 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2496 @WindowConfiguration.ActivityType int ignoreActivityType,
2497 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2498 final int callingUid = Binder.getCallingUid();
2499 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2500
2501 synchronized (mGlobalLock) {
2502 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2503
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002506 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002507 ignoreWindowingMode, callingUid, allowed);
2508 }
2509
2510 return list;
2511 }
2512
2513 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2515 synchronized (mGlobalLock) {
2516 final long origId = Binder.clearCallingIdentity();
2517 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2518 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002519 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002520 }
2521 Binder.restoreCallingIdentity(origId);
2522 }
2523 }
2524
2525 @Override
2526 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 ActivityStack stack = ActivityRecord.getStackLocked(token);
2529 if (stack != null) {
2530 return stack.willActivityBeVisibleLocked(token);
2531 }
2532 return false;
2533 }
2534 }
2535
2536 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002538 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 synchronized (mGlobalLock) {
2540 final long ident = Binder.clearCallingIdentity();
2541 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002542 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 if (task == null) {
2544 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2545 return;
2546 }
2547
2548 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2549 + " to stackId=" + stackId + " toTop=" + toTop);
2550
Wale Ogunwaled32da472018-11-16 07:19:28 -08002551 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 if (stack == null) {
2553 throw new IllegalStateException(
2554 "moveTaskToStack: No stack for stackId=" + stackId);
2555 }
2556 if (!stack.isActivityTypeStandardOrUndefined()) {
2557 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2558 + taskId + " to stack " + stackId);
2559 }
2560 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2563 }
2564 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2565 "moveTaskToStack");
2566 } finally {
2567 Binder.restoreCallingIdentity(ident);
2568 }
2569 }
2570 }
2571
2572 @Override
2573 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2574 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576
2577 final long ident = Binder.clearCallingIdentity();
2578 try {
2579 synchronized (mGlobalLock) {
2580 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002581 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 if (stack == null) {
2583 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2584 return;
2585 }
2586 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2587 throw new IllegalArgumentException("Stack: " + stackId
2588 + " doesn't support animated resize.");
2589 }
2590 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2591 animationDuration, false /* fromFullscreen */);
2592 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002593 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 if (stack == null) {
2595 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2596 return;
2597 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002598 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2600 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2601 }
2602 }
2603 } finally {
2604 Binder.restoreCallingIdentity(ident);
2605 }
2606 }
2607
wilsonshih5c4cf522019-01-25 09:03:47 +08002608 @Override
2609 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2610 int animationDuration) {
2611 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2612
2613 final long ident = Binder.clearCallingIdentity();
2614 try {
2615 synchronized (mGlobalLock) {
2616 if (xOffset == 0 && yOffset == 0) {
2617 return;
2618 }
2619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2620 if (stack == null) {
2621 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2622 return;
2623 }
2624 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2625 throw new IllegalArgumentException("Stack: " + stackId
2626 + " doesn't support animated resize.");
2627 }
2628 final Rect destBounds = new Rect();
2629 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002630 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002631 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2632 return;
2633 }
2634 destBounds.offset(xOffset, yOffset);
2635 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2636 animationDuration, false /* fromFullscreen */);
2637 }
2638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 /**
2643 * Moves the specified task to the primary-split-screen stack.
2644 *
2645 * @param taskId Id of task to move.
2646 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2647 * exist already. See
2648 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2649 * and
2650 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2651 * @param toTop If the task and stack should be moved to the top.
2652 * @param animate Whether we should play an animation for the moving the task.
2653 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2654 * stack. Pass {@code null} to use default bounds.
2655 * @param showRecents If the recents activity should be shown on the other side of the task
2656 * going into split-screen mode.
2657 */
2658 @Override
2659 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2660 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002661 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002662 "setTaskWindowingModeSplitScreenPrimary()");
2663 synchronized (mGlobalLock) {
2664 final long ident = Binder.clearCallingIdentity();
2665 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002666 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002667 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 if (task == null) {
2669 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2670 return false;
2671 }
2672 if (DEBUG_STACK) Slog.d(TAG_STACK,
2673 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2674 + " to createMode=" + createMode + " toTop=" + toTop);
2675 if (!task.isActivityTypeStandardOrUndefined()) {
2676 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2677 + " non-standard task " + taskId + " to split-screen windowing mode");
2678 }
2679
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002680 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002681 final int windowingMode = task.getWindowingMode();
2682 final ActivityStack stack = task.getStack();
2683 if (toTop) {
2684 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2685 }
2686 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002687 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2688 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 return windowingMode != task.getWindowingMode();
2690 } finally {
2691 Binder.restoreCallingIdentity(ident);
2692 }
2693 }
2694 }
2695
2696 /**
2697 * Removes stacks in the input windowing modes from the system if they are of activity type
2698 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2699 */
2700 @Override
2701 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002702 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 "removeStacksInWindowingModes()");
2704
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002708 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713 }
2714
2715 @Override
2716 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 "removeStacksWithActivityTypes()");
2719
2720 synchronized (mGlobalLock) {
2721 final long ident = Binder.clearCallingIdentity();
2722 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729
2730 @Override
2731 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2732 int userId) {
2733 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2735 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 final boolean detailed = checkGetTasksPermission(
2738 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2739 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 == PackageManager.PERMISSION_GRANTED;
2741
2742 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002743 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 callingUid);
2745 }
2746 }
2747
2748 @Override
2749 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002750 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 long ident = Binder.clearCallingIdentity();
2752 try {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002754 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 } finally {
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760
2761 @Override
2762 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002763 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 long ident = Binder.clearCallingIdentity();
2765 try {
2766 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002767 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 }
2769 } finally {
2770 Binder.restoreCallingIdentity(ident);
2771 }
2772 }
2773
2774 @Override
2775 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 final long callingUid = Binder.getCallingUid();
2778 final long origId = Binder.clearCallingIdentity();
2779 try {
2780 synchronized (mGlobalLock) {
2781 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002782 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2784 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2785 }
2786 } finally {
2787 Binder.restoreCallingIdentity(origId);
2788 }
2789 }
2790
2791 @Override
2792 public void startLockTaskModeByToken(IBinder token) {
2793 synchronized (mGlobalLock) {
2794 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2795 if (r == null) {
2796 return;
2797 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002798 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800 }
2801
2802 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002803 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 // This makes inner call to look as if it was initiated by system.
2806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002809 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002810 MATCH_TASK_IN_STACKS_ONLY);
2811 if (task == null) {
2812 return;
2813 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814
2815 // When starting lock task mode the stack must be in front and focused
2816 task.getStack().moveToFront("startSystemLockTaskMode");
2817 startLockTaskModeLocked(task, true /* isSystemCaller */);
2818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
2825 public void stopLockTaskModeByToken(IBinder token) {
2826 synchronized (mGlobalLock) {
2827 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2828 if (r == null) {
2829 return;
2830 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002831 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 }
2833 }
2834
2835 /**
2836 * This API should be called by SystemUI only when user perform certain action to dismiss
2837 * lock task mode. We should only dismiss pinned lock task mode in this case.
2838 */
2839 @Override
2840 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2843 }
2844
2845 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2846 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2847 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2848 return;
2849 }
2850
Wale Ogunwaled32da472018-11-16 07:19:28 -08002851 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 if (stack == null || task != stack.topTask()) {
2853 throw new IllegalArgumentException("Invalid task, not in foreground");
2854 }
2855
2856 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2857 // system or a specific app.
2858 // * System-initiated requests will only start the pinned mode (screen pinning)
2859 // * App-initiated requests
2860 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2861 // - will start the pinned mode, otherwise
2862 final int callingUid = Binder.getCallingUid();
2863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002866 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002868 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 } finally {
2870 Binder.restoreCallingIdentity(ident);
2871 }
2872 }
2873
2874 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2875 final int callingUid = Binder.getCallingUid();
2876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002879 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2882 // task and jumping straight into a call in the case of emergency call back.
2883 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2884 if (tm != null) {
2885 tm.showInCallScreen(false);
2886 }
2887 } finally {
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891
2892 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002893 public void updateLockTaskPackages(int userId, String[] packages) {
2894 final int callingUid = Binder.getCallingUid();
2895 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2896 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2897 "updateLockTaskPackages()");
2898 }
2899 synchronized (this) {
2900 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2901 + Arrays.toString(packages));
2902 getLockTaskController().updateLockTaskPackages(userId, packages);
2903 }
2904 }
2905
2906 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 public boolean isInLockTaskMode() {
2908 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2909 }
2910
2911 @Override
2912 public int getLockTaskModeState() {
2913 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002914 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 }
2916 }
2917
2918 @Override
2919 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2920 synchronized (mGlobalLock) {
2921 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2922 if (r != null) {
2923 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002926 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929 }
2930
2931 @Override
2932 public Bundle getActivityOptions(IBinder token) {
2933 final long origId = Binder.clearCallingIdentity();
2934 try {
2935 synchronized (mGlobalLock) {
2936 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2937 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002938 final ActivityOptions activityOptions = r.takeOptionsLocked(
2939 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 return activityOptions == null ? null : activityOptions.toBundle();
2941 }
2942 return null;
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(origId);
2946 }
2947 }
2948
2949 @Override
2950 public List<IBinder> getAppTasks(String callingPackage) {
2951 int callingUid = Binder.getCallingUid();
2952 long ident = Binder.clearCallingIdentity();
2953 try {
2954 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002955 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
2963 public void finishVoiceTask(IVoiceInteractionSession session) {
2964 synchronized (mGlobalLock) {
2965 final long origId = Binder.clearCallingIdentity();
2966 try {
2967 // TODO: VI Consider treating local voice interactions and voice tasks
2968 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002969 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 } finally {
2971 Binder.restoreCallingIdentity(origId);
2972 }
2973 }
2974
2975 }
2976
2977 @Override
2978 public boolean isTopOfTask(IBinder token) {
2979 synchronized (mGlobalLock) {
2980 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002981 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 }
2983 }
2984
2985 @Override
2986 public void notifyLaunchTaskBehindComplete(IBinder token) {
2987 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2988 }
2989
2990 @Override
2991 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002992 mH.post(() -> {
2993 synchronized (mGlobalLock) {
2994 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002995 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002996 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002997 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002998 } catch (RemoteException e) {
2999 }
3000 }
3001 }
3002
3003 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005
3006 /** Called from an app when assist data is ready. */
3007 @Override
3008 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3009 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 synchronized (pae) {
3012 pae.result = extras;
3013 pae.structure = structure;
3014 pae.content = content;
3015 if (referrer != null) {
3016 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3017 }
3018 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003019 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3021 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 structure.setHomeActivity(pae.isHome);
3023 }
3024 pae.haveResult = true;
3025 pae.notifyAll();
3026 if (pae.intent == null && pae.receiver == null) {
3027 // Caller is just waiting for the result.
3028 return;
3029 }
3030 }
3031 // We are now ready to launch the assist activity.
3032 IAssistDataReceiver sendReceiver = null;
3033 Bundle sendBundle = null;
3034 synchronized (mGlobalLock) {
3035 buildAssistBundleLocked(pae, extras);
3036 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003037 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 if (!exists) {
3039 // Timed out.
3040 return;
3041 }
3042
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 // Caller wants result sent back to them.
3045 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003046 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3047 pae.activity.getTaskRecord().taskId);
3048 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3049 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3051 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3052 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3053 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3054 }
3055 }
3056 if (sendReceiver != null) {
3057 try {
3058 sendReceiver.onHandleAssistData(sendBundle);
3059 } catch (RemoteException e) {
3060 }
3061 return;
3062 }
3063
3064 final long ident = Binder.clearCallingIdentity();
3065 try {
3066 if (TextUtils.equals(pae.intent.getAction(),
3067 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3068 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003069
3070 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 } else {
3072 pae.intent.replaceExtras(pae.extras);
3073 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3074 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3075 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003076 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077
3078 try {
3079 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3080 } catch (ActivityNotFoundException e) {
3081 Slog.w(TAG, "No activity to handle assist action.", e);
3082 }
3083 }
3084 } finally {
3085 Binder.restoreCallingIdentity(ident);
3086 }
3087 }
3088
Marvin Ramin830d4e32019-03-12 13:16:58 +01003089 /**
3090 * Workaround for historical API which starts the Assist service with a non-foreground
3091 * {@code startService()} call.
3092 */
3093 private void startVoiceInteractionServiceAsUser(
3094 Intent intent, int userHandle, String reason) {
3095 // Resolve the intent to find out which package we need to whitelist.
3096 ResolveInfo resolveInfo =
3097 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3098 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3099 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3100 return;
3101 }
3102 intent.setPackage(resolveInfo.serviceInfo.packageName);
3103
3104 // Whitelist background services temporarily.
3105 LocalServices.getService(DeviceIdleController.LocalService.class)
3106 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3107 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3108
3109 // Finally, try to start the service.
3110 try {
3111 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3112 } catch (RuntimeException e) {
3113 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3114 }
3115 }
3116
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 @Override
3118 public int addAppTask(IBinder activityToken, Intent intent,
3119 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3120 final int callingUid = Binder.getCallingUid();
3121 final long callingIdent = Binder.clearCallingIdentity();
3122
3123 try {
3124 synchronized (mGlobalLock) {
3125 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3126 if (r == null) {
3127 throw new IllegalArgumentException("Activity does not exist; token="
3128 + activityToken);
3129 }
3130 ComponentName comp = intent.getComponent();
3131 if (comp == null) {
3132 throw new IllegalArgumentException("Intent " + intent
3133 + " must specify explicit component");
3134 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 if (thumbnail.getWidth() != mThumbnailWidth
3136 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 throw new IllegalArgumentException("Bad thumbnail size: got "
3138 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 }
3141 if (intent.getSelector() != null) {
3142 intent.setSelector(null);
3143 }
3144 if (intent.getSourceBounds() != null) {
3145 intent.setSourceBounds(null);
3146 }
3147 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3148 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3149 // The caller has added this as an auto-remove task... that makes no
3150 // sense, so turn off auto-remove.
3151 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3152 }
3153 }
3154 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3155 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3156 if (ainfo.applicationInfo.uid != callingUid) {
3157 throw new SecurityException(
3158 "Can't add task for another application: target uid="
3159 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3160 }
3161
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003162 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003164 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003166 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003167 // The app has too many tasks already and we can't add any more
3168 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3169 return INVALID_TASK_ID;
3170 }
3171 task.lastTaskDescription.copyFrom(description);
3172
3173 // TODO: Send the thumbnail to WM to store it.
3174
3175 return task.taskId;
3176 }
3177 } finally {
3178 Binder.restoreCallingIdentity(callingIdent);
3179 }
3180 }
3181
3182 @Override
3183 public Point getAppTaskThumbnailSize() {
3184 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 }
3187 }
3188
3189 @Override
3190 public void setTaskResizeable(int taskId, int resizeableMode) {
3191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003192 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3194 if (task == null) {
3195 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3196 return;
3197 }
3198 task.setResizeMode(resizeableMode);
3199 }
3200 }
3201
3202 @Override
3203 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003204 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 long ident = Binder.clearCallingIdentity();
3206 try {
3207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003208 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003209 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 if (task == null) {
3211 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3212 return;
3213 }
3214 // Place the task in the right stack if it isn't there already based on
3215 // the requested bounds.
3216 // The stack transition logic is:
3217 // - a null bounds on a freeform task moves that task to fullscreen
3218 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3219 // that task to freeform
3220 // - otherwise the task is not moved
3221 ActivityStack stack = task.getStack();
3222 if (!task.getWindowConfiguration().canResizeTask()) {
3223 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3224 }
3225 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3226 stack = stack.getDisplay().getOrCreateStack(
3227 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3228 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3229 stack = stack.getDisplay().getOrCreateStack(
3230 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3231 }
3232
3233 // Reparent the task to the right stack if necessary
3234 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3235 if (stack != task.getStack()) {
3236 // Defer resume until the task is resized below
3237 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3238 DEFER_RESUME, "resizeTask");
3239 preserveWindow = false;
3240 }
3241
3242 // After reparenting (which only resizes the task to the stack bounds), resize the
3243 // task to the actual bounds provided
3244 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3245 }
3246 } finally {
3247 Binder.restoreCallingIdentity(ident);
3248 }
3249 }
3250
3251 @Override
3252 public boolean releaseActivityInstance(IBinder token) {
3253 synchronized (mGlobalLock) {
3254 final long origId = Binder.clearCallingIdentity();
3255 try {
3256 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3257 if (r == null) {
3258 return false;
3259 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003260 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 } finally {
3262 Binder.restoreCallingIdentity(origId);
3263 }
3264 }
3265 }
3266
3267 @Override
3268 public void releaseSomeActivities(IApplicationThread appInt) {
3269 synchronized (mGlobalLock) {
3270 final long origId = Binder.clearCallingIdentity();
3271 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003272 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003273 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003274 } finally {
3275 Binder.restoreCallingIdentity(origId);
3276 }
3277 }
3278 }
3279
3280 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003281 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003282 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 != PackageManager.PERMISSION_GRANTED) {
3284 throw new SecurityException("Requires permission "
3285 + android.Manifest.permission.DEVICE_POWER);
3286 }
3287
3288 synchronized (mGlobalLock) {
3289 long ident = Binder.clearCallingIdentity();
3290 if (mKeyguardShown != keyguardShowing) {
3291 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003292 final Message msg = PooledLambda.obtainMessage(
3293 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3294 keyguardShowing);
3295 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 }
3297 try {
wilsonshih177261f2019-02-22 12:02:18 +08003298 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 } finally {
3300 Binder.restoreCallingIdentity(ident);
3301 }
3302 }
3303
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003304 mH.post(() -> {
3305 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3306 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3307 }
3308 });
3309 }
3310
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003311 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 mH.post(() -> {
3313 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3314 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3315 }
3316 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 }
3318
3319 @Override
3320 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003321 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3322 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323
3324 final File passedIconFile = new File(filePath);
3325 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3326 passedIconFile.getName());
3327 if (!legitIconFile.getPath().equals(filePath)
3328 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3329 throw new IllegalArgumentException("Bad file path: " + filePath
3330 + " passed for userId " + userId);
3331 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003332 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 }
3334
3335 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003336 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3338 final ActivityOptions activityOptions = safeOptions != null
3339 ? safeOptions.getOptions(mStackSupervisor)
3340 : null;
3341 if (activityOptions == null
3342 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3343 || activityOptions.getCustomInPlaceResId() == 0) {
3344 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3345 "with valid animation");
3346 }
lumark588a3e82018-07-20 18:53:54 +08003347 // Get top display of front most application.
3348 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3349 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003350 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3351 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3352 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003353 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003354 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003355 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 }
3357
3358 @Override
3359 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003360 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 synchronized (mGlobalLock) {
3362 final long ident = Binder.clearCallingIdentity();
3363 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003364 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 if (stack == null) {
3366 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3367 return;
3368 }
3369 if (!stack.isActivityTypeStandardOrUndefined()) {
3370 throw new IllegalArgumentException(
3371 "Removing non-standard stack is not allowed.");
3372 }
3373 mStackSupervisor.removeStack(stack);
3374 } finally {
3375 Binder.restoreCallingIdentity(ident);
3376 }
3377 }
3378 }
3379
3380 @Override
3381 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383
3384 synchronized (mGlobalLock) {
3385 final long ident = Binder.clearCallingIdentity();
3386 try {
3387 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3388 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003389 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 } finally {
3391 Binder.restoreCallingIdentity(ident);
3392 }
3393 }
3394 }
3395
3396 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003397 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 synchronized (mGlobalLock) {
3399 long ident = Binder.clearCallingIdentity();
3400 try {
3401 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3402 if (r == null) {
3403 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003404 "toggleFreeformWindowingMode: No activity record matching token="
3405 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 }
3407
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003408 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003409 if (stack == null) {
3410 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3411 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
Yunfan Chend967af82019-01-17 18:30:18 +09003414 if (!stack.inFreeformWindowingMode()
3415 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3416 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3417 + "toggle between fullscreen and freeform.");
3418 }
3419
3420 if (stack.inFreeformWindowingMode()) {
3421 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003422 } else if (stack.getParent().inFreeformWindowingMode()) {
3423 // If the window is on a freeform display, set it to undefined. It will be
3424 // resolved to freeform and it can adjust windowing mode when the display mode
3425 // changes in runtime.
3426 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003427 } else {
3428 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3429 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434 }
3435
3436 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3437 @Override
3438 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003439 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003441 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 }
3443
3444 /** Unregister a task stack listener so that it stops receiving callbacks. */
3445 @Override
3446 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003447 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003449 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 }
3451
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 @Override
3453 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3454 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3455 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3456 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3457 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3458 }
3459
3460 @Override
3461 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3462 IBinder activityToken, int flags) {
3463 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3464 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3465 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3466 }
3467
3468 @Override
3469 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3470 Bundle args) {
3471 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3472 true /* focused */, true /* newSessionId */, userHandle, args,
3473 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3474 }
3475
3476 @Override
3477 public Bundle getAssistContextExtras(int requestType) {
3478 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3479 null, null, true /* focused */, true /* newSessionId */,
3480 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3481 if (pae == null) {
3482 return null;
3483 }
3484 synchronized (pae) {
3485 while (!pae.haveResult) {
3486 try {
3487 pae.wait();
3488 } catch (InterruptedException e) {
3489 }
3490 }
3491 }
3492 synchronized (mGlobalLock) {
3493 buildAssistBundleLocked(pae, pae.result);
3494 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003496 }
3497 return pae.extras;
3498 }
3499
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003500 /**
3501 * Binder IPC calls go through the public entry point.
3502 * This can be called with or without the global lock held.
3503 */
3504 private static int checkCallingPermission(String permission) {
3505 return checkPermission(
3506 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3507 }
3508
3509 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003510 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003511 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3512 mAmInternal.enforceCallingPermission(permission, func);
3513 }
3514 }
3515
3516 @VisibleForTesting
3517 int checkGetTasksPermission(String permission, int pid, int uid) {
3518 return checkPermission(permission, pid, uid);
3519 }
3520
3521 static int checkPermission(String permission, int pid, int uid) {
3522 if (permission == null) {
3523 return PackageManager.PERMISSION_DENIED;
3524 }
3525 return checkComponentPermission(permission, pid, uid, -1, true);
3526 }
3527
Wale Ogunwale214f3482018-10-04 11:00:47 -07003528 public static int checkComponentPermission(String permission, int pid, int uid,
3529 int owningUid, boolean exported) {
3530 return ActivityManagerService.checkComponentPermission(
3531 permission, pid, uid, owningUid, exported);
3532 }
3533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003534 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3535 if (getRecentTasks().isCallerRecents(callingUid)) {
3536 // Always allow the recents component to get tasks
3537 return true;
3538 }
3539
3540 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3541 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3542 if (!allowed) {
3543 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3544 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3545 // Temporary compatibility: some existing apps on the system image may
3546 // still be requesting the old permission and not switched to the new
3547 // one; if so, we'll still allow them full access. This means we need
3548 // to see if they are holding the old permission and are a system app.
3549 try {
3550 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3551 allowed = true;
3552 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3553 + " is using old GET_TASKS but privileged; allowing");
3554 }
3555 } catch (RemoteException e) {
3556 }
3557 }
3558 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3559 + " does not hold REAL_GET_TASKS; limiting output");
3560 }
3561 return allowed;
3562 }
3563
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003564 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3565 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3566 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3567 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003568 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003569 "enqueueAssistContext()");
3570
3571 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003572 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 if (activity == null) {
3574 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3575 return null;
3576 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003577 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3579 return null;
3580 }
3581 if (focused) {
3582 if (activityToken != null) {
3583 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3584 if (activity != caller) {
3585 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3586 + " is not current top " + activity);
3587 return null;
3588 }
3589 }
3590 } else {
3591 activity = ActivityRecord.forTokenLocked(activityToken);
3592 if (activity == null) {
3593 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3594 + " couldn't be found");
3595 return null;
3596 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003597 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3599 return null;
3600 }
3601 }
3602
3603 PendingAssistExtras pae;
3604 Bundle extras = new Bundle();
3605 if (args != null) {
3606 extras.putAll(args);
3607 }
3608 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003609 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610
3611 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3612 userHandle);
3613 pae.isHome = activity.isActivityTypeHome();
3614
3615 // Increment the sessionId if necessary
3616 if (newSessionId) {
3617 mViSessionId++;
3618 }
3619 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003620 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3621 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003623 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 } catch (RemoteException e) {
3625 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3626 return null;
3627 }
3628 return pae;
3629 }
3630 }
3631
3632 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3633 if (result != null) {
3634 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3635 }
3636 if (pae.hint != null) {
3637 pae.extras.putBoolean(pae.hint, true);
3638 }
3639 }
3640
3641 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3642 IAssistDataReceiver receiver;
3643 synchronized (mGlobalLock) {
3644 mPendingAssistExtras.remove(pae);
3645 receiver = pae.receiver;
3646 }
3647 if (receiver != null) {
3648 // Caller wants result sent back to them.
3649 Bundle sendBundle = new Bundle();
3650 // At least return the receiver extras
3651 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3652 try {
3653 pae.receiver.onHandleAssistData(sendBundle);
3654 } catch (RemoteException e) {
3655 }
3656 }
3657 }
3658
3659 public class PendingAssistExtras extends Binder implements Runnable {
3660 public final ActivityRecord activity;
3661 public boolean isHome;
3662 public final Bundle extras;
3663 public final Intent intent;
3664 public final String hint;
3665 public final IAssistDataReceiver receiver;
3666 public final int userHandle;
3667 public boolean haveResult = false;
3668 public Bundle result = null;
3669 public AssistStructure structure = null;
3670 public AssistContent content = null;
3671 public Bundle receiverExtras;
3672
3673 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3674 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3675 int _userHandle) {
3676 activity = _activity;
3677 extras = _extras;
3678 intent = _intent;
3679 hint = _hint;
3680 receiver = _receiver;
3681 receiverExtras = _receiverExtras;
3682 userHandle = _userHandle;
3683 }
3684
3685 @Override
3686 public void run() {
3687 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3688 synchronized (this) {
3689 haveResult = true;
3690 notifyAll();
3691 }
3692 pendingAssistExtrasTimedOut(this);
3693 }
3694 }
3695
3696 @Override
3697 public boolean isAssistDataAllowedOnCurrentActivity() {
3698 int userId;
3699 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003700 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003701 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3702 return false;
3703 }
3704
3705 final ActivityRecord activity = focusedStack.getTopActivity();
3706 if (activity == null) {
3707 return false;
3708 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003709 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 }
3711 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3712 }
3713
3714 @Override
3715 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3716 long ident = Binder.clearCallingIdentity();
3717 try {
3718 synchronized (mGlobalLock) {
3719 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003720 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 if (top != caller) {
3722 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3723 + " is not current top " + top);
3724 return false;
3725 }
3726 if (!top.nowVisible) {
3727 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3728 + " is not visible");
3729 return false;
3730 }
3731 }
3732 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3733 token);
3734 } finally {
3735 Binder.restoreCallingIdentity(ident);
3736 }
3737 }
3738
3739 @Override
3740 public boolean isRootVoiceInteraction(IBinder token) {
3741 synchronized (mGlobalLock) {
3742 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3743 if (r == null) {
3744 return false;
3745 }
3746 return r.rootVoiceInteraction;
3747 }
3748 }
3749
Wale Ogunwalef6733932018-06-27 05:14:34 -07003750 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3751 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3752 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3753 if (activityToCallback == null) return;
3754 activityToCallback.setVoiceSessionLocked(voiceSession);
3755
3756 // Inform the activity
3757 try {
3758 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3759 voiceInteractor);
3760 long token = Binder.clearCallingIdentity();
3761 try {
3762 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3763 } finally {
3764 Binder.restoreCallingIdentity(token);
3765 }
3766 // TODO: VI Should we cache the activity so that it's easier to find later
3767 // rather than scan through all the stacks and activities?
3768 } catch (RemoteException re) {
3769 activityToCallback.clearVoiceSessionLocked();
3770 // TODO: VI Should this terminate the voice session?
3771 }
3772 }
3773
3774 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3775 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3776 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3777 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3778 boolean wasRunningVoice = mRunningVoice != null;
3779 mRunningVoice = session;
3780 if (!wasRunningVoice) {
3781 mVoiceWakeLock.acquire();
3782 updateSleepIfNeededLocked();
3783 }
3784 }
3785 }
3786
3787 void finishRunningVoiceLocked() {
3788 if (mRunningVoice != null) {
3789 mRunningVoice = null;
3790 mVoiceWakeLock.release();
3791 updateSleepIfNeededLocked();
3792 }
3793 }
3794
3795 @Override
3796 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3797 synchronized (mGlobalLock) {
3798 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3799 if (keepAwake) {
3800 mVoiceWakeLock.acquire();
3801 } else {
3802 mVoiceWakeLock.release();
3803 }
3804 }
3805 }
3806 }
3807
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 @Override
3809 public ComponentName getActivityClassForToken(IBinder token) {
3810 synchronized (mGlobalLock) {
3811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3812 if (r == null) {
3813 return null;
3814 }
3815 return r.intent.getComponent();
3816 }
3817 }
3818
3819 @Override
3820 public String getPackageForToken(IBinder token) {
3821 synchronized (mGlobalLock) {
3822 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3823 if (r == null) {
3824 return null;
3825 }
3826 return r.packageName;
3827 }
3828 }
3829
3830 @Override
3831 public void showLockTaskEscapeMessage(IBinder token) {
3832 synchronized (mGlobalLock) {
3833 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3834 if (r == null) {
3835 return;
3836 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003837 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839 }
3840
3841 @Override
3842 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003843 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 final long token = Binder.clearCallingIdentity();
3845 try {
3846 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003847 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 }
3849 } finally {
3850 Binder.restoreCallingIdentity(token);
3851 }
3852 }
3853
3854 /**
3855 * Try to place task to provided position. The final position might be different depending on
3856 * current user and stacks state. The task will be moved to target stack if it's currently in
3857 * different stack.
3858 */
3859 @Override
3860 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003861 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 synchronized (mGlobalLock) {
3863 long ident = Binder.clearCallingIdentity();
3864 try {
3865 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3866 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003867 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 if (task == null) {
3869 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3870 + taskId);
3871 }
3872
Wale Ogunwaled32da472018-11-16 07:19:28 -08003873 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874
3875 if (stack == null) {
3876 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3877 + stackId);
3878 }
3879 if (!stack.isActivityTypeStandardOrUndefined()) {
3880 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3881 + " the position of task " + taskId + " in/to non-standard stack");
3882 }
3883
3884 // TODO: Have the callers of this API call a separate reparent method if that is
3885 // what they intended to do vs. having this method also do reparenting.
3886 if (task.getStack() == stack) {
3887 // Change position in current stack.
3888 stack.positionChildAt(task, position);
3889 } else {
3890 // Reparent to new stack.
3891 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3892 !DEFER_RESUME, "positionTaskInStack");
3893 }
3894 } finally {
3895 Binder.restoreCallingIdentity(ident);
3896 }
3897 }
3898 }
3899
3900 @Override
3901 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3902 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3903 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3904 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3905 synchronized (mGlobalLock) {
3906 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3907 if (record == null) {
3908 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3909 + "found for: " + token);
3910 }
3911 record.setSizeConfigurations(horizontalSizeConfiguration,
3912 verticalSizeConfigurations, smallestSizeConfigurations);
3913 }
3914 }
3915
3916 /**
3917 * Dismisses split-screen multi-window mode.
3918 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3919 */
3920 @Override
3921 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3924 final long ident = Binder.clearCallingIdentity();
3925 try {
3926 synchronized (mGlobalLock) {
3927 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003928 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 if (stack == null) {
3930 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3931 return;
3932 }
3933
3934 if (toTop) {
3935 // Caller wants the current split-screen primary stack to be the top stack after
3936 // it goes fullscreen, so move it to the front.
3937 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003938 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 // In this case the current split-screen primary stack shouldn't be the top
3940 // stack after it goes fullscreen, but it current has focus, so we move the
3941 // focus to the top-most split-screen secondary stack next to it.
3942 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3943 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3944 if (otherStack != null) {
3945 otherStack.moveToFront("dismissSplitScreenMode_other");
3946 }
3947 }
3948
Evan Rosky10475742018-09-05 19:02:48 -07003949 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 }
3951 } finally {
3952 Binder.restoreCallingIdentity(ident);
3953 }
3954 }
3955
3956 /**
3957 * Dismisses Pip
3958 * @param animate True if the dismissal should be animated.
3959 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3960 * default animation duration should be used.
3961 */
3962 @Override
3963 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003964 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 final long ident = Binder.clearCallingIdentity();
3966 try {
3967 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003968 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003969 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 if (stack == null) {
3971 Slog.w(TAG, "dismissPip: pinned stack not found.");
3972 return;
3973 }
3974 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3975 throw new IllegalArgumentException("Stack: " + stack
3976 + " doesn't support animated resize.");
3977 }
3978 if (animate) {
3979 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3980 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3981 } else {
3982 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3983 }
3984 }
3985 } finally {
3986 Binder.restoreCallingIdentity(ident);
3987 }
3988 }
3989
3990 @Override
3991 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 synchronized (mGlobalLock) {
3994 mSuppressResizeConfigChanges = suppress;
3995 }
3996 }
3997
3998 /**
3999 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4000 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4001 * activity and clearing the task at the same time.
4002 */
4003 @Override
4004 // TODO: API should just be about changing windowing modes...
4005 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 "moveTasksToFullscreenStack()");
4008 synchronized (mGlobalLock) {
4009 final long origId = Binder.clearCallingIdentity();
4010 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004011 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 if (stack != null){
4013 if (!stack.isActivityTypeStandardOrUndefined()) {
4014 throw new IllegalArgumentException(
4015 "You can't move tasks from non-standard stacks.");
4016 }
4017 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4018 }
4019 } finally {
4020 Binder.restoreCallingIdentity(origId);
4021 }
4022 }
4023 }
4024
4025 /**
4026 * Moves the top activity in the input stackId to the pinned stack.
4027 *
4028 * @param stackId Id of stack to move the top activity to pinned stack.
4029 * @param bounds Bounds to use for pinned stack.
4030 *
4031 * @return True if the top activity of the input stack was successfully moved to the pinned
4032 * stack.
4033 */
4034 @Override
4035 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 "moveTopActivityToPinnedStack()");
4038 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4041 + "Device doesn't support picture-in-picture mode");
4042 }
4043
4044 long ident = Binder.clearCallingIdentity();
4045 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004046 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 } finally {
4048 Binder.restoreCallingIdentity(ident);
4049 }
4050 }
4051 }
4052
4053 @Override
4054 public boolean isInMultiWindowMode(IBinder token) {
4055 final long origId = Binder.clearCallingIdentity();
4056 try {
4057 synchronized (mGlobalLock) {
4058 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4059 if (r == null) {
4060 return false;
4061 }
4062 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4063 return r.inMultiWindowMode();
4064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(origId);
4067 }
4068 }
4069
4070 @Override
4071 public boolean isInPictureInPictureMode(IBinder token) {
4072 final long origId = Binder.clearCallingIdentity();
4073 try {
4074 synchronized (mGlobalLock) {
4075 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4076 }
4077 } finally {
4078 Binder.restoreCallingIdentity(origId);
4079 }
4080 }
4081
4082 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004083 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4084 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 return false;
4086 }
4087
4088 // If we are animating to fullscreen then we have already dispatched the PIP mode
4089 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004090 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4091 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 }
4093
4094 @Override
4095 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4096 final long origId = Binder.clearCallingIdentity();
4097 try {
4098 synchronized (mGlobalLock) {
4099 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4100 "enterPictureInPictureMode", token, params);
4101
4102 // If the activity is already in picture in picture mode, then just return early
4103 if (isInPictureInPictureMode(r)) {
4104 return true;
4105 }
4106
4107 // Activity supports picture-in-picture, now check that we can enter PiP at this
4108 // point, if it is
4109 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4110 false /* beforeStopping */)) {
4111 return false;
4112 }
4113
4114 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 synchronized (mGlobalLock) {
4116 // Only update the saved args from the args that are set
4117 r.pictureInPictureArgs.copyOnlySet(params);
4118 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4119 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4120 // Adjust the source bounds by the insets for the transition down
4121 final Rect sourceBounds = new Rect(
4122 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004123 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004124 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004125 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 stack.setPictureInPictureAspectRatio(aspectRatio);
4127 stack.setPictureInPictureActions(actions);
4128 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4129 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4130 logPictureInPictureArgs(params);
4131 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 };
4133
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004134 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 // If the keyguard is showing or occluded, then try and dismiss it before
4136 // entering picture-in-picture (this will prompt the user to authenticate if the
4137 // device is currently locked).
4138 dismissKeyguard(token, new KeyguardDismissCallback() {
4139 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004140 public void onDismissSucceeded() {
4141 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 }
4143 }, null /* message */);
4144 } else {
4145 // Enter picture in picture immediately otherwise
4146 enterPipRunnable.run();
4147 }
4148 return true;
4149 }
4150 } finally {
4151 Binder.restoreCallingIdentity(origId);
4152 }
4153 }
4154
4155 @Override
4156 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4157 final long origId = Binder.clearCallingIdentity();
4158 try {
4159 synchronized (mGlobalLock) {
4160 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4161 "setPictureInPictureParams", token, params);
4162
4163 // Only update the saved args from the args that are set
4164 r.pictureInPictureArgs.copyOnlySet(params);
4165 if (r.inPinnedWindowingMode()) {
4166 // If the activity is already in picture-in-picture, update the pinned stack now
4167 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4168 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 if (!stack.isAnimatingBoundsToFullscreen()) {
4171 stack.setPictureInPictureAspectRatio(
4172 r.pictureInPictureArgs.getAspectRatio());
4173 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4174 }
4175 }
4176 logPictureInPictureArgs(params);
4177 }
4178 } finally {
4179 Binder.restoreCallingIdentity(origId);
4180 }
4181 }
4182
4183 @Override
4184 public int getMaxNumPictureInPictureActions(IBinder token) {
4185 // Currently, this is a static constant, but later, we may change this to be dependent on
4186 // the context of the activity
4187 return 3;
4188 }
4189
4190 private void logPictureInPictureArgs(PictureInPictureParams params) {
4191 if (params.hasSetActions()) {
4192 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4193 params.getActions().size());
4194 }
4195 if (params.hasSetAspectRatio()) {
4196 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4197 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4198 MetricsLogger.action(lm);
4199 }
4200 }
4201
4202 /**
4203 * Checks the state of the system and the activity associated with the given {@param token} to
4204 * verify that picture-in-picture is supported for that activity.
4205 *
4206 * @return the activity record for the given {@param token} if all the checks pass.
4207 */
4208 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4209 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 throw new IllegalStateException(caller
4212 + ": Device doesn't support picture-in-picture mode.");
4213 }
4214
4215 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4216 if (r == null) {
4217 throw new IllegalStateException(caller
4218 + ": Can't find activity for token=" + token);
4219 }
4220
4221 if (!r.supportsPictureInPicture()) {
4222 throw new IllegalStateException(caller
4223 + ": Current activity does not support picture-in-picture.");
4224 }
4225
4226 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004227 && !mWindowManager.isValidPictureInPictureAspectRatio(
4228 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 final float minAspectRatio = mContext.getResources().getFloat(
4230 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4231 final float maxAspectRatio = mContext.getResources().getFloat(
4232 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4233 throw new IllegalArgumentException(String.format(caller
4234 + ": Aspect ratio is too extreme (must be between %f and %f).",
4235 minAspectRatio, maxAspectRatio));
4236 }
4237
4238 // Truncate the number of actions if necessary
4239 params.truncateActions(getMaxNumPictureInPictureActions(token));
4240
4241 return r;
4242 }
4243
4244 @Override
4245 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004246 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 synchronized (mGlobalLock) {
4248 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4249 if (r == null) {
4250 throw new IllegalArgumentException("Activity does not exist; token="
4251 + activityToken);
4252 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004253 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
4255 }
4256
4257 @Override
4258 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4259 Rect tempDockedTaskInsetBounds,
4260 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 long ident = Binder.clearCallingIdentity();
4263 try {
4264 synchronized (mGlobalLock) {
4265 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4266 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4267 PRESERVE_WINDOWS);
4268 }
4269 } finally {
4270 Binder.restoreCallingIdentity(ident);
4271 }
4272 }
4273
4274 @Override
4275 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 final long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
4280 mStackSupervisor.setSplitScreenResizing(resizing);
4281 }
4282 } finally {
4283 Binder.restoreCallingIdentity(ident);
4284 }
4285 }
4286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 /**
4288 * Check that we have the features required for VR-related API calls, and throw an exception if
4289 * not.
4290 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004291 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 if (!mContext.getPackageManager().hasSystemFeature(
4293 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4294 throw new UnsupportedOperationException("VR mode not supported on this device!");
4295 }
4296 }
4297
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 @Override
4299 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004300 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301
4302 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4303
4304 ActivityRecord r;
4305 synchronized (mGlobalLock) {
4306 r = ActivityRecord.isInStackLocked(token);
4307 }
4308
4309 if (r == null) {
4310 throw new IllegalArgumentException();
4311 }
4312
4313 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004314 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 VrManagerInternal.NO_ERROR) {
4316 return err;
4317 }
4318
4319 // Clear the binder calling uid since this path may call moveToTask().
4320 final long callingId = Binder.clearCallingIdentity();
4321 try {
4322 synchronized (mGlobalLock) {
4323 r.requestedVrComponent = (enabled) ? packageName : null;
4324
4325 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004326 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004327 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 }
4329 return 0;
4330 }
4331 } finally {
4332 Binder.restoreCallingIdentity(callingId);
4333 }
4334 }
4335
4336 @Override
4337 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4338 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4339 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004340 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4342 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4343 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004344 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 || activity.voiceSession != null) {
4346 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4347 return;
4348 }
4349 if (activity.pendingVoiceInteractionStart) {
4350 Slog.w(TAG, "Pending start of voice interaction already.");
4351 return;
4352 }
4353 activity.pendingVoiceInteractionStart = true;
4354 }
4355 LocalServices.getService(VoiceInteractionManagerInternal.class)
4356 .startLocalVoiceInteraction(callingActivity, options);
4357 }
4358
4359 @Override
4360 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4361 LocalServices.getService(VoiceInteractionManagerInternal.class)
4362 .stopLocalVoiceInteraction(callingActivity);
4363 }
4364
4365 @Override
4366 public boolean supportsLocalVoiceInteraction() {
4367 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4368 .supportsLocalVoiceInteraction();
4369 }
4370
4371 /** Notifies all listeners when the pinned stack animation starts. */
4372 @Override
4373 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004374 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 }
4376
4377 /** Notifies all listeners when the pinned stack animation ends. */
4378 @Override
4379 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004380 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 }
4382
4383 @Override
4384 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 final long ident = Binder.clearCallingIdentity();
4387 try {
4388 synchronized (mGlobalLock) {
4389 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4390 }
4391 } finally {
4392 Binder.restoreCallingIdentity(ident);
4393 }
4394 }
4395
4396 @Override
4397 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399
4400 synchronized (mGlobalLock) {
4401 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004402 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 // Call might come when display is not yet added or has already been removed.
4404 if (DEBUG_CONFIGURATION) {
4405 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4406 + displayId);
4407 }
4408 return false;
4409 }
4410
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004417 final Message msg = PooledLambda.obtainMessage(
4418 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4419 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 final long origId = Binder.clearCallingIdentity();
4423 try {
4424 if (values != null) {
4425 Settings.System.clearConfiguration(values);
4426 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004427 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4429 return mTmpUpdateConfigurationResult.changes != 0;
4430 } finally {
4431 Binder.restoreCallingIdentity(origId);
4432 }
4433 }
4434 }
4435
4436 @Override
4437 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439
4440 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 }
4445
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004447 final Message msg = PooledLambda.obtainMessage(
4448 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4449 DEFAULT_DISPLAY);
4450 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 }
4452
4453 final long origId = Binder.clearCallingIdentity();
4454 try {
4455 if (values != null) {
4456 Settings.System.clearConfiguration(values);
4457 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 UserHandle.USER_NULL, false /* deferResume */,
4460 mTmpUpdateConfigurationResult);
4461 return mTmpUpdateConfigurationResult.changes != 0;
4462 } finally {
4463 Binder.restoreCallingIdentity(origId);
4464 }
4465 }
4466 }
4467
4468 @Override
4469 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4470 CharSequence message) {
4471 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4474 }
4475 final long callingId = Binder.clearCallingIdentity();
4476 try {
4477 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004478 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 }
4480 } finally {
4481 Binder.restoreCallingIdentity(callingId);
4482 }
4483 }
4484
4485 @Override
4486 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 "cancelTaskWindowTransition()");
4489 final long ident = Binder.clearCallingIdentity();
4490 try {
4491 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004492 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 MATCH_TASK_IN_STACKS_ONLY);
4494 if (task == null) {
4495 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4496 return;
4497 }
4498 task.cancelWindowTransition();
4499 }
4500 } finally {
4501 Binder.restoreCallingIdentity(ident);
4502 }
4503 }
4504
4505 @Override
4506 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 final long ident = Binder.clearCallingIdentity();
4509 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004510 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 } finally {
4512 Binder.restoreCallingIdentity(ident);
4513 }
4514 }
4515
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004516 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4517 boolean restoreFromDisk) {
4518 final TaskRecord task;
4519 synchronized (mGlobalLock) {
4520 task = mRootActivityContainer.anyTaskForId(taskId,
4521 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4522 if (task == null) {
4523 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4524 return null;
4525 }
4526 }
4527 // Don't call this while holding the lock as this operation might hit the disk.
4528 return task.getSnapshot(reducedResolution, restoreFromDisk);
4529 }
4530
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004531 @Override
4532 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4533 synchronized (mGlobalLock) {
4534 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4535 if (r == null) {
4536 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4537 + token);
4538 return;
4539 }
4540 final long origId = Binder.clearCallingIdentity();
4541 try {
4542 r.setDisablePreviewScreenshots(disable);
4543 } finally {
4544 Binder.restoreCallingIdentity(origId);
4545 }
4546 }
4547 }
4548
4549 /** Return the user id of the last resumed activity. */
4550 @Override
4551 public @UserIdInt
4552 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004553 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4555 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004556 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004557 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004559 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004560 }
4561 }
4562
4563 @Override
4564 public void updateLockTaskFeatures(int userId, int flags) {
4565 final int callingUid = Binder.getCallingUid();
4566 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004567 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004568 "updateLockTaskFeatures()");
4569 }
4570 synchronized (mGlobalLock) {
4571 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4572 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004573 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 }
4575 }
4576
4577 @Override
4578 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4579 synchronized (mGlobalLock) {
4580 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4581 if (r == null) {
4582 return;
4583 }
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
4586 r.setShowWhenLocked(showWhenLocked);
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591 }
4592
4593 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004594 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4595 synchronized (mGlobalLock) {
4596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4597 if (r == null) {
4598 return;
4599 }
4600 final long origId = Binder.clearCallingIdentity();
4601 try {
4602 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4603 } finally {
4604 Binder.restoreCallingIdentity(origId);
4605 }
4606 }
4607 }
4608
4609 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4611 synchronized (mGlobalLock) {
4612 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4613 if (r == null) {
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 r.setTurnScreenOn(turnScreenOn);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
4625 @Override
4626 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "registerRemoteAnimations");
4629 definition.setCallingPid(Binder.getCallingPid());
4630 synchronized (mGlobalLock) {
4631 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4632 if (r == null) {
4633 return;
4634 }
4635 final long origId = Binder.clearCallingIdentity();
4636 try {
4637 r.registerRemoteAnimations(definition);
4638 } finally {
4639 Binder.restoreCallingIdentity(origId);
4640 }
4641 }
4642 }
4643
4644 @Override
4645 public void registerRemoteAnimationForNextActivityStart(String packageName,
4646 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004647 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 "registerRemoteAnimationForNextActivityStart");
4649 adapter.setCallingPid(Binder.getCallingPid());
4650 synchronized (mGlobalLock) {
4651 final long origId = Binder.clearCallingIdentity();
4652 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004653 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004654 packageName, adapter);
4655 } finally {
4656 Binder.restoreCallingIdentity(origId);
4657 }
4658 }
4659 }
4660
Evan Rosky966759f2019-01-15 10:33:58 -08004661 @Override
4662 public void registerRemoteAnimationsForDisplay(int displayId,
4663 RemoteAnimationDefinition definition) {
4664 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4665 "registerRemoteAnimations");
4666 definition.setCallingPid(Binder.getCallingPid());
4667 synchronized (mGlobalLock) {
4668 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4669 if (display == null) {
4670 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4671 return;
4672 }
4673 final long origId = Binder.clearCallingIdentity();
4674 try {
4675 display.mDisplayContent.registerRemoteAnimations(definition);
4676 } finally {
4677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680 }
4681
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004682 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4683 @Override
4684 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4685 synchronized (mGlobalLock) {
4686 final long origId = Binder.clearCallingIdentity();
4687 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004688 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 } finally {
4690 Binder.restoreCallingIdentity(origId);
4691 }
4692 }
4693 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004694
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004695 @Override
4696 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004699 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004700 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004701 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 }
4703 }
4704
4705 @Override
4706 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004708 != PERMISSION_GRANTED) {
4709 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4710 + Binder.getCallingPid()
4711 + ", uid=" + Binder.getCallingUid()
4712 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4713 Slog.w(TAG, msg);
4714 throw new SecurityException(msg);
4715 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004716 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004718 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004719 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004720 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 }
4722 }
4723
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 @Override
4725 public void stopAppSwitches() {
4726 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4727 synchronized (mGlobalLock) {
4728 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4729 mDidAppSwitch = false;
4730 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4731 }
4732 }
4733
4734 @Override
4735 public void resumeAppSwitches() {
4736 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4737 synchronized (mGlobalLock) {
4738 // Note that we don't execute any pending app switches... we will
4739 // let those wait until either the timeout, or the next start
4740 // activity request.
4741 mAppSwitchesAllowedTime = 0;
4742 }
4743 }
4744
4745 void onStartActivitySetDidAppSwitch() {
4746 if (mDidAppSwitch) {
4747 // This is the second allowed switch since we stopped switches, so now just generally
4748 // allow switches. Use case:
4749 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4750 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4751 // anyone to switch again).
4752 mAppSwitchesAllowedTime = 0;
4753 } else {
4754 mDidAppSwitch = true;
4755 }
4756 }
4757
4758 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004759 boolean shouldDisableNonVrUiLocked() {
4760 return mVrController.shouldDisableNonVrUiLocked();
4761 }
4762
Wale Ogunwale53783742018-09-16 10:21:51 -07004763 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004764 // VR apps are expected to run in a main display. If an app is turning on VR for
4765 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4766 // fullscreen stack before enabling VR Mode.
4767 // TODO: The goal of this code is to keep the VR app on the main display. When the
4768 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4769 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4770 // option would be a better choice here.
4771 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4772 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4773 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004774 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004776 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004777 }
4778 mH.post(() -> {
4779 if (!mVrController.onVrModeChanged(r)) {
4780 return;
4781 }
4782 synchronized (mGlobalLock) {
4783 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4784 mWindowManager.disableNonVrUi(disableNonVrUi);
4785 if (disableNonVrUi) {
4786 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4787 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004788 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004789 }
4790 }
4791 });
4792 }
4793
Wale Ogunwale53783742018-09-16 10:21:51 -07004794 @Override
4795 public int getPackageScreenCompatMode(String packageName) {
4796 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4797 synchronized (mGlobalLock) {
4798 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4799 }
4800 }
4801
4802 @Override
4803 public void setPackageScreenCompatMode(String packageName, int mode) {
4804 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4805 "setPackageScreenCompatMode");
4806 synchronized (mGlobalLock) {
4807 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4808 }
4809 }
4810
4811 @Override
4812 public boolean getPackageAskScreenCompat(String packageName) {
4813 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4814 synchronized (mGlobalLock) {
4815 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4816 }
4817 }
4818
4819 @Override
4820 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4821 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4822 "setPackageAskScreenCompat");
4823 synchronized (mGlobalLock) {
4824 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4825 }
4826 }
4827
Wale Ogunwale64258362018-10-16 15:13:37 -07004828 public static String relaunchReasonToString(int relaunchReason) {
4829 switch (relaunchReason) {
4830 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4831 return "window_resize";
4832 case RELAUNCH_REASON_FREE_RESIZE:
4833 return "free_resize";
4834 default:
4835 return null;
4836 }
4837 }
4838
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004839 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004840 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004841 }
4842
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 /** Pokes the task persister. */
4844 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4845 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4846 }
4847
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004848 boolean isKeyguardLocked() {
4849 return mKeyguardController.isKeyguardLocked();
4850 }
4851
Garfield Tan01548632018-11-27 10:15:48 -08004852 /**
4853 * Clears launch params for the given package.
4854 * @param packageNames the names of the packages of which the launch params are to be cleared
4855 */
4856 @Override
4857 public void clearLaunchParamsForPackages(List<String> packageNames) {
4858 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4859 "clearLaunchParamsForPackages");
4860 synchronized (mGlobalLock) {
4861 for (int i = 0; i < packageNames.size(); ++i) {
4862 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4863 }
4864 }
4865 }
4866
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004867 /**
4868 * Makes the display with the given id a single task instance display. I.e the display can only
4869 * contain one task.
4870 */
4871 @Override
4872 public void setDisplayToSingleTaskInstance(int displayId) {
4873 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4874 "setDisplayToSingleTaskInstance");
4875 final long origId = Binder.clearCallingIdentity();
4876 try {
4877 final ActivityDisplay display =
4878 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4879 if (display != null) {
4880 display.setDisplayToSingleTaskInstance();
4881 }
4882 } finally {
4883 Binder.restoreCallingIdentity(origId);
4884 }
4885 }
4886
Wale Ogunwale31913b52018-10-13 08:29:31 -07004887 void dumpLastANRLocked(PrintWriter pw) {
4888 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4889 if (mLastANRState == null) {
4890 pw.println(" <no ANR has occurred since boot>");
4891 } else {
4892 pw.println(mLastANRState);
4893 }
4894 }
4895
4896 void dumpLastANRTracesLocked(PrintWriter pw) {
4897 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4898
4899 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4900 if (ArrayUtils.isEmpty(files)) {
4901 pw.println(" <no ANR has occurred since boot>");
4902 return;
4903 }
4904 // Find the latest file.
4905 File latest = null;
4906 for (File f : files) {
4907 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4908 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004909 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004910 }
4911 pw.print("File: ");
4912 pw.print(latest.getName());
4913 pw.println();
4914 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4915 String line;
4916 while ((line = in.readLine()) != null) {
4917 pw.println(line);
4918 }
4919 } catch (IOException e) {
4920 pw.print("Unable to read: ");
4921 pw.print(e);
4922 pw.println();
4923 }
4924 }
4925
4926 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4927 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4928 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4929 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4930 }
4931
4932 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4933 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4934 pw.println(header);
4935
Wale Ogunwaled32da472018-11-16 07:19:28 -08004936 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 dumpPackage);
4938 boolean needSep = printedAnything;
4939
4940 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004941 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 " ResumedActivity: ");
4943 if (printed) {
4944 printedAnything = true;
4945 needSep = false;
4946 }
4947
4948 if (dumpPackage == null) {
4949 if (needSep) {
4950 pw.println();
4951 }
4952 printedAnything = true;
4953 mStackSupervisor.dump(pw, " ");
4954 }
4955
4956 if (!printedAnything) {
4957 pw.println(" (nothing)");
4958 }
4959 }
4960
4961 void dumpActivityContainersLocked(PrintWriter pw) {
4962 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004963 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 pw.println(" ");
4965 }
4966
4967 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4968 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4969 getActivityStartController().dump(pw, "", dumpPackage);
4970 }
4971
4972 /**
4973 * There are three things that cmd can be:
4974 * - a flattened component name that matches an existing activity
4975 * - the cmd arg isn't the flattened component name of an existing activity:
4976 * dump all activity whose component contains the cmd as a substring
4977 * - A hex number of the ActivityRecord object instance.
4978 *
4979 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4980 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4981 */
4982 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4983 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4984 ArrayList<ActivityRecord> activities;
4985
4986 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004987 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004988 dumpFocusedStackOnly);
4989 }
4990
4991 if (activities.size() <= 0) {
4992 return false;
4993 }
4994
4995 String[] newArgs = new String[args.length - opti];
4996 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4997
4998 TaskRecord lastTask = null;
4999 boolean needSep = false;
5000 for (int i = activities.size() - 1; i >= 0; i--) {
5001 ActivityRecord r = activities.get(i);
5002 if (needSep) {
5003 pw.println();
5004 }
5005 needSep = true;
5006 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005007 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005008 if (lastTask != task) {
5009 lastTask = task;
5010 pw.print("TASK "); pw.print(lastTask.affinity);
5011 pw.print(" id="); pw.print(lastTask.taskId);
5012 pw.print(" userId="); pw.println(lastTask.userId);
5013 if (dumpAll) {
5014 lastTask.dump(pw, " ");
5015 }
5016 }
5017 }
5018 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5019 }
5020 return true;
5021 }
5022
5023 /**
5024 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5025 * there is a thread associated with the activity.
5026 */
5027 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5028 final ActivityRecord r, String[] args, boolean dumpAll) {
5029 String innerPrefix = prefix + " ";
5030 synchronized (mGlobalLock) {
5031 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5032 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5033 pw.print(" pid=");
5034 if (r.hasProcess()) pw.println(r.app.getPid());
5035 else pw.println("(not running)");
5036 if (dumpAll) {
5037 r.dump(pw, innerPrefix);
5038 }
5039 }
5040 if (r.attachedToProcess()) {
5041 // flush anything that is already in the PrintWriter since the thread is going
5042 // to write to the file descriptor directly
5043 pw.flush();
5044 try {
5045 TransferPipe tp = new TransferPipe();
5046 try {
5047 r.app.getThread().dumpActivity(tp.getWriteFd(),
5048 r.appToken, innerPrefix, args);
5049 tp.go(fd);
5050 } finally {
5051 tp.kill();
5052 }
5053 } catch (IOException e) {
5054 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5055 } catch (RemoteException e) {
5056 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5057 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005058 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005059 }
5060
sanryhuang498e77e2018-12-06 14:57:01 +08005061 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5062 boolean testPssMode) {
5063 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5064 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5065 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005066 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005067 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5068 st.toString());
5069 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005070 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5071 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5072 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005073 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5074 testPssMode);
5075 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005076 }
5077
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005078 int getCurrentUserId() {
5079 return mAmInternal.getCurrentUserId();
5080 }
5081
5082 private void enforceNotIsolatedCaller(String caller) {
5083 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5084 throw new SecurityException("Isolated process not allowed to call " + caller);
5085 }
5086 }
5087
Wale Ogunwalef6733932018-06-27 05:14:34 -07005088 public Configuration getConfiguration() {
5089 Configuration ci;
5090 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005091 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005092 ci.userSetLocale = false;
5093 }
5094 return ci;
5095 }
5096
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005097 /**
5098 * Current global configuration information. Contains general settings for the entire system,
5099 * also corresponds to the merged configuration of the default display.
5100 */
5101 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005102 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005103 }
5104
5105 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5106 boolean initLocale) {
5107 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5108 }
5109
5110 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5111 boolean initLocale, boolean deferResume) {
5112 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5113 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5114 UserHandle.USER_NULL, deferResume);
5115 }
5116
Wale Ogunwale59507092018-10-29 09:00:30 -07005117 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005118 final long origId = Binder.clearCallingIdentity();
5119 try {
5120 synchronized (mGlobalLock) {
5121 updateConfigurationLocked(values, null, false, true, userId,
5122 false /* deferResume */);
5123 }
5124 } finally {
5125 Binder.restoreCallingIdentity(origId);
5126 }
5127 }
5128
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5130 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5131 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5132 deferResume, null /* result */);
5133 }
5134
5135 /**
5136 * Do either or both things: (1) change the current configuration, and (2)
5137 * make sure the given activity is running with the (now) current
5138 * configuration. Returns true if the activity has been left running, or
5139 * false if <var>starting</var> is being destroyed to match the new
5140 * configuration.
5141 *
5142 * @param userId is only used when persistent parameter is set to true to persist configuration
5143 * for that particular user
5144 */
5145 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5146 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5147 ActivityTaskManagerService.UpdateConfigurationResult result) {
5148 int changes = 0;
5149 boolean kept = true;
5150
5151 if (mWindowManager != null) {
5152 mWindowManager.deferSurfaceLayout();
5153 }
5154 try {
5155 if (values != null) {
5156 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5157 deferResume);
5158 }
5159
5160 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5161 } finally {
5162 if (mWindowManager != null) {
5163 mWindowManager.continueSurfaceLayout();
5164 }
5165 }
5166
5167 if (result != null) {
5168 result.changes = changes;
5169 result.activityRelaunched = !kept;
5170 }
5171 return kept;
5172 }
5173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174 /** Update default (global) configuration and notify listeners about changes. */
5175 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5176 boolean persistent, int userId, boolean deferResume) {
5177 mTempConfig.setTo(getGlobalConfiguration());
5178 final int changes = mTempConfig.updateFrom(values);
5179 if (changes == 0) {
5180 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5181 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5182 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5183 // (even if there are no actual changes) to unfreeze the window.
5184 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5185 return 0;
5186 }
5187
5188 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5189 "Updating global configuration to: " + values);
5190
5191 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5192 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5193 values.colorMode,
5194 values.densityDpi,
5195 values.fontScale,
5196 values.hardKeyboardHidden,
5197 values.keyboard,
5198 values.keyboardHidden,
5199 values.mcc,
5200 values.mnc,
5201 values.navigation,
5202 values.navigationHidden,
5203 values.orientation,
5204 values.screenHeightDp,
5205 values.screenLayout,
5206 values.screenWidthDp,
5207 values.smallestScreenWidthDp,
5208 values.touchscreen,
5209 values.uiMode);
5210
5211
5212 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5213 final LocaleList locales = values.getLocales();
5214 int bestLocaleIndex = 0;
5215 if (locales.size() > 1) {
5216 if (mSupportedSystemLocales == null) {
5217 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5218 }
5219 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5220 }
5221 SystemProperties.set("persist.sys.locale",
5222 locales.get(bestLocaleIndex).toLanguageTag());
5223 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005224
5225 final Message m = PooledLambda.obtainMessage(
5226 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5227 locales.get(bestLocaleIndex));
5228 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 }
5230
Yunfan Chen75157d72018-07-27 14:47:21 +09005231 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232
5233 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005234 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235
5236 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5237 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005238 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005241 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242
5243 AttributeCache ac = AttributeCache.instance();
5244 if (ac != null) {
5245 ac.updateConfiguration(mTempConfig);
5246 }
5247
5248 // Make sure all resources in our process are updated right now, so that anyone who is going
5249 // to retrieve resource values after we return will be sure to get the new ones. This is
5250 // especially important during boot, where the first config change needs to guarantee all
5251 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005252 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253
5254 // We need another copy of global config because we're scheduling some calls instead of
5255 // running them in place. We need to be sure that object we send will be handled unchanged.
5256 final Configuration configCopy = new Configuration(mTempConfig);
5257 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005258 final Message msg = PooledLambda.obtainMessage(
5259 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5260 this, userId, configCopy);
5261 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262 }
5263
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005264 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5265 for (int i = pidMap.size() - 1; i >= 0; i--) {
5266 final int pid = pidMap.keyAt(i);
5267 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005268 if (DEBUG_CONFIGURATION) {
5269 Slog.v(TAG_CONFIGURATION, "Update process config of "
5270 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005272 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 }
5274
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005275 final Message msg = PooledLambda.obtainMessage(
5276 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5277 mAmInternal, changes, initLocale);
5278 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005279
5280 // Override configuration of the default display duplicates global config, so we need to
5281 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005282 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005283 DEFAULT_DISPLAY);
5284
5285 return changes;
5286 }
5287
5288 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5289 boolean deferResume, int displayId) {
5290 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5291 displayId, null /* result */);
5292 }
5293
5294 /**
5295 * Updates override configuration specific for the selected display. If no config is provided,
5296 * new one will be computed in WM based on current display info.
5297 */
5298 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5299 ActivityRecord starting, boolean deferResume, int displayId,
5300 ActivityTaskManagerService.UpdateConfigurationResult result) {
5301 int changes = 0;
5302 boolean kept = true;
5303
5304 if (mWindowManager != null) {
5305 mWindowManager.deferSurfaceLayout();
5306 }
5307 try {
5308 if (values != null) {
5309 if (displayId == DEFAULT_DISPLAY) {
5310 // Override configuration of the default display duplicates global config, so
5311 // we're calling global config update instead for default display. It will also
5312 // apply the correct override config.
5313 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5314 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5315 } else {
5316 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5317 }
5318 }
5319
5320 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5321 } finally {
5322 if (mWindowManager != null) {
5323 mWindowManager.continueSurfaceLayout();
5324 }
5325 }
5326
5327 if (result != null) {
5328 result.changes = changes;
5329 result.activityRelaunched = !kept;
5330 }
5331 return kept;
5332 }
5333
5334 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5335 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005336 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337 final int changes = mTempConfig.updateFrom(values);
5338 if (changes != 0) {
5339 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5340 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005341 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342
5343 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5344 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005345 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005346
Wale Ogunwale5c918702018-10-18 11:06:33 -07005347 // Post message to start process to avoid possible deadlock of calling into AMS with
5348 // the ATMS lock held.
5349 final Message msg = PooledLambda.obtainMessage(
5350 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005351 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005352 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 }
5354 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355 return changes;
5356 }
5357
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 private void updateEventDispatchingLocked(boolean booted) {
5359 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5360 }
5361
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005362 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5363 final ContentResolver resolver = mContext.getContentResolver();
5364 Settings.System.putConfigurationForUser(resolver, config, userId);
5365 }
5366
5367 private void sendLocaleToMountDaemonMsg(Locale l) {
5368 try {
5369 IBinder service = ServiceManager.getService("mount");
5370 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5371 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5372 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5373 } catch (RemoteException e) {
5374 Log.e(TAG, "Error storing locale for decryption UI", e);
5375 }
5376 }
5377
Alison Cichowlas3e340502018-08-07 17:15:01 -04005378 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5379 mStartActivitySources.remove(permissionToken);
5380 mExpiredStartAsCallerTokens.add(permissionToken);
5381 }
5382
5383 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5384 mExpiredStartAsCallerTokens.remove(permissionToken);
5385 }
5386
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005387 boolean isActivityStartsLoggingEnabled() {
5388 return mAmInternal.isActivityStartsLoggingEnabled();
5389 }
5390
Michal Karpinski8596ded2018-11-14 14:43:48 +00005391 boolean isBackgroundActivityStartsEnabled() {
5392 return mAmInternal.isBackgroundActivityStartsEnabled();
5393 }
5394
Ricky Waiaca8a772019-04-04 16:01:06 +01005395 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5396 if (packageName == null) {
5397 return false;
5398 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005399 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5400 }
5401
Wale Ogunwalef6733932018-06-27 05:14:34 -07005402 void enableScreenAfterBoot(boolean booted) {
5403 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5404 SystemClock.uptimeMillis());
5405 mWindowManager.enableScreenAfterBoot();
5406
5407 synchronized (mGlobalLock) {
5408 updateEventDispatchingLocked(booted);
5409 }
5410 }
5411
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005412 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5413 if (r == null || !r.hasProcess()) {
5414 return KEY_DISPATCHING_TIMEOUT_MS;
5415 }
5416 return getInputDispatchingTimeoutLocked(r.app);
5417 }
5418
5419 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005420 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005421 }
5422
Wale Ogunwalef6733932018-06-27 05:14:34 -07005423 /**
5424 * Decide based on the configuration whether we should show the ANR,
5425 * crash, etc dialogs. The idea is that if there is no affordance to
5426 * press the on-screen buttons, or the user experience would be more
5427 * greatly impacted than the crash itself, we shouldn't show the dialog.
5428 *
5429 * A thought: SystemUI might also want to get told about this, the Power
5430 * dialog / global actions also might want different behaviors.
5431 */
5432 private void updateShouldShowDialogsLocked(Configuration config) {
5433 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5434 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5435 && config.navigation == Configuration.NAVIGATION_NONAV);
5436 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5437 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5438 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5439 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5440 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5441 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5442 HIDE_ERROR_DIALOGS, 0) != 0;
5443 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5444 }
5445
5446 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5447 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5448 FONT_SCALE, 1.0f, userId);
5449
5450 synchronized (this) {
5451 if (getGlobalConfiguration().fontScale == scaleFactor) {
5452 return;
5453 }
5454
5455 final Configuration configuration
5456 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5457 configuration.fontScale = scaleFactor;
5458 updatePersistentConfiguration(configuration, userId);
5459 }
5460 }
5461
5462 // Actually is sleeping or shutting down or whatever else in the future
5463 // is an inactive state.
5464 boolean isSleepingOrShuttingDownLocked() {
5465 return isSleepingLocked() || mShuttingDown;
5466 }
5467
5468 boolean isSleepingLocked() {
5469 return mSleeping;
5470 }
5471
Riddle Hsu16567132018-08-16 21:37:47 +08005472 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005474 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475 if (task.isActivityTypeStandard()) {
5476 if (mCurAppTimeTracker != r.appTimeTracker) {
5477 // We are switching app tracking. Complete the current one.
5478 if (mCurAppTimeTracker != null) {
5479 mCurAppTimeTracker.stop();
5480 mH.obtainMessage(
5481 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005482 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 mCurAppTimeTracker = null;
5484 }
5485 if (r.appTimeTracker != null) {
5486 mCurAppTimeTracker = r.appTimeTracker;
5487 startTimeTrackingFocusedActivityLocked();
5488 }
5489 } else {
5490 startTimeTrackingFocusedActivityLocked();
5491 }
5492 } else {
5493 r.appTimeTracker = null;
5494 }
5495 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5496 // TODO: Probably not, because we don't want to resume voice on switching
5497 // back to this activity
5498 if (task.voiceInteractor != null) {
5499 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5500 } else {
5501 finishRunningVoiceLocked();
5502
5503 if (mLastResumedActivity != null) {
5504 final IVoiceInteractionSession session;
5505
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005506 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 if (lastResumedActivityTask != null
5508 && lastResumedActivityTask.voiceSession != null) {
5509 session = lastResumedActivityTask.voiceSession;
5510 } else {
5511 session = mLastResumedActivity.voiceSession;
5512 }
5513
5514 if (session != null) {
5515 // We had been in a voice interaction session, but now focused has
5516 // move to something different. Just finish the session, we can't
5517 // return to it and retain the proper state and synchronization with
5518 // the voice interaction service.
5519 finishVoiceTask(session);
5520 }
5521 }
5522 }
5523
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005524 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5525 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526 }
5527 updateResumedAppTrace(r);
5528 mLastResumedActivity = r;
5529
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005530 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005531
5532 applyUpdateLockStateLocked(r);
5533 applyUpdateVrModeLocked(r);
5534
5535 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005536 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005537 r == null ? "NULL" : r.shortComponentName,
5538 reason);
5539 }
5540
5541 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5542 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005543 final ActivityTaskManagerInternal.SleepToken token =
5544 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 updateSleepIfNeededLocked();
5546 return token;
5547 }
5548 }
5549
5550 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005551 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005552 final boolean wasSleeping = mSleeping;
5553 boolean updateOomAdj = false;
5554
5555 if (!shouldSleep) {
5556 // If wasSleeping is true, we need to wake up activity manager state from when
5557 // we started sleeping. In either case, we need to apply the sleep tokens, which
5558 // will wake up stacks or put them to sleep as appropriate.
5559 if (wasSleeping) {
5560 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005561 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5562 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 startTimeTrackingFocusedActivityLocked();
5564 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005565 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005566 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5567 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005568 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 if (wasSleeping) {
5570 updateOomAdj = true;
5571 }
5572 } else if (!mSleeping && shouldSleep) {
5573 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005574 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5575 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 if (mCurAppTimeTracker != null) {
5577 mCurAppTimeTracker.stop();
5578 }
5579 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005580 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005581 mStackSupervisor.goingToSleepLocked();
5582 updateResumedAppTrace(null /* resumed */);
5583 updateOomAdj = true;
5584 }
5585 if (updateOomAdj) {
5586 mH.post(mAmInternal::updateOomAdj);
5587 }
5588 }
5589
5590 void updateOomAdj() {
5591 mH.post(mAmInternal::updateOomAdj);
5592 }
5593
Wale Ogunwale53783742018-09-16 10:21:51 -07005594 void updateCpuStats() {
5595 mH.post(mAmInternal::updateCpuStats);
5596 }
5597
Hui Yu03d12402018-12-06 18:00:37 -08005598 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5599 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005600 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5601 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005602 mH.sendMessage(m);
5603 }
5604
Hui Yu03d12402018-12-06 18:00:37 -08005605 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005606 ComponentName taskRoot = null;
5607 final TaskRecord task = activity.getTaskRecord();
5608 if (task != null) {
5609 final ActivityRecord rootActivity = task.getRootActivity();
5610 if (rootActivity != null) {
5611 taskRoot = rootActivity.mActivityComponent;
5612 }
5613 }
5614
Hui Yu03d12402018-12-06 18:00:37 -08005615 final Message m = PooledLambda.obtainMessage(
5616 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005617 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005618 mH.sendMessage(m);
5619 }
5620
Wale Ogunwale53783742018-09-16 10:21:51 -07005621 void setBooting(boolean booting) {
5622 mAmInternal.setBooting(booting);
5623 }
5624
5625 boolean isBooting() {
5626 return mAmInternal.isBooting();
5627 }
5628
5629 void setBooted(boolean booted) {
5630 mAmInternal.setBooted(booted);
5631 }
5632
5633 boolean isBooted() {
5634 return mAmInternal.isBooted();
5635 }
5636
5637 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5638 mH.post(() -> {
5639 if (finishBooting) {
5640 mAmInternal.finishBooting();
5641 }
5642 if (enableScreen) {
5643 mInternal.enableScreenAfterBoot(isBooted());
5644 }
5645 });
5646 }
5647
5648 void setHeavyWeightProcess(ActivityRecord root) {
5649 mHeavyWeightProcess = root.app;
5650 final Message m = PooledLambda.obtainMessage(
5651 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005652 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005653 mH.sendMessage(m);
5654 }
5655
5656 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5657 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5658 return;
5659 }
5660
5661 mHeavyWeightProcess = null;
5662 final Message m = PooledLambda.obtainMessage(
5663 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5664 proc.mUserId);
5665 mH.sendMessage(m);
5666 }
5667
5668 private void cancelHeavyWeightProcessNotification(int userId) {
5669 final INotificationManager inm = NotificationManager.getService();
5670 if (inm == null) {
5671 return;
5672 }
5673 try {
5674 inm.cancelNotificationWithTag("android", null,
5675 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5676 } catch (RuntimeException e) {
5677 Slog.w(TAG, "Error canceling notification for service", e);
5678 } catch (RemoteException e) {
5679 }
5680
5681 }
5682
5683 private void postHeavyWeightProcessNotification(
5684 WindowProcessController proc, Intent intent, int userId) {
5685 if (proc == null) {
5686 return;
5687 }
5688
5689 final INotificationManager inm = NotificationManager.getService();
5690 if (inm == null) {
5691 return;
5692 }
5693
5694 try {
5695 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5696 String text = mContext.getString(R.string.heavy_weight_notification,
5697 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5698 Notification notification =
5699 new Notification.Builder(context,
5700 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5701 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5702 .setWhen(0)
5703 .setOngoing(true)
5704 .setTicker(text)
5705 .setColor(mContext.getColor(
5706 com.android.internal.R.color.system_notification_accent_color))
5707 .setContentTitle(text)
5708 .setContentText(
5709 mContext.getText(R.string.heavy_weight_notification_detail))
5710 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5711 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5712 new UserHandle(userId)))
5713 .build();
5714 try {
5715 inm.enqueueNotificationWithTag("android", "android", null,
5716 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5717 } catch (RuntimeException e) {
5718 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5719 } catch (RemoteException e) {
5720 }
5721 } catch (PackageManager.NameNotFoundException e) {
5722 Slog.w(TAG, "Unable to create context for heavy notification", e);
5723 }
5724
5725 }
5726
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005727 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5728 IBinder token, String resultWho, int requestCode, Intent[] intents,
5729 String[] resolvedTypes, int flags, Bundle bOptions) {
5730
5731 ActivityRecord activity = null;
5732 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5733 activity = ActivityRecord.isInStackLocked(token);
5734 if (activity == null) {
5735 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5736 return null;
5737 }
5738 if (activity.finishing) {
5739 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5740 return null;
5741 }
5742 }
5743
5744 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5745 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5746 bOptions);
5747 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5748 if (noCreate) {
5749 return rec;
5750 }
5751 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5752 if (activity.pendingResults == null) {
5753 activity.pendingResults = new HashSet<>();
5754 }
5755 activity.pendingResults.add(rec.ref);
5756 }
5757 return rec;
5758 }
5759
Andrii Kulian52d255c2018-07-13 11:32:19 -07005760 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005761 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005762 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005763 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5764 mCurAppTimeTracker.start(resumedActivity.packageName);
5765 }
5766 }
5767
5768 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5769 if (mTracedResumedActivity != null) {
5770 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5771 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5772 }
5773 if (resumed != null) {
5774 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5775 constructResumedTraceName(resumed.packageName), 0);
5776 }
5777 mTracedResumedActivity = resumed;
5778 }
5779
5780 private String constructResumedTraceName(String packageName) {
5781 return "focused app: " + packageName;
5782 }
5783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 /** Applies latest configuration and/or visibility updates if needed. */
5785 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5786 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005787 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005788 // mainStack is null during startup.
5789 if (mainStack != null) {
5790 if (changes != 0 && starting == null) {
5791 // If the configuration changed, and the caller is not already
5792 // in the process of starting an activity, then find the top
5793 // activity to check if its configuration needs to change.
5794 starting = mainStack.topRunningActivityLocked();
5795 }
5796
5797 if (starting != null) {
5798 kept = starting.ensureActivityConfiguration(changes,
5799 false /* preserveWindow */);
5800 // And we need to make sure at this point that all other activities
5801 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005802 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005803 !PRESERVE_WINDOWS);
5804 }
5805 }
5806
5807 return kept;
5808 }
5809
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005810 void scheduleAppGcsLocked() {
5811 mH.post(() -> mAmInternal.scheduleAppGcs());
5812 }
5813
Wale Ogunwale53783742018-09-16 10:21:51 -07005814 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5815 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5816 }
5817
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005818 /**
5819 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5820 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5821 * on demand.
5822 */
5823 IPackageManager getPackageManager() {
5824 return AppGlobals.getPackageManager();
5825 }
5826
5827 PackageManagerInternal getPackageManagerInternalLocked() {
5828 if (mPmInternal == null) {
5829 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5830 }
5831 return mPmInternal;
5832 }
5833
Hai Zhangf4da9be2019-05-01 13:46:06 +08005834 PermissionPolicyInternal getPermissionPolicyInternal() {
5835 if (mPermissionPolicyInternal == null) {
5836 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5837 }
5838 return mPermissionPolicyInternal;
5839 }
5840
Wale Ogunwale008163e2018-07-23 23:11:08 -07005841 AppWarnings getAppWarningsLocked() {
5842 return mAppWarnings;
5843 }
5844
Wale Ogunwale214f3482018-10-04 11:00:47 -07005845 Intent getHomeIntent() {
5846 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5847 intent.setComponent(mTopComponent);
5848 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5849 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5850 intent.addCategory(Intent.CATEGORY_HOME);
5851 }
5852 return intent;
5853 }
5854
Chilun2ef71f72018-11-16 17:57:15 +08005855 /**
5856 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5857 * activities.
5858 *
5859 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5860 * component defined in config_secondaryHomeComponent.
5861 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5862 */
5863 Intent getSecondaryHomeIntent(String preferredPackage) {
5864 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005865 if (preferredPackage == null) {
5866 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005867 final String secondaryHomeComponent = mContext.getResources().getString(
5868 com.android.internal.R.string.config_secondaryHomeComponent);
5869 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5870 } else {
5871 intent.setPackage(preferredPackage);
5872 }
5873 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5874 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5875 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5876 }
5877 return intent;
5878 }
5879
Wale Ogunwale214f3482018-10-04 11:00:47 -07005880 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5881 if (info == null) return null;
5882 ApplicationInfo newInfo = new ApplicationInfo(info);
5883 newInfo.initForUser(userId);
5884 return newInfo;
5885 }
5886
Wale Ogunwale9c103022018-10-18 07:44:54 -07005887 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005888 if (uid == SYSTEM_UID) {
5889 // The system gets to run in any process. If there are multiple processes with the same
5890 // uid, just pick the first (this should never happen).
5891 final SparseArray<WindowProcessController> procs =
5892 mProcessNames.getMap().get(processName);
5893 if (procs == null) return null;
5894 final int procCount = procs.size();
5895 for (int i = 0; i < procCount; i++) {
5896 final int procUid = procs.keyAt(i);
5897 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5898 // Don't use an app process or different user process for system component.
5899 continue;
5900 }
5901 return procs.valueAt(i);
5902 }
5903 }
5904
5905 return mProcessNames.get(processName, uid);
5906 }
5907
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005908 WindowProcessController getProcessController(IApplicationThread thread) {
5909 if (thread == null) {
5910 return null;
5911 }
5912
5913 final IBinder threadBinder = thread.asBinder();
5914 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5915 for (int i = pmap.size()-1; i >= 0; i--) {
5916 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5917 for (int j = procs.size() - 1; j >= 0; j--) {
5918 final WindowProcessController proc = procs.valueAt(j);
5919 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5920 return proc;
5921 }
5922 }
5923 }
5924
5925 return null;
5926 }
5927
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005928 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005929 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005930 if (proc == null) return null;
5931 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5932 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005933 }
5934 return null;
5935 }
5936
Riddle Hsua0536432019-02-16 00:38:59 +08005937 int getUidState(int uid) {
5938 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005939 }
5940
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005941 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005942 // A uid is considered to be foreground if it has a visible non-toast window.
5943 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005944 }
5945
Ricky Wai96f5c352019-04-10 18:40:17 +01005946 boolean isDeviceOwner(int uid) {
5947 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005948 }
5949
Ricky Wai96f5c352019-04-10 18:40:17 +01005950 void setDeviceOwnerUid(int uid) {
5951 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005952 }
5953
Wale Ogunwale9de19442018-10-18 19:05:03 -07005954 /**
5955 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5956 * the whitelist
5957 */
5958 String getPendingTempWhitelistTagForUidLocked(int uid) {
5959 return mPendingTempWhitelist.get(uid);
5960 }
5961
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005962 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5963 if (true || Build.IS_USER) {
5964 return;
5965 }
5966
5967 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5968 StrictMode.allowThreadDiskWrites();
5969 try {
5970 File tracesDir = new File("/data/anr");
5971 File tracesFile = null;
5972 try {
5973 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5974
5975 StringBuilder sb = new StringBuilder();
5976 Time tobj = new Time();
5977 tobj.set(System.currentTimeMillis());
5978 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5979 sb.append(": ");
5980 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5981 sb.append(" since ");
5982 sb.append(msg);
5983 FileOutputStream fos = new FileOutputStream(tracesFile);
5984 fos.write(sb.toString().getBytes());
5985 if (app == null) {
5986 fos.write("\n*** No application process!".getBytes());
5987 }
5988 fos.close();
5989 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5990 } catch (IOException e) {
5991 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5992 return;
5993 }
5994
5995 if (app != null && app.getPid() > 0) {
5996 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5997 firstPids.add(app.getPid());
5998 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5999 }
6000
6001 File lastTracesFile = null;
6002 File curTracesFile = null;
6003 for (int i=9; i>=0; i--) {
6004 String name = String.format(Locale.US, "slow%02d.txt", i);
6005 curTracesFile = new File(tracesDir, name);
6006 if (curTracesFile.exists()) {
6007 if (lastTracesFile != null) {
6008 curTracesFile.renameTo(lastTracesFile);
6009 } else {
6010 curTracesFile.delete();
6011 }
6012 }
6013 lastTracesFile = curTracesFile;
6014 }
6015 tracesFile.renameTo(curTracesFile);
6016 } finally {
6017 StrictMode.setThreadPolicy(oldPolicy);
6018 }
6019 }
6020
Michal Karpinskida34cd42019-04-02 19:46:52 +01006021 boolean isAssociatedCompanionApp(int userId, int uid) {
6022 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6023 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006024 return false;
6025 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006026 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006027 }
6028
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006029 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006030 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006031
6032
Wale Ogunwale98875612018-10-12 07:53:02 -07006033 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6034 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035
Riddle Hsud93a6c42018-11-29 21:50:06 +08006036 H(Looper looper) {
6037 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006038 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006039
6040 @Override
6041 public void handleMessage(Message msg) {
6042 switch (msg.what) {
6043 case REPORT_TIME_TRACKER_MSG: {
6044 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6045 tracker.deliverResult(mContext);
6046 } break;
6047 }
6048 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006049 }
6050
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006051 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006052 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006053
6054 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006055 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006056 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057
6058 @Override
6059 public void handleMessage(Message msg) {
6060 switch (msg.what) {
6061 case DISMISS_DIALOG_UI_MSG: {
6062 final Dialog d = (Dialog) msg.obj;
6063 d.dismiss();
6064 break;
6065 }
6066 }
6067 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006068 }
6069
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 final class LocalService extends ActivityTaskManagerInternal {
6071 @Override
6072 public SleepToken acquireSleepToken(String tag, int displayId) {
6073 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006074 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 }
6076
6077 @Override
6078 public ComponentName getHomeActivityForUser(int userId) {
6079 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006080 final ActivityRecord homeActivity =
6081 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006082 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006083 }
6084 }
6085
6086 @Override
6087 public void onLocalVoiceInteractionStarted(IBinder activity,
6088 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6089 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092 }
6093
6094 @Override
6095 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6096 synchronized (mGlobalLock) {
6097 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6098 reasons, timestamp);
6099 }
6100 }
6101
6102 @Override
6103 public void notifyAppTransitionFinished() {
6104 synchronized (mGlobalLock) {
6105 mStackSupervisor.notifyAppTransitionDone();
6106 }
6107 }
6108
6109 @Override
6110 public void notifyAppTransitionCancelled() {
6111 synchronized (mGlobalLock) {
6112 mStackSupervisor.notifyAppTransitionDone();
6113 }
6114 }
6115
6116 @Override
6117 public List<IBinder> getTopVisibleActivities() {
6118 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006119 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 }
6121 }
6122
6123 @Override
6124 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006126 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128 }
6129
6130 @Override
6131 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6132 Bundle bOptions) {
6133 Preconditions.checkNotNull(intents, "intents");
6134 final String[] resolvedTypes = new String[intents.length];
6135
6136 // UID of the package on user userId.
6137 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6138 // packageUid may not be initialized.
6139 int packageUid = 0;
6140 final long ident = Binder.clearCallingIdentity();
6141
6142 try {
6143 for (int i = 0; i < intents.length; i++) {
6144 resolvedTypes[i] =
6145 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6146 }
6147
6148 packageUid = AppGlobals.getPackageManager().getPackageUid(
6149 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6150 } catch (RemoteException e) {
6151 // Shouldn't happen.
6152 } finally {
6153 Binder.restoreCallingIdentity(ident);
6154 }
6155
Riddle Hsu591bf612019-02-14 17:55:31 +08006156 return getActivityStartController().startActivitiesInPackage(
6157 packageUid, packageName,
6158 intents, resolvedTypes, null /* resultTo */,
6159 SafeActivityOptions.fromBundle(bOptions), userId,
6160 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6161 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 }
6163
6164 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006165 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6166 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6167 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6168 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006169 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006170 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006171 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6172 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6173 userId, validateIncomingUser, originatingPendingIntent,
6174 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006175 }
6176 }
6177
6178 @Override
6179 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6180 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6181 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6182 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006183 PendingIntentRecord originatingPendingIntent,
6184 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006185 synchronized (mGlobalLock) {
6186 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6187 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6188 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006189 validateIncomingUser, originatingPendingIntent,
6190 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006191 }
6192 }
6193
6194 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6196 Intent intent, Bundle options, int userId) {
6197 return ActivityTaskManagerService.this.startActivityAsUser(
6198 caller, callerPacakge, intent,
6199 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6200 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6201 false /*validateIncomingUser*/);
6202 }
6203
6204 @Override
lumark588a3e82018-07-20 18:53:54 +08006205 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 synchronized (mGlobalLock) {
6207
6208 // We might change the visibilities here, so prepare an empty app transition which
6209 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006210 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006211 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006212 if (activityDisplay == null) {
6213 return;
6214 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006215 final DisplayContent dc = activityDisplay.mDisplayContent;
6216 final boolean wasTransitionSet =
6217 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006219 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006220 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006221 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222
6223 // If there was a transition set already we don't want to interfere with it as we
6224 // might be starting it too early.
6225 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006226 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 }
6228 }
6229 if (callback != null) {
6230 callback.run();
6231 }
6232 }
6233
6234 @Override
6235 public void notifyKeyguardTrustedChanged() {
6236 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006237 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006238 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 }
6240 }
6241 }
6242
6243 /**
6244 * Called after virtual display Id is updated by
6245 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6246 * {@param vrVr2dDisplayId}.
6247 */
6248 @Override
6249 public void setVr2dDisplayId(int vr2dDisplayId) {
6250 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6251 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006252 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 }
6254 }
6255
6256 @Override
6257 public void setFocusedActivity(IBinder token) {
6258 synchronized (mGlobalLock) {
6259 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6260 if (r == null) {
6261 throw new IllegalArgumentException(
6262 "setFocusedActivity: No activity record matching token=" + token);
6263 }
Louis Chang19443452018-10-09 12:10:21 +08006264 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006265 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 }
6267 }
6268 }
6269
6270 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006271 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006272 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006273 }
6274
6275 @Override
6276 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006277 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006278 }
6279
6280 @Override
6281 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006282 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
6284
6285 @Override
6286 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6287 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6288 }
6289
6290 @Override
6291 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006292 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006294
6295 @Override
6296 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6297 synchronized (mGlobalLock) {
6298 mActiveVoiceInteractionServiceComponent = component;
6299 }
6300 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006301
6302 @Override
6303 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6304 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6305 return;
6306 }
6307 synchronized (mGlobalLock) {
6308 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6309 if (types == null) {
6310 if (uid < 0) {
6311 return;
6312 }
6313 types = new ArrayMap<>();
6314 mAllowAppSwitchUids.put(userId, types);
6315 }
6316 if (uid < 0) {
6317 types.remove(type);
6318 } else {
6319 types.put(type, uid);
6320 }
6321 }
6322 }
6323
6324 @Override
6325 public void onUserStopped(int userId) {
6326 synchronized (mGlobalLock) {
6327 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6328 mAllowAppSwitchUids.remove(userId);
6329 }
6330 }
6331
6332 @Override
6333 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6334 synchronized (mGlobalLock) {
6335 return ActivityTaskManagerService.this.isGetTasksAllowed(
6336 caller, callingPid, callingUid);
6337 }
6338 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006339
Riddle Hsua0536432019-02-16 00:38:59 +08006340 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006341 @Override
6342 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006343 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006344 mProcessNames.put(proc.mName, proc.mUid, proc);
6345 }
6346 }
6347
Riddle Hsua0536432019-02-16 00:38:59 +08006348 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349 @Override
6350 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006351 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006352 mProcessNames.remove(name, uid);
6353 }
6354 }
6355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 @Override
6358 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360 if (proc == mHomeProcess) {
6361 mHomeProcess = null;
6362 }
6363 if (proc == mPreviousProcess) {
6364 mPreviousProcess = null;
6365 }
6366 }
6367 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006368
Riddle Hsua0536432019-02-16 00:38:59 +08006369 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006370 @Override
6371 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006372 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006373 return mTopProcessState;
6374 }
6375 }
6376
Riddle Hsua0536432019-02-16 00:38:59 +08006377 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006379 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006380 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006381 return proc == mHeavyWeightProcess;
6382 }
6383 }
6384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006386 @Override
6387 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6390 }
6391 }
6392
6393 @Override
6394 public void finishHeavyWeightApp() {
6395 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006396 if (mHeavyWeightProcess != null) {
6397 mHeavyWeightProcess.finishActivities();
6398 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006399 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6400 mHeavyWeightProcess);
6401 }
6402 }
6403
Riddle Hsua0536432019-02-16 00:38:59 +08006404 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006405 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006406 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006407 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006408 return isSleepingLocked();
6409 }
6410 }
6411
6412 @Override
6413 public boolean isShuttingDown() {
6414 synchronized (mGlobalLock) {
6415 return mShuttingDown;
6416 }
6417 }
6418
6419 @Override
6420 public boolean shuttingDown(boolean booted, int timeout) {
6421 synchronized (mGlobalLock) {
6422 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006423 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006424 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006425 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006426 return mStackSupervisor.shutdownLocked(timeout);
6427 }
6428 }
6429
6430 @Override
6431 public void enableScreenAfterBoot(boolean booted) {
6432 synchronized (mGlobalLock) {
6433 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6434 SystemClock.uptimeMillis());
6435 mWindowManager.enableScreenAfterBoot();
6436 updateEventDispatchingLocked(booted);
6437 }
6438 }
6439
6440 @Override
6441 public boolean showStrictModeViolationDialog() {
6442 synchronized (mGlobalLock) {
6443 return mShowDialogs && !mSleeping && !mShuttingDown;
6444 }
6445 }
6446
6447 @Override
6448 public void showSystemReadyErrorDialogsIfNeeded() {
6449 synchronized (mGlobalLock) {
6450 try {
6451 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6452 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6453 + " data partition or your device will be unstable.");
6454 mUiHandler.post(() -> {
6455 if (mShowDialogs) {
6456 AlertDialog d = new BaseErrorDialog(mUiContext);
6457 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6458 d.setCancelable(false);
6459 d.setTitle(mUiContext.getText(R.string.android_system_label));
6460 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6461 d.setButton(DialogInterface.BUTTON_POSITIVE,
6462 mUiContext.getText(R.string.ok),
6463 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6464 d.show();
6465 }
6466 });
6467 }
6468 } catch (RemoteException e) {
6469 }
6470
6471 if (!Build.isBuildConsistent()) {
6472 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6473 mUiHandler.post(() -> {
6474 if (mShowDialogs) {
6475 AlertDialog d = new BaseErrorDialog(mUiContext);
6476 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6477 d.setCancelable(false);
6478 d.setTitle(mUiContext.getText(R.string.android_system_label));
6479 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6480 d.setButton(DialogInterface.BUTTON_POSITIVE,
6481 mUiContext.getText(R.string.ok),
6482 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6483 d.show();
6484 }
6485 });
6486 }
6487 }
6488 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006489
6490 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006491 public void onProcessMapped(int pid, WindowProcessController proc) {
6492 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006493 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006494 }
6495 }
6496
6497 @Override
6498 public void onProcessUnMapped(int pid) {
6499 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006500 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006501 }
6502 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006503
6504 @Override
6505 public void onPackageDataCleared(String name) {
6506 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006507 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006508 mAppWarnings.onPackageDataCleared(name);
6509 }
6510 }
6511
6512 @Override
6513 public void onPackageUninstalled(String name) {
6514 synchronized (mGlobalLock) {
6515 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006516 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006517 }
6518 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006519
6520 @Override
6521 public void onPackageAdded(String name, boolean replacing) {
6522 synchronized (mGlobalLock) {
6523 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6524 }
6525 }
6526
6527 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006528 public void onPackageReplaced(ApplicationInfo aInfo) {
6529 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006530 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006531 }
6532 }
6533
6534 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006535 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6536 synchronized (mGlobalLock) {
6537 return compatibilityInfoForPackageLocked(ai);
6538 }
6539 }
6540
Yunfan Chen75157d72018-07-27 14:47:21 +09006541 /**
6542 * Set the corresponding display information for the process global configuration. To be
6543 * called when we need to show IME on a different display.
6544 *
6545 * @param pid The process id associated with the IME window.
6546 * @param displayId The ID of the display showing the IME.
6547 */
6548 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006549 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006550 // Don't update process-level configuration for Multi-Client IME process since other
6551 // IMEs on other displays will also receive this configuration change due to IME
6552 // services use the same application config/context.
6553 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006554
Yunfan Chen75157d72018-07-27 14:47:21 +09006555 if (pid == MY_PID || pid < 0) {
6556 if (DEBUG_CONFIGURATION) {
6557 Slog.w(TAG,
6558 "Trying to update display configuration for system/invalid process.");
6559 }
6560 return;
6561 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006562 synchronized (mGlobalLock) {
6563 final ActivityDisplay activityDisplay =
6564 mRootActivityContainer.getActivityDisplay(displayId);
6565 if (activityDisplay == null) {
6566 // Call might come when display is not yet added or has been removed.
6567 if (DEBUG_CONFIGURATION) {
6568 Slog.w(TAG, "Trying to update display configuration for non-existing "
6569 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006570 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006571 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006572 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006573 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006574 if (process == null) {
6575 if (DEBUG_CONFIGURATION) {
6576 Slog.w(TAG, "Trying to update display configuration for invalid "
6577 + "process, pid=" + pid);
6578 }
6579 return;
6580 }
6581 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6582 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006583 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006584
6585 @Override
6586 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6587 int requestCode, int resultCode, Intent data) {
6588 synchronized (mGlobalLock) {
6589 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006590 if (r != null && r.getActivityStack() != null) {
6591 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6592 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006593 }
6594 }
6595 }
6596
6597 @Override
6598 public void clearPendingResultForActivity(IBinder activityToken,
6599 WeakReference<PendingIntentRecord> pir) {
6600 synchronized (mGlobalLock) {
6601 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6602 if (r != null && r.pendingResults != null) {
6603 r.pendingResults.remove(pir);
6604 }
6605 }
6606 }
6607
6608 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006609 public ActivityTokens getTopActivityForTask(int taskId) {
6610 synchronized (mGlobalLock) {
6611 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6612 if (taskRecord == null) {
6613 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6614 + " Requested task not found");
6615 return null;
6616 }
6617 final ActivityRecord activity = taskRecord.getTopActivity();
6618 if (activity == null) {
6619 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6620 + " Requested activity not found");
6621 return null;
6622 }
6623 if (!activity.attachedToProcess()) {
6624 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6625 + activity);
6626 return null;
6627 }
6628 return new ActivityTokens(activity.appToken, activity.assistToken,
6629 activity.app.getThread());
6630 }
6631 }
6632
6633 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006634 public IIntentSender getIntentSender(int type, String packageName,
6635 int callingUid, int userId, IBinder token, String resultWho,
6636 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6637 Bundle bOptions) {
6638 synchronized (mGlobalLock) {
6639 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6640 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6641 }
6642 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006643
6644 @Override
6645 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6646 synchronized (mGlobalLock) {
6647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6648 if (r == null) {
6649 return null;
6650 }
6651 if (r.mServiceConnectionsHolder == null) {
6652 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6653 ActivityTaskManagerService.this, r);
6654 }
6655
6656 return r.mServiceConnectionsHolder;
6657 }
6658 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006659
6660 @Override
6661 public Intent getHomeIntent() {
6662 synchronized (mGlobalLock) {
6663 return ActivityTaskManagerService.this.getHomeIntent();
6664 }
6665 }
6666
6667 @Override
6668 public boolean startHomeActivity(int userId, String reason) {
6669 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006670 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006671 }
6672 }
6673
6674 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006675 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006676 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006677 synchronized (mGlobalLock) {
6678 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006679 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006680 }
Chilun8b1f1be2019-03-13 17:14:36 +08006681 }
6682
6683 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006684 public boolean startHomeOnAllDisplays(int userId, String reason) {
6685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006686 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006687 }
6688 }
6689
Riddle Hsua0536432019-02-16 00:38:59 +08006690 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006691 @Override
6692 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006693 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006694 if (mFactoryTest == FACTORY_TEST_OFF) {
6695 return false;
6696 }
6697 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6698 && wpc.mName.equals(mTopComponent.getPackageName())) {
6699 return true;
6700 }
6701 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6702 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6703 }
6704 }
6705
6706 @Override
6707 public void updateTopComponentForFactoryTest() {
6708 synchronized (mGlobalLock) {
6709 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6710 return;
6711 }
6712 final ResolveInfo ri = mContext.getPackageManager()
6713 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6714 final CharSequence errorMsg;
6715 if (ri != null) {
6716 final ActivityInfo ai = ri.activityInfo;
6717 final ApplicationInfo app = ai.applicationInfo;
6718 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6719 mTopAction = Intent.ACTION_FACTORY_TEST;
6720 mTopData = null;
6721 mTopComponent = new ComponentName(app.packageName, ai.name);
6722 errorMsg = null;
6723 } else {
6724 errorMsg = mContext.getResources().getText(
6725 com.android.internal.R.string.factorytest_not_system);
6726 }
6727 } else {
6728 errorMsg = mContext.getResources().getText(
6729 com.android.internal.R.string.factorytest_no_action);
6730 }
6731 if (errorMsg == null) {
6732 return;
6733 }
6734
6735 mTopAction = null;
6736 mTopData = null;
6737 mTopComponent = null;
6738 mUiHandler.post(() -> {
6739 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6740 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006741 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006742 });
6743 }
6744 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006745
Riddle Hsua0536432019-02-16 00:38:59 +08006746 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006747 @Override
6748 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6749 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006750 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006752 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753
6754 wpc.clearRecentTasks();
6755 wpc.clearActivities();
6756
6757 if (wpc.isInstrumenting()) {
6758 finishInstrumentationCallback.run();
6759 }
6760
Jorim Jaggid0752812018-10-16 16:07:20 +02006761 if (!restarting && hasVisibleActivities) {
6762 mWindowManager.deferSurfaceLayout();
6763 try {
6764 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6765 // If there was nothing to resume, and we are not already restarting
6766 // this process, but there is a visible activity that is hosted by the
6767 // process...then make sure all visible activities are running, taking
6768 // care of restarting this process.
6769 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6770 !PRESERVE_WINDOWS);
6771 }
6772 } finally {
6773 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 }
6776 }
6777 }
6778
6779 @Override
6780 public void closeSystemDialogs(String reason) {
6781 enforceNotIsolatedCaller("closeSystemDialogs");
6782
6783 final int pid = Binder.getCallingPid();
6784 final int uid = Binder.getCallingUid();
6785 final long origId = Binder.clearCallingIdentity();
6786 try {
6787 synchronized (mGlobalLock) {
6788 // Only allow this from foreground processes, so that background
6789 // applications can't abuse it to prevent system UI from being shown.
6790 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006791 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 if (!proc.isPerceptible()) {
6793 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6794 + " from background process " + proc);
6795 return;
6796 }
6797 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 mWindowManager.closeSystemDialogs(reason);
6799
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006802 // Call into AM outside the synchronized block.
6803 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 } finally {
6805 Binder.restoreCallingIdentity(origId);
6806 }
6807 }
6808
6809 @Override
6810 public void cleanupDisabledPackageComponents(
6811 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6812 synchronized (mGlobalLock) {
6813 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006814 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006816 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 mStackSupervisor.scheduleIdleLocked();
6818 }
6819
6820 // Clean-up disabled tasks
6821 getRecentTasks().cleanupDisabledPackageTasksLocked(
6822 packageName, disabledClasses, userId);
6823 }
6824 }
6825
6826 @Override
6827 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6828 int userId) {
6829 synchronized (mGlobalLock) {
6830
6831 boolean didSomething =
6832 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006833 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 null, doit, evenPersistent, userId);
6835 return didSomething;
6836 }
6837 }
6838
6839 @Override
6840 public void resumeTopActivities(boolean scheduleIdle) {
6841 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006842 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 if (scheduleIdle) {
6844 mStackSupervisor.scheduleIdleLocked();
6845 }
6846 }
6847 }
6848
Riddle Hsua0536432019-02-16 00:38:59 +08006849 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 @Override
6851 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006852 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6854 }
6855 }
6856
Riddle Hsua0536432019-02-16 00:38:59 +08006857 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 @Override
6859 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006860 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006861 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
6863 }
6864
6865 @Override
6866 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6867 try {
6868 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6869 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6870 }
6871 } catch (RemoteException ex) {
6872 throw new SecurityException("Fail to check is caller a privileged app", ex);
6873 }
6874
6875 synchronized (mGlobalLock) {
6876 final long ident = Binder.clearCallingIdentity();
6877 try {
6878 if (mAmInternal.shouldConfirmCredentials(userId)) {
6879 if (mKeyguardController.isKeyguardLocked()) {
6880 // Showing launcher to avoid user entering credential twice.
6881 startHomeActivity(currentUserId, "notifyLockedProfile");
6882 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006883 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 }
6885 } finally {
6886 Binder.restoreCallingIdentity(ident);
6887 }
6888 }
6889 }
6890
6891 @Override
6892 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6893 mAmInternal.enforceCallingPermission(
6894 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6895
6896 synchronized (mGlobalLock) {
6897 final long ident = Binder.clearCallingIdentity();
6898 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006899 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6900 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6903 UserHandle.CURRENT);
6904 } finally {
6905 Binder.restoreCallingIdentity(ident);
6906 }
6907 }
6908 }
6909
6910 @Override
6911 public void writeActivitiesToProto(ProtoOutputStream proto) {
6912 synchronized (mGlobalLock) {
6913 // The output proto of "activity --proto activities"
6914 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006915 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006916 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6917 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 }
6919 }
6920
6921 @Override
6922 public void saveANRState(String reason) {
6923 synchronized (mGlobalLock) {
6924 final StringWriter sw = new StringWriter();
6925 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6926 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6927 if (reason != null) {
6928 pw.println(" Reason: " + reason);
6929 }
6930 pw.println();
6931 getActivityStartController().dump(pw, " ", null);
6932 pw.println();
6933 pw.println("-------------------------------------------------------------------------------");
6934 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6935 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6936 "" /* header */);
6937 pw.println();
6938 pw.close();
6939
6940 mLastANRState = sw.toString();
6941 }
6942 }
6943
6944 @Override
6945 public void clearSavedANRState() {
6946 synchronized (mGlobalLock) {
6947 mLastANRState = null;
6948 }
6949 }
6950
6951 @Override
6952 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6953 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6954 synchronized (mGlobalLock) {
6955 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6956 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6957 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6958 dumpLastANRLocked(pw);
6959 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6960 dumpLastANRTracesLocked(pw);
6961 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6962 dumpActivityStarterLocked(pw, dumpPackage);
6963 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6964 dumpActivityContainersLocked(pw);
6965 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6966 if (getRecentTasks() != null) {
6967 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6968 }
6969 }
6970 }
6971 }
6972
6973 @Override
6974 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6975 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6976 int wakefulness) {
6977 synchronized (mGlobalLock) {
6978 if (mHomeProcess != null && (dumpPackage == null
6979 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6980 if (needSep) {
6981 pw.println();
6982 needSep = false;
6983 }
6984 pw.println(" mHomeProcess: " + mHomeProcess);
6985 }
6986 if (mPreviousProcess != null && (dumpPackage == null
6987 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6988 if (needSep) {
6989 pw.println();
6990 needSep = false;
6991 }
6992 pw.println(" mPreviousProcess: " + mPreviousProcess);
6993 }
6994 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6995 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6996 StringBuilder sb = new StringBuilder(128);
6997 sb.append(" mPreviousProcessVisibleTime: ");
6998 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6999 pw.println(sb);
7000 }
7001 if (mHeavyWeightProcess != null && (dumpPackage == null
7002 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7003 if (needSep) {
7004 pw.println();
7005 needSep = false;
7006 }
7007 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7008 }
7009 if (dumpPackage == null) {
7010 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007011 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 }
7013 if (dumpAll) {
7014 if (dumpPackage == null) {
7015 pw.println(" mConfigWillChange: "
7016 + getTopDisplayFocusedStack().mConfigWillChange);
7017 }
7018 if (mCompatModePackages.getPackages().size() > 0) {
7019 boolean printed = false;
7020 for (Map.Entry<String, Integer> entry
7021 : mCompatModePackages.getPackages().entrySet()) {
7022 String pkg = entry.getKey();
7023 int mode = entry.getValue();
7024 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7025 continue;
7026 }
7027 if (!printed) {
7028 pw.println(" mScreenCompatPackages:");
7029 printed = true;
7030 }
7031 pw.println(" " + pkg + ": " + mode);
7032 }
7033 }
7034 }
7035
7036 if (dumpPackage == null) {
7037 pw.println(" mWakefulness="
7038 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007039 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 if (mRunningVoice != null) {
7041 pw.println(" mRunningVoice=" + mRunningVoice);
7042 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7043 }
7044 pw.println(" mSleeping=" + mSleeping);
7045 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7046 pw.println(" mVrController=" + mVrController);
7047 }
7048 if (mCurAppTimeTracker != null) {
7049 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7050 }
7051 if (mAllowAppSwitchUids.size() > 0) {
7052 boolean printed = false;
7053 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7054 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7055 for (int j = 0; j < types.size(); j++) {
7056 if (dumpPackage == null ||
7057 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7058 if (needSep) {
7059 pw.println();
7060 needSep = false;
7061 }
7062 if (!printed) {
7063 pw.println(" mAllowAppSwitchUids:");
7064 printed = true;
7065 }
7066 pw.print(" User ");
7067 pw.print(mAllowAppSwitchUids.keyAt(i));
7068 pw.print(": Type ");
7069 pw.print(types.keyAt(j));
7070 pw.print(" = ");
7071 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7072 pw.println();
7073 }
7074 }
7075 }
7076 }
7077 if (dumpPackage == null) {
7078 if (mController != null) {
7079 pw.println(" mController=" + mController
7080 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7081 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007082 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7083 pw.println(" mLaunchingActivityWakeLock="
7084 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007085 }
7086
7087 return needSep;
7088 }
7089 }
7090
7091 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007092 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7093 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 synchronized (mGlobalLock) {
7095 if (dumpPackage == null) {
7096 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7097 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007098 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7099 if (mRunningVoice != null) {
7100 final long vrToken = proto.start(
7101 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7102 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7103 mRunningVoice.toString());
7104 mVoiceWakeLock.writeToProto(
7105 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7106 proto.end(vrToken);
7107 }
7108 mVrController.writeToProto(proto,
7109 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 if (mController != null) {
7111 final long token = proto.start(CONTROLLER);
7112 proto.write(CONTROLLER, mController.toString());
7113 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7114 proto.end(token);
7115 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007116 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7117 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7118 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120
7121 if (mHomeProcess != null && (dumpPackage == null
7122 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007123 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125
7126 if (mPreviousProcess != null && (dumpPackage == null
7127 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007128 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7130 }
7131
7132 if (mHeavyWeightProcess != null && (dumpPackage == null
7133 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007134 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 }
7136
7137 for (Map.Entry<String, Integer> entry
7138 : mCompatModePackages.getPackages().entrySet()) {
7139 String pkg = entry.getKey();
7140 int mode = entry.getValue();
7141 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7142 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7143 proto.write(PACKAGE, pkg);
7144 proto.write(MODE, mode);
7145 proto.end(compatToken);
7146 }
7147 }
7148
7149 if (mCurAppTimeTracker != null) {
7150 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7151 }
7152
7153 }
7154 }
7155
7156 @Override
7157 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7158 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7159 boolean dumpFocusedStackOnly) {
7160 synchronized (mGlobalLock) {
7161 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7162 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7163 }
7164 }
7165
7166 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007167 public void dumpForOom(PrintWriter pw) {
7168 synchronized (mGlobalLock) {
7169 pw.println(" mHomeProcess: " + mHomeProcess);
7170 pw.println(" mPreviousProcess: " + mPreviousProcess);
7171 if (mHeavyWeightProcess != null) {
7172 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7173 }
7174 }
7175 }
7176
7177 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007178 public boolean canGcNow() {
7179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007180 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 }
7182 }
7183
Riddle Hsua0536432019-02-16 00:38:59 +08007184 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007185 @Override
7186 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007187 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007188 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 return top != null ? top.app : null;
7190 }
7191 }
7192
Riddle Hsua0536432019-02-16 00:38:59 +08007193 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 @Override
7195 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007196 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007197 if (mRootActivityContainer != null) {
7198 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 }
7200 }
7201 }
7202
7203 @Override
7204 public void scheduleDestroyAllActivities(String reason) {
7205 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007206 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 }
7208 }
7209
7210 @Override
7211 public void removeUser(int userId) {
7212 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007213 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007214 }
7215 }
7216
7217 @Override
7218 public boolean switchUser(int userId, UserState userState) {
7219 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007220 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 }
7222 }
7223
7224 @Override
7225 public void onHandleAppCrash(WindowProcessController wpc) {
7226 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007227 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 }
7229 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007230
7231 @Override
7232 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7233 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007234 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007235 }
7236 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007237
Riddle Hsua0536432019-02-16 00:38:59 +08007238 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007239 @Override
7240 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007241 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007242 }
7243
Riddle Hsua0536432019-02-16 00:38:59 +08007244 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007245 @Override
7246 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007247 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007248 }
7249
Riddle Hsua0536432019-02-16 00:38:59 +08007250 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007251 @Override
7252 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007253 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007254 }
7255
Riddle Hsua0536432019-02-16 00:38:59 +08007256 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007257 @Override
7258 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007259 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007260 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007261
7262 @Override
7263 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007264 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007265 mPendingTempWhitelist.put(uid, tag);
7266 }
7267 }
7268
7269 @Override
7270 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007271 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007272 mPendingTempWhitelist.remove(uid);
7273 }
7274 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007275
7276 @Override
7277 public boolean handleAppCrashInActivityController(String processName, int pid,
7278 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7279 Runnable killCrashingAppCallback) {
7280 synchronized (mGlobalLock) {
7281 if (mController == null) {
7282 return false;
7283 }
7284
7285 try {
7286 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7287 stackTrace)) {
7288 killCrashingAppCallback.run();
7289 return true;
7290 }
7291 } catch (RemoteException e) {
7292 mController = null;
7293 Watchdog.getInstance().setActivityController(null);
7294 }
7295 return false;
7296 }
7297 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007298
7299 @Override
7300 public void removeRecentTasksByPackageName(String packageName, int userId) {
7301 synchronized (mGlobalLock) {
7302 mRecentTasks.removeTasksByPackageName(packageName, userId);
7303 }
7304 }
7305
7306 @Override
7307 public void cleanupRecentTasksForUser(int userId) {
7308 synchronized (mGlobalLock) {
7309 mRecentTasks.cleanupLocked(userId);
7310 }
7311 }
7312
7313 @Override
7314 public void loadRecentTasksForUser(int userId) {
7315 synchronized (mGlobalLock) {
7316 mRecentTasks.loadUserRecentsLocked(userId);
7317 }
7318 }
7319
7320 @Override
7321 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7322 synchronized (mGlobalLock) {
7323 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7324 }
7325 }
7326
7327 @Override
7328 public void flushRecentTasks() {
7329 mRecentTasks.flush();
7330 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007331
7332 @Override
7333 public WindowProcessController getHomeProcess() {
7334 synchronized (mGlobalLock) {
7335 return mHomeProcess;
7336 }
7337 }
7338
7339 @Override
7340 public WindowProcessController getPreviousProcess() {
7341 synchronized (mGlobalLock) {
7342 return mPreviousProcess;
7343 }
7344 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007345
7346 @Override
7347 public void clearLockedTasks(String reason) {
7348 synchronized (mGlobalLock) {
7349 getLockTaskController().clearLockedTasks(reason);
7350 }
7351 }
7352
7353 @Override
7354 public void updateUserConfiguration() {
7355 synchronized (mGlobalLock) {
7356 final Configuration configuration = new Configuration(getGlobalConfiguration());
7357 final int currentUserId = mAmInternal.getCurrentUserId();
7358 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7359 configuration, currentUserId, Settings.System.canWrite(mContext));
7360 updateConfigurationLocked(configuration, null /* starting */,
7361 false /* initLocale */, false /* persistent */, currentUserId,
7362 false /* deferResume */);
7363 }
7364 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007365
7366 @Override
7367 public boolean canShowErrorDialogs() {
7368 synchronized (mGlobalLock) {
7369 return mShowDialogs && !mSleeping && !mShuttingDown
7370 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7371 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7372 mAmInternal.getCurrentUserId())
7373 && !(UserManager.isDeviceInDemoMode(mContext)
7374 && mAmInternal.getCurrentUser().isDemo());
7375 }
7376 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007377
7378 @Override
7379 public void setProfileApp(String profileApp) {
7380 synchronized (mGlobalLock) {
7381 mProfileApp = profileApp;
7382 }
7383 }
7384
7385 @Override
7386 public void setProfileProc(WindowProcessController wpc) {
7387 synchronized (mGlobalLock) {
7388 mProfileProc = wpc;
7389 }
7390 }
7391
7392 @Override
7393 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7394 synchronized (mGlobalLock) {
7395 mProfilerInfo = profilerInfo;
7396 }
7397 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007398
7399 @Override
7400 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7401 synchronized (mGlobalLock) {
7402 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7403 }
7404 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007405
7406 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007407 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7408 boolean reducedResolution) {
7409 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7410 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007411 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007412
7413 @Override
7414 public boolean isUidForeground(int uid) {
7415 synchronized (mGlobalLock) {
7416 return ActivityTaskManagerService.this.isUidForeground(uid);
7417 }
7418 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007419
7420 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007421 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007422 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007423 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007424 }
7425 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007426
7427 @Override
7428 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007429 // Translate package names into UIDs
7430 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007431 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007432 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7433 if (uid >= 0) {
7434 result.add(uid);
7435 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007436 }
7437 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007438 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007439 }
7440 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007441 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007442}