blob: 7284e0f70b54e43a39aaa92f82ad57eedc699226 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100314 // How long we permit background activity starts after an activity in the process
315 // started or finished.
316 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317
Wale Ogunwale98875612018-10-12 07:53:02 -0700318 /** Used to indicate that an app transition should be animated. */
319 static final boolean ANIMATE = true;
320
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700321 /** Hardware-reported OpenGLES version. */
322 final int GL_ES_VERSION;
323
Wale Ogunwale31913b52018-10-13 08:29:31 -0700324 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
325 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
326 public static final String DUMP_LASTANR_CMD = "lastanr" ;
327 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
328 public static final String DUMP_STARTER_CMD = "starter" ;
329 public static final String DUMP_CONTAINERS_CMD = "containers" ;
330 public static final String DUMP_RECENTS_CMD = "recents" ;
331 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
332
Wale Ogunwale64258362018-10-16 15:13:37 -0700333 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
334 public static final int RELAUNCH_REASON_NONE = 0;
335 /** This activity is being relaunched due to windowing mode change. */
336 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
337 /** This activity is being relaunched due to a free-resize operation. */
338 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
339
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700340 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700341
Wale Ogunwalef6733932018-06-27 05:14:34 -0700342 /**
343 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
344 * change at runtime. Use mContext for non-UI purposes.
345 */
346 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700348 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700351 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700352 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800353 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800354 @VisibleForTesting
355 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 PowerManagerInternal mPowerManagerInternal;
357 private UsageStatsManagerInternal mUsageStatsInternal;
358
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700359 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 IntentFirewall mIntentFirewall;
361
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700362 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800363 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 /**
365 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
366 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
367 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
368 *
369 * @see WindowManagerThreadPriorityBooster
370 */
371 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800373 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700374 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700375 private UserManagerService mUserManager;
376 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700377 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800378 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700379 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** All processes currently running that might have a window organized by name. */
381 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100382 /** All processes we currently have running mapped by pid and uid */
383 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** This is the process holding what we currently consider to be the "home" activity. */
385 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700386 /** The currently running heavy-weight process, if any. */
387 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700388 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /**
390 * This is the process holding the activity the user last visited that is in a different process
391 * from the one they are currently in.
392 */
393 WindowProcessController mPreviousProcess;
394 /** The time at which the previous process was last visible. */
395 long mPreviousProcessVisibleTime;
396
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700397 /** List of intents that were used to start the most recent tasks. */
398 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700399 /** State of external calls telling us if the device is awake or asleep. */
400 private boolean mKeyguardShown = false;
401
402 // Wrapper around VoiceInteractionServiceManager
403 private AssistUtils mAssistUtils;
404
405 // VoiceInteraction session ID that changes for each new request except when
406 // being called for multi-window assist in a single session.
407 private int mViSessionId = 1000;
408
409 // How long to wait in getAssistContextExtras for the activity and foreground services
410 // to respond with the result.
411 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
412
413 // How long top wait when going through the modern assist (which doesn't need to block
414 // on getting this result before starting to launch its UI).
415 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
416
417 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
418 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
419
Alison Cichowlas3e340502018-08-07 17:15:01 -0400420 // Permission tokens are used to temporarily granted a trusted app the ability to call
421 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
422 // showing any appropriate error messages to the user.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
424 10 * MINUTE_IN_MILLIS;
425
426 // How long before the service actually expires a token. This is slightly longer than
427 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
428 // expiration exception.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
430 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
431
432 // How long the service will remember expired tokens, for the purpose of providing error
433 // messaging when a client uses an expired token.
434 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
435 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
436
Marvin Ramin830d4e32019-03-12 13:16:58 +0100437 // How long to whitelist the Services for when requested.
438 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
439
Alison Cichowlas3e340502018-08-07 17:15:01 -0400440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
466 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
553 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
602 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
603 // automatically. Important for devices without direct input devices.
604 private boolean mShowDialogs = true;
605
606 /** Set if we are shutting down the system, similar to sleeping. */
607 boolean mShuttingDown = false;
608
609 /**
610 * We want to hold a wake lock while running a voice interaction session, since
611 * this may happen with the screen off and we need to keep the CPU running to
612 * be able to continue to interact with the user.
613 */
614 PowerManager.WakeLock mVoiceWakeLock;
615
616 /**
617 * Set while we are running a voice interaction. This overrides sleeping while it is active.
618 */
619 IVoiceInteractionSession mRunningVoice;
620
621 /**
622 * The last resumed activity. This is identical to the current resumed activity most
623 * of the time but could be different when we're pausing one activity before we resume
624 * another activity.
625 */
626 ActivityRecord mLastResumedActivity;
627
628 /**
629 * The activity that is currently being traced as the active resumed activity.
630 *
631 * @see #updateResumedAppTrace
632 */
633 private @Nullable ActivityRecord mTracedResumedActivity;
634
635 /** If non-null, we are tracking the time the user spends in the currently focused app. */
636 AppTimeTracker mCurAppTimeTracker;
637
Wale Ogunwale008163e2018-07-23 23:11:08 -0700638 private AppWarnings mAppWarnings;
639
Wale Ogunwale53783742018-09-16 10:21:51 -0700640 /**
641 * Packages that the user has asked to have run in screen size
642 * compatibility mode instead of filling the screen.
643 */
644 CompatModePackages mCompatModePackages;
645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private FontScaleSettingObserver mFontScaleSettingObserver;
647
Ricky Wai96f5c352019-04-10 18:40:17 +0100648 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000649
Wale Ogunwalef6733932018-06-27 05:14:34 -0700650 private final class FontScaleSettingObserver extends ContentObserver {
651 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
652 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
653
654 public FontScaleSettingObserver() {
655 super(mH);
656 final ContentResolver resolver = mContext.getContentResolver();
657 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
658 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
659 UserHandle.USER_ALL);
660 }
661
662 @Override
663 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
664 if (mFontScaleUri.equals(uri)) {
665 updateFontScaleIfNeeded(userId);
666 } else if (mHideErrorDialogsUri.equals(uri)) {
667 synchronized (mGlobalLock) {
668 updateShouldShowDialogsLocked(getGlobalConfiguration());
669 }
670 }
671 }
672 }
673
Riddle Hsua0536432019-02-16 00:38:59 +0800674 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
675 @Target(ElementType.METHOD)
676 @Retention(RetentionPolicy.SOURCE)
677 @interface HotPath {
678 int NONE = 0;
679 int OOM_ADJUSTMENT = 1;
680 int LRU_UPDATE = 2;
681 int PROCESS_CHANGE = 3;
682 int caller() default NONE;
683 }
684
Charles Chen8d98dd22018-12-26 17:36:54 +0800685 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
686 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700687 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700688 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 mSystemThread = ActivityThread.currentActivityThread();
690 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700691 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800692 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700693 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void onSystemReady() {
697 synchronized (mGlobalLock) {
698 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
699 PackageManager.FEATURE_CANT_SAVE_STATE);
700 mAssistUtils = new AssistUtils(mContext);
701 mVrController.onSystemReady();
702 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700703 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void onInitPowerManagement() {
708 synchronized (mGlobalLock) {
709 mStackSupervisor.initPowerManagement();
710 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
711 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
712 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
713 mVoiceWakeLock.setReferenceCounted(false);
714 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700718 mFontScaleSettingObserver = new FontScaleSettingObserver();
719 }
720
Wale Ogunwale59507092018-10-29 09:00:30 -0700721 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722 final boolean freeformWindowManagement =
723 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
724 || Settings.Global.getInt(
725 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
726
727 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
728 final boolean supportsPictureInPicture = supportsMultiWindow &&
729 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
730 final boolean supportsSplitScreenMultiWindow =
731 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
732 final boolean supportsMultiDisplay = mContext.getPackageManager()
733 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
735 final boolean forceResizable = Settings.Global.getInt(
736 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700737 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738
739 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900740 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700741
742 final Configuration configuration = new Configuration();
743 Settings.System.getConfiguration(resolver, configuration);
744 if (forceRtl) {
745 // This will take care of setting the correct layout direction flags
746 configuration.setLayoutDirection(configuration.locale);
747 }
748
749 synchronized (mGlobalLock) {
750 mForceResizableActivities = forceResizable;
751 final boolean multiWindowFormEnabled = freeformWindowManagement
752 || supportsSplitScreenMultiWindow
753 || supportsPictureInPicture
754 || supportsMultiDisplay;
755 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
756 mSupportsMultiWindow = true;
757 mSupportsFreeformWindowManagement = freeformWindowManagement;
758 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
759 mSupportsPictureInPicture = supportsPictureInPicture;
760 mSupportsMultiDisplay = supportsMultiDisplay;
761 } else {
762 mSupportsMultiWindow = false;
763 mSupportsFreeformWindowManagement = false;
764 mSupportsSplitScreenMultiWindow = false;
765 mSupportsPictureInPicture = false;
766 mSupportsMultiDisplay = false;
767 }
768 mWindowManager.setForceResizableTasks(mForceResizableActivities);
769 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700770 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
771 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700772 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 // This happens before any activities are started, so we can change global configuration
774 // in-place.
775 updateConfigurationLocked(configuration, null, true);
776 final Configuration globalConfig = getGlobalConfiguration();
777 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
778
779 // Load resources only after the current configuration has been set.
780 final Resources res = mContext.getResources();
781 mThumbnailWidth = res.getDimensionPixelSize(
782 com.android.internal.R.dimen.thumbnail_width);
783 mThumbnailHeight = res.getDimensionPixelSize(
784 com.android.internal.R.dimen.thumbnail_height);
785
786 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
787 mFullscreenThumbnailScale = (float) res
788 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
789 (float) globalConfig.screenWidthDp;
790 } else {
791 mFullscreenThumbnailScale = res.getFraction(
792 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
793 }
794 }
795 }
796
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800797 public WindowManagerGlobalLock getGlobalLock() {
798 return mGlobalLock;
799 }
800
Yunfan Chen585f2932019-01-29 16:04:45 +0900801 /** For test purpose only. */
802 @VisibleForTesting
803 public ActivityTaskManagerInternal getAtmInternal() {
804 return mInternal;
805 }
806
Riddle Hsud93a6c42018-11-29 21:50:06 +0800807 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
808 Looper looper) {
809 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700812 final File systemDir = SystemServiceManager.ensureSystemDir();
813 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
814 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700815 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700816
817 mTempConfig.setToDefaults();
818 mTempConfig.setLocales(LocaleList.getDefault());
819 mConfigurationSeq = mTempConfig.seq = 1;
820 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800821 mRootActivityContainer = new RootActivityContainer(this);
822 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700824 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700826 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700827 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700828 mRecentTasks = createRecentTasks();
829 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700831 mKeyguardController = mStackSupervisor.getKeyguardController();
832 }
833
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700834 public void onActivityManagerInternalAdded() {
835 synchronized (mGlobalLock) {
836 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
837 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
838 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700839 }
840
Yunfan Chen75157d72018-07-27 14:47:21 +0900841 int increaseConfigurationSeqLocked() {
842 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
843 return mConfigurationSeq;
844 }
845
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700846 protected ActivityStackSupervisor createStackSupervisor() {
847 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
848 supervisor.initialize();
849 return supervisor;
850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setWindowManager(WindowManagerService wm) {
853 synchronized (mGlobalLock) {
854 mWindowManager = wm;
855 mLockTaskController.setWindowManager(wm);
856 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800857 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 }
860
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700861 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
862 synchronized (mGlobalLock) {
863 mUsageStatsInternal = usageStatsManager;
864 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700865 }
866
Wale Ogunwalef6733932018-06-27 05:14:34 -0700867 UserManagerService getUserManager() {
868 if (mUserManager == null) {
869 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
870 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
871 }
872 return mUserManager;
873 }
874
875 AppOpsService getAppOpsService() {
876 if (mAppOpsService == null) {
877 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
878 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
879 }
880 return mAppOpsService;
881 }
882
883 boolean hasUserRestriction(String restriction, int userId) {
884 return getUserManager().hasUserRestriction(restriction, userId);
885 }
886
Michal Karpinski15486842019-04-25 17:33:42 +0100887 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
888 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
889 callingUid, callingPackage);
890 if (mode == AppOpsManager.MODE_DEFAULT) {
891 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
892 == PERMISSION_GRANTED;
893 }
894 return mode == AppOpsManager.MODE_ALLOWED;
895 }
896
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700897 protected RecentTasks createRecentTasks() {
898 return new RecentTasks(this, mStackSupervisor);
899 }
900
901 RecentTasks getRecentTasks() {
902 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 ClientLifecycleManager getLifecycleManager() {
906 return mLifecycleManager;
907 }
908
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700909 ActivityStartController getActivityStartController() {
910 return mActivityStartController;
911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 TaskChangeNotificationController getTaskChangeNotificationController() {
914 return mTaskChangeNotificationController;
915 }
916
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700917 LockTaskController getLockTaskController() {
918 return mLockTaskController;
919 }
920
Yunfan Chen75157d72018-07-27 14:47:21 +0900921 /**
922 * Return the global configuration used by the process corresponding to the input pid. This is
923 * usually the global configuration with some overrides specific to that process.
924 */
925 Configuration getGlobalConfigurationForCallingPid() {
926 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800927 return getGlobalConfigurationForPid(pid);
928 }
929
930 /**
931 * Return the global configuration used by the process corresponding to the given pid.
932 */
933 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900934 if (pid == MY_PID || pid < 0) {
935 return getGlobalConfiguration();
936 }
937 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100938 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 return app != null ? app.getConfiguration() : getGlobalConfiguration();
940 }
941 }
942
943 /**
944 * Return the device configuration info used by the process corresponding to the input pid.
945 * The value is consistent with the global configuration for the process.
946 */
947 @Override
948 public ConfigurationInfo getDeviceConfigurationInfo() {
949 ConfigurationInfo config = new ConfigurationInfo();
950 synchronized (mGlobalLock) {
951 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
952 config.reqTouchScreen = globalConfig.touchscreen;
953 config.reqKeyboardType = globalConfig.keyboard;
954 config.reqNavigation = globalConfig.navigation;
955 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
956 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
958 }
959 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
960 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
961 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
962 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700963 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900964 }
965 return config;
966 }
967
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700968 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700969 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700970 }
971
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700972 public static final class Lifecycle extends SystemService {
973 private final ActivityTaskManagerService mService;
974
975 public Lifecycle(Context context) {
976 super(context);
977 mService = new ActivityTaskManagerService(context);
978 }
979
980 @Override
981 public void onStart() {
982 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700983 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700984 }
985
Garfield Tan891146c2018-10-09 12:14:00 -0700986 @Override
987 public void onUnlockUser(int userId) {
988 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800989 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700990 }
991 }
992
993 @Override
994 public void onCleanupUser(int userId) {
995 synchronized (mService.getGlobalLock()) {
996 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
997 }
998 }
999
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 public ActivityTaskManagerService getService() {
1001 return mService;
1002 }
1003 }
1004
1005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 public final int startActivity(IApplicationThread caller, String callingPackage,
1007 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1008 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1009 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1010 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1011 UserHandle.getCallingUserId());
1012 }
1013
1014 @Override
1015 public final int startActivities(IApplicationThread caller, String callingPackage,
1016 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1017 int userId) {
1018 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001019 enforceNotIsolatedCaller(reason);
1020 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001022 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1023 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1024 reason, null /* originatingPendingIntent */,
1025 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 }
1027
1028 @Override
1029 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1030 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1032 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1033 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1034 true /*validateIncomingUser*/);
1035 }
1036
1037 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1040 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001043 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1045
1046 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001047 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 .setCaller(caller)
1049 .setCallingPackage(callingPackage)
1050 .setResolvedType(resolvedType)
1051 .setResultTo(resultTo)
1052 .setResultWho(resultWho)
1053 .setRequestCode(requestCode)
1054 .setStartFlags(startFlags)
1055 .setProfilerInfo(profilerInfo)
1056 .setActivityOptions(bOptions)
1057 .setMayWait(userId)
1058 .execute();
1059
1060 }
1061
1062 @Override
1063 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1064 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1066 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 // Refuse possible leaked file descriptors
1068 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1069 throw new IllegalArgumentException("File descriptors passed in Intent");
1070 }
1071
1072 if (!(target instanceof PendingIntentRecord)) {
1073 throw new IllegalArgumentException("Bad PendingIntent object");
1074 }
1075
1076 PendingIntentRecord pir = (PendingIntentRecord)target;
1077
1078 synchronized (mGlobalLock) {
1079 // If this is coming from the currently resumed activity, it is
1080 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001081 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 if (stack.mResumedActivity != null &&
1083 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001084 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 }
1086 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001087 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 }
1090
1091 @Override
1092 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1093 Bundle bOptions) {
1094 // Refuse possible leaked file descriptors
1095 if (intent != null && intent.hasFileDescriptors()) {
1096 throw new IllegalArgumentException("File descriptors passed in Intent");
1097 }
1098 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1099
1100 synchronized (mGlobalLock) {
1101 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1102 if (r == null) {
1103 SafeActivityOptions.abort(options);
1104 return false;
1105 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001106 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 // The caller is not running... d'oh!
1108 SafeActivityOptions.abort(options);
1109 return false;
1110 }
1111 intent = new Intent(intent);
1112 // The caller is not allowed to change the data.
1113 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1114 // And we are resetting to find the next component...
1115 intent.setComponent(null);
1116
1117 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1118
1119 ActivityInfo aInfo = null;
1120 try {
1121 List<ResolveInfo> resolves =
1122 AppGlobals.getPackageManager().queryIntentActivities(
1123 intent, r.resolvedType,
1124 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1125 UserHandle.getCallingUserId()).getList();
1126
1127 // Look for the original activity in the list...
1128 final int N = resolves != null ? resolves.size() : 0;
1129 for (int i=0; i<N; i++) {
1130 ResolveInfo rInfo = resolves.get(i);
1131 if (rInfo.activityInfo.packageName.equals(r.packageName)
1132 && rInfo.activityInfo.name.equals(r.info.name)) {
1133 // We found the current one... the next matching is
1134 // after it.
1135 i++;
1136 if (i<N) {
1137 aInfo = resolves.get(i).activityInfo;
1138 }
1139 if (debug) {
1140 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1141 + "/" + r.info.name);
1142 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1143 ? "null" : aInfo.packageName + "/" + aInfo.name));
1144 }
1145 break;
1146 }
1147 }
1148 } catch (RemoteException e) {
1149 }
1150
1151 if (aInfo == null) {
1152 // Nobody who is next!
1153 SafeActivityOptions.abort(options);
1154 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1155 return false;
1156 }
1157
1158 intent.setComponent(new ComponentName(
1159 aInfo.applicationInfo.packageName, aInfo.name));
1160 intent.setFlags(intent.getFlags()&~(
1161 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1162 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1163 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1164 FLAG_ACTIVITY_NEW_TASK));
1165
1166 // Okay now we need to start the new activity, replacing the currently running activity.
1167 // This is a little tricky because we want to start the new one as if the current one is
1168 // finished, but not finish the current one first so that there is no flicker.
1169 // And thus...
1170 final boolean wasFinishing = r.finishing;
1171 r.finishing = true;
1172
1173 // Propagate reply information over to the new activity.
1174 final ActivityRecord resultTo = r.resultTo;
1175 final String resultWho = r.resultWho;
1176 final int requestCode = r.requestCode;
1177 r.resultTo = null;
1178 if (resultTo != null) {
1179 resultTo.removeResultsLocked(r, resultWho, requestCode);
1180 }
1181
1182 final long origId = Binder.clearCallingIdentity();
1183 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001184 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001185 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001186 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001187 .setResolvedType(r.resolvedType)
1188 .setActivityInfo(aInfo)
1189 .setResultTo(resultTo != null ? resultTo.appToken : null)
1190 .setResultWho(resultWho)
1191 .setRequestCode(requestCode)
1192 .setCallingPid(-1)
1193 .setCallingUid(r.launchedFromUid)
1194 .setCallingPackage(r.launchedFromPackage)
1195 .setRealCallingPid(-1)
1196 .setRealCallingUid(r.launchedFromUid)
1197 .setActivityOptions(options)
1198 .execute();
1199 Binder.restoreCallingIdentity(origId);
1200
1201 r.finishing = wasFinishing;
1202 if (res != ActivityManager.START_SUCCESS) {
1203 return false;
1204 }
1205 return true;
1206 }
1207 }
1208
1209 @Override
1210 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1211 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1212 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1213 final WaitResult res = new WaitResult();
1214 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001215 enforceNotIsolatedCaller("startActivityAndWait");
1216 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1217 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001219 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 .setCaller(caller)
1221 .setCallingPackage(callingPackage)
1222 .setResolvedType(resolvedType)
1223 .setResultTo(resultTo)
1224 .setResultWho(resultWho)
1225 .setRequestCode(requestCode)
1226 .setStartFlags(startFlags)
1227 .setActivityOptions(bOptions)
1228 .setMayWait(userId)
1229 .setProfilerInfo(profilerInfo)
1230 .setWaitResult(res)
1231 .execute();
1232 }
1233 return res;
1234 }
1235
1236 @Override
1237 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1238 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1239 int startFlags, Configuration config, Bundle bOptions, int userId) {
1240 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001241 enforceNotIsolatedCaller("startActivityWithConfig");
1242 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1243 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001245 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 .setCaller(caller)
1247 .setCallingPackage(callingPackage)
1248 .setResolvedType(resolvedType)
1249 .setResultTo(resultTo)
1250 .setResultWho(resultWho)
1251 .setRequestCode(requestCode)
1252 .setStartFlags(startFlags)
1253 .setGlobalConfiguration(config)
1254 .setActivityOptions(bOptions)
1255 .setMayWait(userId)
1256 .execute();
1257 }
1258 }
1259
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260
1261 @Override
1262 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1263 int callingUid = Binder.getCallingUid();
1264 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1265 throw new SecurityException("Only the system process can request a permission token, "
1266 + "received request from uid: " + callingUid);
1267 }
1268 IBinder permissionToken = new Binder();
1269 synchronized (mGlobalLock) {
1270 mStartActivitySources.put(permissionToken, delegatorToken);
1271 }
1272
1273 Message expireMsg = PooledLambda.obtainMessage(
1274 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1275 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1276
1277 Message forgetMsg = PooledLambda.obtainMessage(
1278 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1279 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1280
1281 return permissionToken;
1282 }
1283
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 @Override
1285 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1286 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001287 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1288 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001290 // permission grants) as any app that may launch one of your own activities. So we only
1291 // allow this in two cases:
1292 // 1) The caller is an activity that is part of the core framework, and then only when it
1293 // is running as the system.
1294 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1295 // can only be requested by a system activity, which may then delegate this call to
1296 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 final ActivityRecord sourceRecord;
1298 final int targetUid;
1299 final String targetPackage;
1300 final boolean isResolver;
1301 synchronized (mGlobalLock) {
1302 if (resultTo == null) {
1303 throw new SecurityException("Must be called from an activity");
1304 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001305 final IBinder sourceToken;
1306 if (permissionToken != null) {
1307 // To even attempt to use a permissionToken, an app must also have this signature
1308 // permission.
1309 mAmInternal.enforceCallingPermission(
1310 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1311 "startActivityAsCaller");
1312 // If called with a permissionToken, we want the sourceRecord from the delegator
1313 // activity that requested this token.
1314 sourceToken = mStartActivitySources.remove(permissionToken);
1315 if (sourceToken == null) {
1316 // Invalid permissionToken, check if it recently expired.
1317 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1318 throw new SecurityException("Called with expired permission token: "
1319 + permissionToken);
1320 } else {
1321 throw new SecurityException("Called with invalid permission token: "
1322 + permissionToken);
1323 }
1324 }
1325 } else {
1326 // This method was called directly by the source.
1327 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001328 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329
Wale Ogunwaled32da472018-11-16 07:19:28 -08001330 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331 if (sourceRecord == null) {
1332 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001333 }
1334 if (sourceRecord.app == null) {
1335 throw new SecurityException("Called without a process attached to activity");
1336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337
1338 // Whether called directly or from a delegate, the source activity must be from the
1339 // android package.
1340 if (!sourceRecord.info.packageName.equals("android")) {
1341 throw new SecurityException("Must be called from an activity that is "
1342 + "declared in the android package");
1343 }
1344
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001345 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 // This is still okay, as long as this activity is running under the
1347 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001348 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 + " must be system uid or original calling uid "
1352 + sourceRecord.launchedFromUid);
1353 }
1354 }
1355 if (ignoreTargetSecurity) {
1356 if (intent.getComponent() == null) {
1357 throw new SecurityException(
1358 "Component must be specified with ignoreTargetSecurity");
1359 }
1360 if (intent.getSelector() != null) {
1361 throw new SecurityException(
1362 "Selector not allowed with ignoreTargetSecurity");
1363 }
1364 }
1365 targetUid = sourceRecord.launchedFromUid;
1366 targetPackage = sourceRecord.launchedFromPackage;
1367 isResolver = sourceRecord.isResolverOrChildActivity();
1368 }
1369
1370 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001371 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 }
1373
1374 // TODO: Switch to user app stacks here.
1375 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001376 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 .setCallingUid(targetUid)
1378 .setCallingPackage(targetPackage)
1379 .setResolvedType(resolvedType)
1380 .setResultTo(resultTo)
1381 .setResultWho(resultWho)
1382 .setRequestCode(requestCode)
1383 .setStartFlags(startFlags)
1384 .setActivityOptions(bOptions)
1385 .setMayWait(userId)
1386 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1387 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001388 // The target may well be in the background, which would normally prevent it
1389 // from starting an activity. Here we definitely want the start to succeed.
1390 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 .execute();
1392 } catch (SecurityException e) {
1393 // XXX need to figure out how to propagate to original app.
1394 // A SecurityException here is generally actually a fault of the original
1395 // calling activity (such as a fairly granting permissions), so propagate it
1396 // back to them.
1397 /*
1398 StringBuilder msg = new StringBuilder();
1399 msg.append("While launching");
1400 msg.append(intent.toString());
1401 msg.append(": ");
1402 msg.append(e.getMessage());
1403 */
1404 throw e;
1405 }
1406 }
1407
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001408 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1409 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1410 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1411 }
1412
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 @Override
1414 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1415 Intent intent, String resolvedType, IVoiceInteractionSession session,
1416 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1417 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 if (session == null || interactor == null) {
1420 throw new NullPointerException("null session or interactor");
1421 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001422 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001424 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 .setCallingUid(callingUid)
1426 .setCallingPackage(callingPackage)
1427 .setResolvedType(resolvedType)
1428 .setVoiceSession(session)
1429 .setVoiceInteractor(interactor)
1430 .setStartFlags(startFlags)
1431 .setProfilerInfo(profilerInfo)
1432 .setActivityOptions(bOptions)
1433 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001434 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 .execute();
1436 }
1437
1438 @Override
1439 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1440 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001441 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1442 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001444 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 .setCallingUid(callingUid)
1446 .setCallingPackage(callingPackage)
1447 .setResolvedType(resolvedType)
1448 .setActivityOptions(bOptions)
1449 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001450 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 .execute();
1452 }
1453
1454 @Override
1455 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1456 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 final int callingPid = Binder.getCallingPid();
1459 final long origId = Binder.clearCallingIdentity();
1460 try {
1461 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001462 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1463 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464
1465 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001466 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1467 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1469 recentsUid, assistDataReceiver);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 @Override
1477 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001478 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 "startActivityFromRecents()");
1480
1481 final int callingPid = Binder.getCallingPid();
1482 final int callingUid = Binder.getCallingUid();
1483 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1484 final long origId = Binder.clearCallingIdentity();
1485 try {
1486 synchronized (mGlobalLock) {
1487 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1488 safeOptions);
1489 }
1490 } finally {
1491 Binder.restoreCallingIdentity(origId);
1492 }
1493 }
1494
1495 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001496 * Public API to check if the client is allowed to start an activity on specified display.
1497 *
1498 * If the target display is private or virtual, some restrictions will apply.
1499 *
1500 * @param displayId Target display id.
1501 * @param intent Intent used to launch the activity.
1502 * @param resolvedType The MIME type of the intent.
1503 * @param userId The id of the user for whom the call is made.
1504 * @return {@code true} if a call to start an activity on the target display should succeed and
1505 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1506 */
1507 @Override
1508 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1509 String resolvedType, int userId) {
1510 final int callingUid = Binder.getCallingUid();
1511 final int callingPid = Binder.getCallingPid();
1512 final long origId = Binder.clearCallingIdentity();
1513
1514 try {
1515 // Collect information about the target of the Intent.
1516 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1517 0 /* startFlags */, null /* profilerInfo */, userId,
1518 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1519 UserHandle.USER_NULL));
1520 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1521
1522 synchronized (mGlobalLock) {
1523 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1524 aInfo);
1525 }
1526 } finally {
1527 Binder.restoreCallingIdentity(origId);
1528 }
1529 }
1530
1531 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 * This is the internal entry point for handling Activity.finish().
1533 *
1534 * @param token The Binder token referencing the Activity we want to finish.
1535 * @param resultCode Result code, if any, from this Activity.
1536 * @param resultData Result data (Intent), if any, from this Activity.
1537 * @param finishTask Whether to finish the task associated with this Activity.
1538 *
1539 * @return Returns true if the activity successfully finished, or false if it is still running.
1540 */
1541 @Override
1542 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1543 int finishTask) {
1544 // Refuse possible leaked file descriptors
1545 if (resultData != null && resultData.hasFileDescriptors()) {
1546 throw new IllegalArgumentException("File descriptors passed in Intent");
1547 }
1548
1549 synchronized (mGlobalLock) {
1550 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1551 if (r == null) {
1552 return true;
1553 }
1554 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001555 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 ActivityRecord rootR = tr.getRootActivity();
1557 if (rootR == null) {
1558 Slog.w(TAG, "Finishing task with all activities already finished");
1559 }
1560 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1561 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001562 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 return false;
1564 }
1565
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001566 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1567 // We should consolidate.
1568 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001570 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (next != null) {
1572 // ask watcher if this is allowed
1573 boolean resumeOK = true;
1574 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001575 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001577 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 Watchdog.getInstance().setActivityController(null);
1579 }
1580
1581 if (!resumeOK) {
1582 Slog.i(TAG, "Not finishing activity because controller resumed");
1583 return false;
1584 }
1585 }
1586 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001587
1588 // note down that the process has finished an activity and is in background activity
1589 // starts grace period
1590 if (r.app != null) {
1591 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1592 }
1593
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001594 final long origId = Binder.clearCallingIdentity();
1595 try {
1596 boolean res;
1597 final boolean finishWithRootActivity =
1598 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1599 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1600 || (finishWithRootActivity && r == rootR)) {
1601 // If requested, remove the task that is associated to this activity only if it
1602 // was the root activity in the task. The result code and data is ignored
1603 // because we don't support returning them across task boundaries. Also, to
1604 // keep backwards compatibility we remove the task from recents when finishing
1605 // task with root activity.
1606 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1607 finishWithRootActivity, "finish-activity");
1608 if (!res) {
1609 Slog.i(TAG, "Removing task failed to finish activity");
1610 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001611 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001612 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 } else {
1614 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1615 resultData, "app-request", true);
1616 if (!res) {
1617 Slog.i(TAG, "Failed to finish by app-request");
1618 }
1619 }
1620 return res;
1621 } finally {
1622 Binder.restoreCallingIdentity(origId);
1623 }
1624 }
1625 }
1626
1627 @Override
1628 public boolean finishActivityAffinity(IBinder token) {
1629 synchronized (mGlobalLock) {
1630 final long origId = Binder.clearCallingIdentity();
1631 try {
1632 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1633 if (r == null) {
1634 return false;
1635 }
1636
1637 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1638 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001639 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001640 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 return false;
1642 }
1643 return task.getStack().finishActivityAffinityLocked(r);
1644 } finally {
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1652 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001653 try {
1654 WindowProcessController proc = null;
1655 synchronized (mGlobalLock) {
1656 ActivityStack stack = ActivityRecord.getStackLocked(token);
1657 if (stack == null) {
1658 return;
1659 }
1660 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1661 false /* fromTimeout */, false /* processPausingActivities */, config);
1662 if (r != null) {
1663 proc = r.app;
1664 }
1665 if (stopProfiling && proc != null) {
1666 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 }
1668 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001669 } finally {
1670 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 }
1673
1674 @Override
1675 public final void activityResumed(IBinder token) {
1676 final long origId = Binder.clearCallingIdentity();
1677 synchronized (mGlobalLock) {
1678 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001679 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 }
1681 Binder.restoreCallingIdentity(origId);
1682 }
1683
1684 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001685 public final void activityTopResumedStateLost() {
1686 final long origId = Binder.clearCallingIdentity();
1687 synchronized (mGlobalLock) {
1688 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 public final void activityPaused(IBinder token) {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 ActivityStack stack = ActivityRecord.getStackLocked(token);
1698 if (stack != null) {
1699 stack.activityPausedLocked(token, false);
1700 }
1701 }
1702 Binder.restoreCallingIdentity(origId);
1703 }
1704
1705 @Override
1706 public final void activityStopped(IBinder token, Bundle icicle,
1707 PersistableBundle persistentState, CharSequence description) {
1708 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1709
1710 // Refuse possible leaked file descriptors
1711 if (icicle != null && icicle.hasFileDescriptors()) {
1712 throw new IllegalArgumentException("File descriptors passed in Bundle");
1713 }
1714
1715 final long origId = Binder.clearCallingIdentity();
1716
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001717 String restartingName = null;
1718 int restartingUid = 0;
1719 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001721 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001723 if (r.attachedToProcess()
1724 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1725 // The activity was requested to restart from
1726 // {@link #restartActivityProcessIfVisible}.
1727 restartingName = r.app.mName;
1728 restartingUid = r.app.mUid;
1729 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001730 r.activityStoppedLocked(icicle, persistentState, description);
1731 }
1732 }
1733
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001734 if (restartingName != null) {
1735 // In order to let the foreground activity can be restarted with its saved state from
1736 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1737 // until the activity reports stopped with the state. And the activity record will be
1738 // kept because the record state is restarting, then the activity will be restarted
1739 // immediately if it is still the top one.
1740 mStackSupervisor.removeRestartTimeouts(r);
1741 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1742 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001743 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747
1748 @Override
1749 public final void activityDestroyed(IBinder token) {
1750 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1751 synchronized (mGlobalLock) {
1752 ActivityStack stack = ActivityRecord.getStackLocked(token);
1753 if (stack != null) {
1754 stack.activityDestroyedLocked(token, "activityDestroyed");
1755 }
1756 }
1757 }
1758
1759 @Override
1760 public final void activityRelaunched(IBinder token) {
1761 final long origId = Binder.clearCallingIdentity();
1762 synchronized (mGlobalLock) {
1763 mStackSupervisor.activityRelaunchedLocked(token);
1764 }
1765 Binder.restoreCallingIdentity(origId);
1766 }
1767
1768 public final void activitySlept(IBinder token) {
1769 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1770
1771 final long origId = Binder.clearCallingIdentity();
1772
1773 synchronized (mGlobalLock) {
1774 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1775 if (r != null) {
1776 mStackSupervisor.activitySleptLocked(r);
1777 }
1778 }
1779
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782
1783 @Override
1784 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1785 synchronized (mGlobalLock) {
1786 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r == null) {
1788 return;
1789 }
1790 final long origId = Binder.clearCallingIdentity();
1791 try {
1792 r.setRequestedOrientation(requestedOrientation);
1793 } finally {
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796 }
1797 }
1798
1799 @Override
1800 public int getRequestedOrientation(IBinder token) {
1801 synchronized (mGlobalLock) {
1802 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1803 if (r == null) {
1804 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1805 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001806 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
1808 }
1809
1810 @Override
1811 public void setImmersive(IBinder token, boolean immersive) {
1812 synchronized (mGlobalLock) {
1813 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1814 if (r == null) {
1815 throw new IllegalArgumentException();
1816 }
1817 r.immersive = immersive;
1818
1819 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001820 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 }
1824 }
1825 }
1826
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 void applyUpdateLockStateLocked(ActivityRecord r) {
1828 // Modifications to the UpdateLock state are done on our handler, outside
1829 // the activity manager's locks. The new state is determined based on the
1830 // state *now* of the relevant activity record. The object is passed to
1831 // the handler solely for logging detail, not to be consulted/modified.
1832 final boolean nextState = r != null && r.immersive;
1833 mH.post(() -> {
1834 if (mUpdateLock.isHeld() != nextState) {
1835 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1836 "Applying new update lock state '" + nextState + "' for " + r);
1837 if (nextState) {
1838 mUpdateLock.acquire();
1839 } else {
1840 mUpdateLock.release();
1841 }
1842 }
1843 });
1844 }
1845
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 @Override
1847 public boolean isImmersive(IBinder token) {
1848 synchronized (mGlobalLock) {
1849 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1850 if (r == null) {
1851 throw new IllegalArgumentException();
1852 }
1853 return r.immersive;
1854 }
1855 }
1856
1857 @Override
1858 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001861 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001862 return (r != null) ? r.immersive : false;
1863 }
1864 }
1865
1866 @Override
1867 public void overridePendingTransition(IBinder token, String packageName,
1868 int enterAnim, int exitAnim) {
1869 synchronized (mGlobalLock) {
1870 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1871 if (self == null) {
1872 return;
1873 }
1874
1875 final long origId = Binder.clearCallingIdentity();
1876
1877 if (self.isState(
1878 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001879 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001880 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 }
1882
1883 Binder.restoreCallingIdentity(origId);
1884 }
1885 }
1886
1887 @Override
1888 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001889 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001891 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 if (r == null) {
1893 return ActivityManager.COMPAT_MODE_UNKNOWN;
1894 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001895 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
1897 }
1898
1899 @Override
1900 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 if (r == null) {
1907 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1908 return;
1909 }
1910 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001911 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
1913 }
1914
1915 @Override
1916 public int getLaunchedFromUid(IBinder activityToken) {
1917 ActivityRecord srec;
1918 synchronized (mGlobalLock) {
1919 srec = ActivityRecord.forTokenLocked(activityToken);
1920 }
1921 if (srec == null) {
1922 return -1;
1923 }
1924 return srec.launchedFromUid;
1925 }
1926
1927 @Override
1928 public String getLaunchedFromPackage(IBinder activityToken) {
1929 ActivityRecord srec;
1930 synchronized (mGlobalLock) {
1931 srec = ActivityRecord.forTokenLocked(activityToken);
1932 }
1933 if (srec == null) {
1934 return null;
1935 }
1936 return srec.launchedFromPackage;
1937 }
1938
1939 @Override
1940 public boolean convertFromTranslucent(IBinder token) {
1941 final long origId = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
1944 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1945 if (r == null) {
1946 return false;
1947 }
1948 final boolean translucentChanged = r.changeWindowTranslucency(true);
1949 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001950 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 return translucentChanged;
1954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(origId);
1957 }
1958 }
1959
1960 @Override
1961 public boolean convertToTranslucent(IBinder token, Bundle options) {
1962 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1963 final long origId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
1966 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1967 if (r == null) {
1968 return false;
1969 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001970 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 int index = task.mActivities.lastIndexOf(r);
1972 if (index > 0) {
1973 ActivityRecord under = task.mActivities.get(index - 1);
1974 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1975 }
1976 final boolean translucentChanged = r.changeWindowTranslucency(false);
1977 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001978 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001980 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001981 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 return translucentChanged;
1983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(origId);
1986 }
1987 }
1988
1989 @Override
1990 public void notifyActivityDrawn(IBinder token) {
1991 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1992 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001993 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001995 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 }
1997 }
1998 }
1999
2000 @Override
2001 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2002 synchronized (mGlobalLock) {
2003 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2004 if (r == null) {
2005 return;
2006 }
2007 r.reportFullyDrawnLocked(restoredFromBundle);
2008 }
2009 }
2010
2011 @Override
2012 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2013 synchronized (mGlobalLock) {
2014 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2015 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2016 return stack.mDisplayId;
2017 }
2018 return DEFAULT_DISPLAY;
2019 }
2020 }
2021
2022 @Override
2023 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 try {
2027 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002028 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 return null;
2033 }
2034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
2037 }
2038
2039 @Override
2040 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2043 final long callingId = Binder.clearCallingIdentity();
2044 try {
2045 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (stack == null) {
2048 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2049 return;
2050 }
2051 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002052 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(callingId);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002069 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (task == null) {
2071 return;
2072 }
2073 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002084 public void restartActivityProcessIfVisible(IBinder activityToken) {
2085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
2089 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2090 if (r == null) {
2091 return;
2092 }
2093 r.restartProcessIfVisible();
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingId);
2097 }
2098 }
2099
2100 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002102 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 synchronized (mGlobalLock) {
2104 final long ident = Binder.clearCallingIdentity();
2105 try {
2106 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2107 "remove-task");
2108 } finally {
2109 Binder.restoreCallingIdentity(ident);
2110 }
2111 }
2112 }
2113
2114 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002115 public void removeAllVisibleRecentTasks() {
2116 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2117 synchronized (mGlobalLock) {
2118 final long ident = Binder.clearCallingIdentity();
2119 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002120 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002121 } finally {
2122 Binder.restoreCallingIdentity(ident);
2123 }
2124 }
2125 }
2126
2127 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2129 synchronized (mGlobalLock) {
2130 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2131 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002132 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 }
2134 }
2135 return false;
2136 }
2137
2138 @Override
2139 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2140 Intent resultData) {
2141
2142 synchronized (mGlobalLock) {
2143 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2144 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002145 return r.getActivityStack().navigateUpToLocked(
2146 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 return false;
2149 }
2150 }
2151
2152 /**
2153 * Attempts to move a task backwards in z-order (the order of activities within the task is
2154 * unchanged).
2155 *
2156 * There are several possible results of this call:
2157 * - if the task is locked, then we will show the lock toast
2158 * - if there is a task behind the provided task, then that task is made visible and resumed as
2159 * this task is moved to the back
2160 * - otherwise, if there are no other tasks in the stack:
2161 * - if this task is in the pinned stack, then we remove the stack completely, which will
2162 * have the effect of moving the task to the top or bottom of the fullscreen stack
2163 * (depending on whether it is visible)
2164 * - otherwise, we simply return home and hide this task
2165 *
2166 * @param token A reference to the activity we wish to move
2167 * @param nonRoot If false then this only works if the activity is the root
2168 * of a task; if true it will work for any activity in a task.
2169 * @return Returns true if the move completed, false if not.
2170 */
2171 @Override
2172 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 synchronized (mGlobalLock) {
2175 final long origId = Binder.clearCallingIdentity();
2176 try {
2177 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002178 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 if (task != null) {
2180 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2181 }
2182 } finally {
2183 Binder.restoreCallingIdentity(origId);
2184 }
2185 }
2186 return false;
2187 }
2188
2189 @Override
2190 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 long ident = Binder.clearCallingIdentity();
2193 Rect rect = new Rect();
2194 try {
2195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2198 if (task == null) {
2199 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2200 return rect;
2201 }
2202 if (task.getStack() != null) {
2203 // Return the bounds from window manager since it will be adjusted for various
2204 // things like the presense of a docked stack for tasks that aren't resizeable.
2205 task.getWindowContainerBounds(rect);
2206 } else {
2207 // Task isn't in window manager yet since it isn't associated with a stack.
2208 // Return the persist value from activity manager
2209 if (!task.matchParentBounds()) {
2210 rect.set(task.getBounds());
2211 } else if (task.mLastNonFullscreenBounds != null) {
2212 rect.set(task.mLastNonFullscreenBounds);
2213 }
2214 }
2215 }
2216 } finally {
2217 Binder.restoreCallingIdentity(ident);
2218 }
2219 return rect;
2220 }
2221
2222 @Override
2223 public ActivityManager.TaskDescription getTaskDescription(int id) {
2224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002225 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (tr != null) {
2230 return tr.lastTaskDescription;
2231 }
2232 }
2233 return null;
2234 }
2235
2236 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2238 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2239 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2240 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2241 return;
2242 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002244 synchronized (mGlobalLock) {
2245 final long ident = Binder.clearCallingIdentity();
2246 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002247 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002248 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 if (task == null) {
2250 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2251 return;
2252 }
2253
2254 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2255 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2256
2257 if (!task.isActivityTypeStandardOrUndefined()) {
2258 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2259 + " non-standard task " + taskId + " to windowing mode="
2260 + windowingMode);
2261 }
2262
2263 final ActivityStack stack = task.getStack();
2264 if (toTop) {
2265 stack.moveToFront("setTaskWindowingMode", task);
2266 }
2267 stack.setWindowingMode(windowingMode);
2268 } finally {
2269 Binder.restoreCallingIdentity(ident);
2270 }
2271 }
2272 }
2273
2274 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 ActivityRecord r = getCallingRecordLocked(token);
2278 return r != null ? r.info.packageName : null;
2279 }
2280 }
2281
2282 @Override
2283 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 ActivityRecord r = getCallingRecordLocked(token);
2286 return r != null ? r.intent.getComponent() : null;
2287 }
2288 }
2289
2290 private ActivityRecord getCallingRecordLocked(IBinder token) {
2291 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2292 if (r == null) {
2293 return null;
2294 }
2295 return r.resultTo;
2296 }
2297
2298 @Override
2299 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002300 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301
2302 synchronized (mGlobalLock) {
2303 final long origId = Binder.clearCallingIdentity();
2304 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002305 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 } finally {
2307 Binder.restoreCallingIdentity(origId);
2308 }
2309 }
2310 }
2311
Mark Renouf446251d2019-04-26 10:22:41 -04002312 @Override
2313 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2314 synchronized (mGlobalLock) {
2315 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2316 if (r == null) {
2317 return;
2318 }
2319 ActivityStack stack = r.getActivityStack();
2320 if (stack != null && stack.isSingleTaskInstance()) {
2321 // Single-task stacks are used for activities which are presented in floating
2322 // windows above full screen activities. Instead of directly finishing the
2323 // task, a task change listener is used to notify SystemUI so the action can be
2324 // handled specially.
2325 final TaskRecord task = r.getTaskRecord();
2326 mTaskChangeNotificationController
2327 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2328 } else {
2329 try {
2330 callback.requestFinish();
2331 } catch (RemoteException e) {
2332 Slog.e(TAG, "Failed to invoke request finish callback", e);
2333 }
2334 }
2335 }
2336 }
2337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 /**
2339 * TODO: Add mController hook
2340 */
2341 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2343 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2347 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002348 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2349 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 }
2351 }
2352
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2354 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 boolean fromRecents) {
2356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 final int callingPid = Binder.getCallingPid();
2358 final int callingUid = Binder.getCallingUid();
2359 if (!isSameApp(callingUid, callingPackage)) {
2360 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2361 + Binder.getCallingPid() + " as package " + callingPackage;
2362 Slog.w(TAG, msg);
2363 throw new SecurityException(msg);
2364 }
2365 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 SafeActivityOptions.abort(options);
2367 return;
2368 }
2369 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 WindowProcessController callerApp = null;
2371 if (appThread != null) {
2372 callerApp = getProcessController(appThread);
2373 }
2374 final ActivityStarter starter = getActivityStartController().obtainStarter(
2375 null /* intent */, "moveTaskToFront");
2376 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2377 -1, callerApp, null, false, null)) {
2378 boolean abort = !isBackgroundActivityStartsEnabled();
2379 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2380 if (abort) {
2381 return;
2382 }
2383 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002385 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 if (task == null) {
2387 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002388 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 return;
2390 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002391 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002393 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 return;
2395 }
2396 ActivityOptions realOptions = options != null
2397 ? options.getOptions(mStackSupervisor)
2398 : null;
2399 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2400 false /* forceNonResizable */);
2401
2402 final ActivityRecord topActivity = task.getTopActivity();
2403 if (topActivity != null) {
2404
2405 // We are reshowing a task, use a starting window to hide the initial draw delay
2406 // so the transition can start earlier.
2407 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2408 true /* taskSwitch */, fromRecents);
2409 }
2410 } finally {
2411 Binder.restoreCallingIdentity(origId);
2412 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 }
2414
Ricky Waiaca8a772019-04-04 16:01:06 +01002415 /**
2416 * Return true if callingUid is system, or packageName belongs to that callingUid.
2417 */
2418 boolean isSameApp(int callingUid, @Nullable String packageName) {
2419 try {
2420 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2421 if (packageName == null) {
2422 return false;
2423 }
2424 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2425 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2426 UserHandle.getUserId(callingUid));
2427 return UserHandle.isSameApp(callingUid, uid);
2428 }
2429 } catch (RemoteException e) {
2430 // Should not happen
2431 }
2432 return true;
2433 }
2434
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002435 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2436 int callingPid, int callingUid, String name) {
2437 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2438 return true;
2439 }
2440
2441 if (getRecentTasks().isCallerRecents(sourceUid)) {
2442 return true;
2443 }
2444
2445 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2446 if (perm == PackageManager.PERMISSION_GRANTED) {
2447 return true;
2448 }
2449 if (checkAllowAppSwitchUid(sourceUid)) {
2450 return true;
2451 }
2452
2453 // If the actual IPC caller is different from the logical source, then
2454 // also see if they are allowed to control app switches.
2455 if (callingUid != -1 && callingUid != sourceUid) {
2456 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2457 if (perm == PackageManager.PERMISSION_GRANTED) {
2458 return true;
2459 }
2460 if (checkAllowAppSwitchUid(callingUid)) {
2461 return true;
2462 }
2463 }
2464
2465 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2466 return false;
2467 }
2468
2469 private boolean checkAllowAppSwitchUid(int uid) {
2470 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2471 if (types != null) {
2472 for (int i = types.size() - 1; i >= 0; i--) {
2473 if (types.valueAt(i).intValue() == uid) {
2474 return true;
2475 }
2476 }
2477 }
2478 return false;
2479 }
2480
2481 @Override
2482 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2483 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2484 "setActivityController()");
2485 synchronized (mGlobalLock) {
2486 mController = controller;
2487 mControllerIsAMonkey = imAMonkey;
2488 Watchdog.getInstance().setActivityController(controller);
2489 }
2490 }
2491
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002492 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002493 synchronized (mGlobalLock) {
2494 return mController != null && mControllerIsAMonkey;
2495 }
2496 }
2497
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 @Override
2499 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2500 synchronized (mGlobalLock) {
2501 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2502 }
2503 }
2504
2505 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002506 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2507 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2508 }
2509
2510 @Override
2511 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2512 @WindowConfiguration.ActivityType int ignoreActivityType,
2513 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2514 final int callingUid = Binder.getCallingUid();
2515 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2516
2517 synchronized (mGlobalLock) {
2518 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2519
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002520 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002522 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002523 ignoreWindowingMode, callingUid, allowed);
2524 }
2525
2526 return list;
2527 }
2528
2529 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2531 synchronized (mGlobalLock) {
2532 final long origId = Binder.clearCallingIdentity();
2533 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2534 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002535 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 }
2537 Binder.restoreCallingIdentity(origId);
2538 }
2539 }
2540
2541 @Override
2542 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002543 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002544 ActivityStack stack = ActivityRecord.getStackLocked(token);
2545 if (stack != null) {
2546 return stack.willActivityBeVisibleLocked(token);
2547 }
2548 return false;
2549 }
2550 }
2551
2552 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002554 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 synchronized (mGlobalLock) {
2556 final long ident = Binder.clearCallingIdentity();
2557 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002558 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 if (task == null) {
2560 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2561 return;
2562 }
2563
2564 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2565 + " to stackId=" + stackId + " toTop=" + toTop);
2566
Wale Ogunwaled32da472018-11-16 07:19:28 -08002567 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002568 if (stack == null) {
2569 throw new IllegalStateException(
2570 "moveTaskToStack: No stack for stackId=" + stackId);
2571 }
2572 if (!stack.isActivityTypeStandardOrUndefined()) {
2573 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2574 + taskId + " to stack " + stackId);
2575 }
2576 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2579 }
2580 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2581 "moveTaskToStack");
2582 } finally {
2583 Binder.restoreCallingIdentity(ident);
2584 }
2585 }
2586 }
2587
2588 @Override
2589 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2590 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592
2593 final long ident = Binder.clearCallingIdentity();
2594 try {
2595 synchronized (mGlobalLock) {
2596 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002597 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 if (stack == null) {
2599 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2600 return;
2601 }
2602 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2603 throw new IllegalArgumentException("Stack: " + stackId
2604 + " doesn't support animated resize.");
2605 }
2606 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2607 animationDuration, false /* fromFullscreen */);
2608 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002609 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002610 if (stack == null) {
2611 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2612 return;
2613 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002614 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2616 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2617 }
2618 }
2619 } finally {
2620 Binder.restoreCallingIdentity(ident);
2621 }
2622 }
2623
wilsonshih5c4cf522019-01-25 09:03:47 +08002624 @Override
2625 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2626 int animationDuration) {
2627 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2628
2629 final long ident = Binder.clearCallingIdentity();
2630 try {
2631 synchronized (mGlobalLock) {
2632 if (xOffset == 0 && yOffset == 0) {
2633 return;
2634 }
2635 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2636 if (stack == null) {
2637 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2638 return;
2639 }
2640 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2641 throw new IllegalArgumentException("Stack: " + stackId
2642 + " doesn't support animated resize.");
2643 }
2644 final Rect destBounds = new Rect();
2645 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002646 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002647 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2648 return;
2649 }
2650 destBounds.offset(xOffset, yOffset);
2651 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2652 animationDuration, false /* fromFullscreen */);
2653 }
2654 } finally {
2655 Binder.restoreCallingIdentity(ident);
2656 }
2657 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002658 /**
2659 * Moves the specified task to the primary-split-screen stack.
2660 *
2661 * @param taskId Id of task to move.
2662 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2663 * exist already. See
2664 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2665 * and
2666 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2667 * @param toTop If the task and stack should be moved to the top.
2668 * @param animate Whether we should play an animation for the moving the task.
2669 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2670 * stack. Pass {@code null} to use default bounds.
2671 * @param showRecents If the recents activity should be shown on the other side of the task
2672 * going into split-screen mode.
2673 */
2674 @Override
2675 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2676 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002677 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 "setTaskWindowingModeSplitScreenPrimary()");
2679 synchronized (mGlobalLock) {
2680 final long ident = Binder.clearCallingIdentity();
2681 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002682 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002683 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 if (task == null) {
2685 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2686 return false;
2687 }
2688 if (DEBUG_STACK) Slog.d(TAG_STACK,
2689 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2690 + " to createMode=" + createMode + " toTop=" + toTop);
2691 if (!task.isActivityTypeStandardOrUndefined()) {
2692 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2693 + " non-standard task " + taskId + " to split-screen windowing mode");
2694 }
2695
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002696 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002697 final int windowingMode = task.getWindowingMode();
2698 final ActivityStack stack = task.getStack();
2699 if (toTop) {
2700 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2701 }
2702 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002703 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2704 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 return windowingMode != task.getWindowingMode();
2706 } finally {
2707 Binder.restoreCallingIdentity(ident);
2708 }
2709 }
2710 }
2711
2712 /**
2713 * Removes stacks in the input windowing modes from the system if they are of activity type
2714 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2715 */
2716 @Override
2717 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002718 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 "removeStacksInWindowingModes()");
2720
2721 synchronized (mGlobalLock) {
2722 final long ident = Binder.clearCallingIdentity();
2723 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002724 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 } finally {
2726 Binder.restoreCallingIdentity(ident);
2727 }
2728 }
2729 }
2730
2731 @Override
2732 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 "removeStacksWithActivityTypes()");
2735
2736 synchronized (mGlobalLock) {
2737 final long ident = Binder.clearCallingIdentity();
2738 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002739 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 } finally {
2741 Binder.restoreCallingIdentity(ident);
2742 }
2743 }
2744 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002745
2746 @Override
2747 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2748 int userId) {
2749 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002750 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2751 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002753 final boolean detailed = checkGetTasksPermission(
2754 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2755 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 == PackageManager.PERMISSION_GRANTED;
2757
2758 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002759 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 callingUid);
2761 }
2762 }
2763
2764 @Override
2765 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002766 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 long ident = Binder.clearCallingIdentity();
2768 try {
2769 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002770 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 }
2772 } finally {
2773 Binder.restoreCallingIdentity(ident);
2774 }
2775 }
2776
2777 @Override
2778 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 long ident = Binder.clearCallingIdentity();
2781 try {
2782 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002783 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 }
2785 } finally {
2786 Binder.restoreCallingIdentity(ident);
2787 }
2788 }
2789
2790 @Override
2791 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 final long callingUid = Binder.getCallingUid();
2794 final long origId = Binder.clearCallingIdentity();
2795 try {
2796 synchronized (mGlobalLock) {
2797 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002798 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2800 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2801 }
2802 } finally {
2803 Binder.restoreCallingIdentity(origId);
2804 }
2805 }
2806
2807 @Override
2808 public void startLockTaskModeByToken(IBinder token) {
2809 synchronized (mGlobalLock) {
2810 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2811 if (r == null) {
2812 return;
2813 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002814 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 }
2816 }
2817
2818 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002819 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002820 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 // This makes inner call to look as if it was initiated by system.
2822 long ident = Binder.clearCallingIdentity();
2823 try {
2824 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002825 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002826 MATCH_TASK_IN_STACKS_ONLY);
2827 if (task == null) {
2828 return;
2829 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830
2831 // When starting lock task mode the stack must be in front and focused
2832 task.getStack().moveToFront("startSystemLockTaskMode");
2833 startLockTaskModeLocked(task, true /* isSystemCaller */);
2834 }
2835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
2838 }
2839
2840 @Override
2841 public void stopLockTaskModeByToken(IBinder token) {
2842 synchronized (mGlobalLock) {
2843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2844 if (r == null) {
2845 return;
2846 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002847 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 }
2849 }
2850
2851 /**
2852 * This API should be called by SystemUI only when user perform certain action to dismiss
2853 * lock task mode. We should only dismiss pinned lock task mode in this case.
2854 */
2855 @Override
2856 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002857 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002858 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2859 }
2860
2861 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2862 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2863 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2864 return;
2865 }
2866
Wale Ogunwaled32da472018-11-16 07:19:28 -08002867 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 if (stack == null || task != stack.topTask()) {
2869 throw new IllegalArgumentException("Invalid task, not in foreground");
2870 }
2871
2872 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2873 // system or a specific app.
2874 // * System-initiated requests will only start the pinned mode (screen pinning)
2875 // * App-initiated requests
2876 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2877 // - will start the pinned mode, otherwise
2878 final int callingUid = Binder.getCallingUid();
2879 long ident = Binder.clearCallingIdentity();
2880 try {
2881 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002882 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002884 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 } finally {
2886 Binder.restoreCallingIdentity(ident);
2887 }
2888 }
2889
2890 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2891 final int callingUid = Binder.getCallingUid();
2892 long ident = Binder.clearCallingIdentity();
2893 try {
2894 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002895 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 }
2897 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2898 // task and jumping straight into a call in the case of emergency call back.
2899 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2900 if (tm != null) {
2901 tm.showInCallScreen(false);
2902 }
2903 } finally {
2904 Binder.restoreCallingIdentity(ident);
2905 }
2906 }
2907
2908 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002909 public void updateLockTaskPackages(int userId, String[] packages) {
2910 final int callingUid = Binder.getCallingUid();
2911 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2912 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2913 "updateLockTaskPackages()");
2914 }
2915 synchronized (this) {
2916 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2917 + Arrays.toString(packages));
2918 getLockTaskController().updateLockTaskPackages(userId, packages);
2919 }
2920 }
2921
2922 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 public boolean isInLockTaskMode() {
2924 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2925 }
2926
2927 @Override
2928 public int getLockTaskModeState() {
2929 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002930 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 }
2932 }
2933
2934 @Override
2935 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2936 synchronized (mGlobalLock) {
2937 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2938 if (r != null) {
2939 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002940 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002942 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 }
2944 }
2945 }
2946
2947 @Override
2948 public Bundle getActivityOptions(IBinder token) {
2949 final long origId = Binder.clearCallingIdentity();
2950 try {
2951 synchronized (mGlobalLock) {
2952 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2953 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002954 final ActivityOptions activityOptions = r.takeOptionsLocked(
2955 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 return activityOptions == null ? null : activityOptions.toBundle();
2957 }
2958 return null;
2959 }
2960 } finally {
2961 Binder.restoreCallingIdentity(origId);
2962 }
2963 }
2964
2965 @Override
2966 public List<IBinder> getAppTasks(String callingPackage) {
2967 int callingUid = Binder.getCallingUid();
2968 long ident = Binder.clearCallingIdentity();
2969 try {
2970 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002971 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 }
2973 } finally {
2974 Binder.restoreCallingIdentity(ident);
2975 }
2976 }
2977
2978 @Override
2979 public void finishVoiceTask(IVoiceInteractionSession session) {
2980 synchronized (mGlobalLock) {
2981 final long origId = Binder.clearCallingIdentity();
2982 try {
2983 // TODO: VI Consider treating local voice interactions and voice tasks
2984 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002985 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 } finally {
2987 Binder.restoreCallingIdentity(origId);
2988 }
2989 }
2990
2991 }
2992
2993 @Override
2994 public boolean isTopOfTask(IBinder token) {
2995 synchronized (mGlobalLock) {
2996 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002997 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 }
2999 }
3000
3001 @Override
3002 public void notifyLaunchTaskBehindComplete(IBinder token) {
3003 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3004 }
3005
3006 @Override
3007 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 mH.post(() -> {
3009 synchronized (mGlobalLock) {
3010 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003011 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003012 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003013 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003014 } catch (RemoteException e) {
3015 }
3016 }
3017 }
3018
3019 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021
3022 /** Called from an app when assist data is ready. */
3023 @Override
3024 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3025 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003026 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003027 synchronized (pae) {
3028 pae.result = extras;
3029 pae.structure = structure;
3030 pae.content = content;
3031 if (referrer != null) {
3032 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3033 }
3034 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003035 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003036 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3037 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 structure.setHomeActivity(pae.isHome);
3039 }
3040 pae.haveResult = true;
3041 pae.notifyAll();
3042 if (pae.intent == null && pae.receiver == null) {
3043 // Caller is just waiting for the result.
3044 return;
3045 }
3046 }
3047 // We are now ready to launch the assist activity.
3048 IAssistDataReceiver sendReceiver = null;
3049 Bundle sendBundle = null;
3050 synchronized (mGlobalLock) {
3051 buildAssistBundleLocked(pae, extras);
3052 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003053 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 if (!exists) {
3055 // Timed out.
3056 return;
3057 }
3058
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003059 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 // Caller wants result sent back to them.
3061 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003062 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3063 pae.activity.getTaskRecord().taskId);
3064 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3065 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3067 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3068 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3069 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3070 }
3071 }
3072 if (sendReceiver != null) {
3073 try {
3074 sendReceiver.onHandleAssistData(sendBundle);
3075 } catch (RemoteException e) {
3076 }
3077 return;
3078 }
3079
3080 final long ident = Binder.clearCallingIdentity();
3081 try {
3082 if (TextUtils.equals(pae.intent.getAction(),
3083 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3084 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003085
3086 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087 } else {
3088 pae.intent.replaceExtras(pae.extras);
3089 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3090 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3091 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003092 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093
3094 try {
3095 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3096 } catch (ActivityNotFoundException e) {
3097 Slog.w(TAG, "No activity to handle assist action.", e);
3098 }
3099 }
3100 } finally {
3101 Binder.restoreCallingIdentity(ident);
3102 }
3103 }
3104
Marvin Ramin830d4e32019-03-12 13:16:58 +01003105 /**
3106 * Workaround for historical API which starts the Assist service with a non-foreground
3107 * {@code startService()} call.
3108 */
3109 private void startVoiceInteractionServiceAsUser(
3110 Intent intent, int userHandle, String reason) {
3111 // Resolve the intent to find out which package we need to whitelist.
3112 ResolveInfo resolveInfo =
3113 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3114 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3115 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3116 return;
3117 }
3118 intent.setPackage(resolveInfo.serviceInfo.packageName);
3119
3120 // Whitelist background services temporarily.
3121 LocalServices.getService(DeviceIdleController.LocalService.class)
3122 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3123 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3124
3125 // Finally, try to start the service.
3126 try {
3127 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3128 } catch (RuntimeException e) {
3129 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3130 }
3131 }
3132
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 @Override
3134 public int addAppTask(IBinder activityToken, Intent intent,
3135 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3136 final int callingUid = Binder.getCallingUid();
3137 final long callingIdent = Binder.clearCallingIdentity();
3138
3139 try {
3140 synchronized (mGlobalLock) {
3141 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3142 if (r == null) {
3143 throw new IllegalArgumentException("Activity does not exist; token="
3144 + activityToken);
3145 }
3146 ComponentName comp = intent.getComponent();
3147 if (comp == null) {
3148 throw new IllegalArgumentException("Intent " + intent
3149 + " must specify explicit component");
3150 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003151 if (thumbnail.getWidth() != mThumbnailWidth
3152 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 throw new IllegalArgumentException("Bad thumbnail size: got "
3154 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003155 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 }
3157 if (intent.getSelector() != null) {
3158 intent.setSelector(null);
3159 }
3160 if (intent.getSourceBounds() != null) {
3161 intent.setSourceBounds(null);
3162 }
3163 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3164 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3165 // The caller has added this as an auto-remove task... that makes no
3166 // sense, so turn off auto-remove.
3167 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3168 }
3169 }
3170 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3171 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3172 if (ainfo.applicationInfo.uid != callingUid) {
3173 throw new SecurityException(
3174 "Can't add task for another application: target uid="
3175 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3176 }
3177
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003178 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003180 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003182 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183 // The app has too many tasks already and we can't add any more
3184 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3185 return INVALID_TASK_ID;
3186 }
3187 task.lastTaskDescription.copyFrom(description);
3188
3189 // TODO: Send the thumbnail to WM to store it.
3190
3191 return task.taskId;
3192 }
3193 } finally {
3194 Binder.restoreCallingIdentity(callingIdent);
3195 }
3196 }
3197
3198 @Override
3199 public Point getAppTaskThumbnailSize() {
3200 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003201 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 }
3203 }
3204
3205 @Override
3206 public void setTaskResizeable(int taskId, int resizeableMode) {
3207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003208 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3210 if (task == null) {
3211 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3212 return;
3213 }
3214 task.setResizeMode(resizeableMode);
3215 }
3216 }
3217
3218 @Override
3219 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003220 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 long ident = Binder.clearCallingIdentity();
3222 try {
3223 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003224 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003225 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 if (task == null) {
3227 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3228 return;
3229 }
3230 // Place the task in the right stack if it isn't there already based on
3231 // the requested bounds.
3232 // The stack transition logic is:
3233 // - a null bounds on a freeform task moves that task to fullscreen
3234 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3235 // that task to freeform
3236 // - otherwise the task is not moved
3237 ActivityStack stack = task.getStack();
3238 if (!task.getWindowConfiguration().canResizeTask()) {
3239 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3240 }
3241 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3242 stack = stack.getDisplay().getOrCreateStack(
3243 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3244 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3245 stack = stack.getDisplay().getOrCreateStack(
3246 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3247 }
3248
3249 // Reparent the task to the right stack if necessary
3250 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3251 if (stack != task.getStack()) {
3252 // Defer resume until the task is resized below
3253 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3254 DEFER_RESUME, "resizeTask");
3255 preserveWindow = false;
3256 }
3257
3258 // After reparenting (which only resizes the task to the stack bounds), resize the
3259 // task to the actual bounds provided
3260 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3261 }
3262 } finally {
3263 Binder.restoreCallingIdentity(ident);
3264 }
3265 }
3266
3267 @Override
3268 public boolean releaseActivityInstance(IBinder token) {
3269 synchronized (mGlobalLock) {
3270 final long origId = Binder.clearCallingIdentity();
3271 try {
3272 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3273 if (r == null) {
3274 return false;
3275 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003276 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003277 } finally {
3278 Binder.restoreCallingIdentity(origId);
3279 }
3280 }
3281 }
3282
3283 @Override
3284 public void releaseSomeActivities(IApplicationThread appInt) {
3285 synchronized (mGlobalLock) {
3286 final long origId = Binder.clearCallingIdentity();
3287 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003288 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003289 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003290 } finally {
3291 Binder.restoreCallingIdentity(origId);
3292 }
3293 }
3294 }
3295
3296 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003297 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003298 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 != PackageManager.PERMISSION_GRANTED) {
3300 throw new SecurityException("Requires permission "
3301 + android.Manifest.permission.DEVICE_POWER);
3302 }
3303
3304 synchronized (mGlobalLock) {
3305 long ident = Binder.clearCallingIdentity();
3306 if (mKeyguardShown != keyguardShowing) {
3307 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003308 final Message msg = PooledLambda.obtainMessage(
3309 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3310 keyguardShowing);
3311 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 }
3313 try {
wilsonshih177261f2019-02-22 12:02:18 +08003314 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 } finally {
3316 Binder.restoreCallingIdentity(ident);
3317 }
3318 }
3319
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003320 mH.post(() -> {
3321 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3322 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3323 }
3324 });
3325 }
3326
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003327 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003328 mH.post(() -> {
3329 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3330 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3331 }
3332 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 }
3334
3335 @Override
3336 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003337 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3338 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003339
3340 final File passedIconFile = new File(filePath);
3341 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3342 passedIconFile.getName());
3343 if (!legitIconFile.getPath().equals(filePath)
3344 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3345 throw new IllegalArgumentException("Bad file path: " + filePath
3346 + " passed for userId " + userId);
3347 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003348 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 }
3350
3351 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003352 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3354 final ActivityOptions activityOptions = safeOptions != null
3355 ? safeOptions.getOptions(mStackSupervisor)
3356 : null;
3357 if (activityOptions == null
3358 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3359 || activityOptions.getCustomInPlaceResId() == 0) {
3360 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3361 "with valid animation");
3362 }
lumark588a3e82018-07-20 18:53:54 +08003363 // Get top display of front most application.
3364 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3365 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003366 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3367 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3368 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003369 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003370 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003371 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 }
3373
3374 @Override
3375 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003376 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 synchronized (mGlobalLock) {
3378 final long ident = Binder.clearCallingIdentity();
3379 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003380 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 if (stack == null) {
3382 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3383 return;
3384 }
3385 if (!stack.isActivityTypeStandardOrUndefined()) {
3386 throw new IllegalArgumentException(
3387 "Removing non-standard stack is not allowed.");
3388 }
3389 mStackSupervisor.removeStack(stack);
3390 } finally {
3391 Binder.restoreCallingIdentity(ident);
3392 }
3393 }
3394 }
3395
3396 @Override
3397 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003398 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399
3400 synchronized (mGlobalLock) {
3401 final long ident = Binder.clearCallingIdentity();
3402 try {
3403 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3404 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003405 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 } finally {
3407 Binder.restoreCallingIdentity(ident);
3408 }
3409 }
3410 }
3411
3412 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003413 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 synchronized (mGlobalLock) {
3415 long ident = Binder.clearCallingIdentity();
3416 try {
3417 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3418 if (r == null) {
3419 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003420 "toggleFreeformWindowingMode: No activity record matching token="
3421 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003424 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003425 if (stack == null) {
3426 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3427 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 }
3429
Yunfan Chend967af82019-01-17 18:30:18 +09003430 if (!stack.inFreeformWindowingMode()
3431 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3432 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3433 + "toggle between fullscreen and freeform.");
3434 }
3435
3436 if (stack.inFreeformWindowingMode()) {
3437 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003438 } else if (stack.getParent().inFreeformWindowingMode()) {
3439 // If the window is on a freeform display, set it to undefined. It will be
3440 // resolved to freeform and it can adjust windowing mode when the display mode
3441 // changes in runtime.
3442 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003443 } else {
3444 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3445 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3453 @Override
3454 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003457 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 }
3459
3460 /** Unregister a task stack listener so that it stops receiving callbacks. */
3461 @Override
3462 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003465 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 }
3467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 @Override
3469 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3470 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3471 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3472 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3473 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3474 }
3475
3476 @Override
3477 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3478 IBinder activityToken, int flags) {
3479 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3480 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3481 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3482 }
3483
3484 @Override
3485 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3486 Bundle args) {
3487 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3488 true /* focused */, true /* newSessionId */, userHandle, args,
3489 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3490 }
3491
3492 @Override
3493 public Bundle getAssistContextExtras(int requestType) {
3494 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3495 null, null, true /* focused */, true /* newSessionId */,
3496 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3497 if (pae == null) {
3498 return null;
3499 }
3500 synchronized (pae) {
3501 while (!pae.haveResult) {
3502 try {
3503 pae.wait();
3504 } catch (InterruptedException e) {
3505 }
3506 }
3507 }
3508 synchronized (mGlobalLock) {
3509 buildAssistBundleLocked(pae, pae.result);
3510 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003511 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 }
3513 return pae.extras;
3514 }
3515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 /**
3517 * Binder IPC calls go through the public entry point.
3518 * This can be called with or without the global lock held.
3519 */
3520 private static int checkCallingPermission(String permission) {
3521 return checkPermission(
3522 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3523 }
3524
3525 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003526 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3528 mAmInternal.enforceCallingPermission(permission, func);
3529 }
3530 }
3531
3532 @VisibleForTesting
3533 int checkGetTasksPermission(String permission, int pid, int uid) {
3534 return checkPermission(permission, pid, uid);
3535 }
3536
3537 static int checkPermission(String permission, int pid, int uid) {
3538 if (permission == null) {
3539 return PackageManager.PERMISSION_DENIED;
3540 }
3541 return checkComponentPermission(permission, pid, uid, -1, true);
3542 }
3543
Wale Ogunwale214f3482018-10-04 11:00:47 -07003544 public static int checkComponentPermission(String permission, int pid, int uid,
3545 int owningUid, boolean exported) {
3546 return ActivityManagerService.checkComponentPermission(
3547 permission, pid, uid, owningUid, exported);
3548 }
3549
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003550 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3551 if (getRecentTasks().isCallerRecents(callingUid)) {
3552 // Always allow the recents component to get tasks
3553 return true;
3554 }
3555
3556 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3557 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3558 if (!allowed) {
3559 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3560 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3561 // Temporary compatibility: some existing apps on the system image may
3562 // still be requesting the old permission and not switched to the new
3563 // one; if so, we'll still allow them full access. This means we need
3564 // to see if they are holding the old permission and are a system app.
3565 try {
3566 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3567 allowed = true;
3568 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3569 + " is using old GET_TASKS but privileged; allowing");
3570 }
3571 } catch (RemoteException e) {
3572 }
3573 }
3574 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3575 + " does not hold REAL_GET_TASKS; limiting output");
3576 }
3577 return allowed;
3578 }
3579
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003580 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3581 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3582 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3583 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003584 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585 "enqueueAssistContext()");
3586
3587 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003588 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589 if (activity == null) {
3590 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3591 return null;
3592 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003593 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3595 return null;
3596 }
3597 if (focused) {
3598 if (activityToken != null) {
3599 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3600 if (activity != caller) {
3601 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3602 + " is not current top " + activity);
3603 return null;
3604 }
3605 }
3606 } else {
3607 activity = ActivityRecord.forTokenLocked(activityToken);
3608 if (activity == null) {
3609 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3610 + " couldn't be found");
3611 return null;
3612 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003613 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3615 return null;
3616 }
3617 }
3618
3619 PendingAssistExtras pae;
3620 Bundle extras = new Bundle();
3621 if (args != null) {
3622 extras.putAll(args);
3623 }
3624 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003625 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626
3627 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3628 userHandle);
3629 pae.isHome = activity.isActivityTypeHome();
3630
3631 // Increment the sessionId if necessary
3632 if (newSessionId) {
3633 mViSessionId++;
3634 }
3635 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003636 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3637 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003639 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 } catch (RemoteException e) {
3641 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3642 return null;
3643 }
3644 return pae;
3645 }
3646 }
3647
3648 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3649 if (result != null) {
3650 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3651 }
3652 if (pae.hint != null) {
3653 pae.extras.putBoolean(pae.hint, true);
3654 }
3655 }
3656
3657 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3658 IAssistDataReceiver receiver;
3659 synchronized (mGlobalLock) {
3660 mPendingAssistExtras.remove(pae);
3661 receiver = pae.receiver;
3662 }
3663 if (receiver != null) {
3664 // Caller wants result sent back to them.
3665 Bundle sendBundle = new Bundle();
3666 // At least return the receiver extras
3667 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3668 try {
3669 pae.receiver.onHandleAssistData(sendBundle);
3670 } catch (RemoteException e) {
3671 }
3672 }
3673 }
3674
3675 public class PendingAssistExtras extends Binder implements Runnable {
3676 public final ActivityRecord activity;
3677 public boolean isHome;
3678 public final Bundle extras;
3679 public final Intent intent;
3680 public final String hint;
3681 public final IAssistDataReceiver receiver;
3682 public final int userHandle;
3683 public boolean haveResult = false;
3684 public Bundle result = null;
3685 public AssistStructure structure = null;
3686 public AssistContent content = null;
3687 public Bundle receiverExtras;
3688
3689 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3690 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3691 int _userHandle) {
3692 activity = _activity;
3693 extras = _extras;
3694 intent = _intent;
3695 hint = _hint;
3696 receiver = _receiver;
3697 receiverExtras = _receiverExtras;
3698 userHandle = _userHandle;
3699 }
3700
3701 @Override
3702 public void run() {
3703 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3704 synchronized (this) {
3705 haveResult = true;
3706 notifyAll();
3707 }
3708 pendingAssistExtrasTimedOut(this);
3709 }
3710 }
3711
3712 @Override
3713 public boolean isAssistDataAllowedOnCurrentActivity() {
3714 int userId;
3715 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003716 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3718 return false;
3719 }
3720
3721 final ActivityRecord activity = focusedStack.getTopActivity();
3722 if (activity == null) {
3723 return false;
3724 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003725 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003726 }
3727 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3728 }
3729
3730 @Override
3731 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3732 long ident = Binder.clearCallingIdentity();
3733 try {
3734 synchronized (mGlobalLock) {
3735 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003736 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 if (top != caller) {
3738 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3739 + " is not current top " + top);
3740 return false;
3741 }
3742 if (!top.nowVisible) {
3743 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3744 + " is not visible");
3745 return false;
3746 }
3747 }
3748 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3749 token);
3750 } finally {
3751 Binder.restoreCallingIdentity(ident);
3752 }
3753 }
3754
3755 @Override
3756 public boolean isRootVoiceInteraction(IBinder token) {
3757 synchronized (mGlobalLock) {
3758 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3759 if (r == null) {
3760 return false;
3761 }
3762 return r.rootVoiceInteraction;
3763 }
3764 }
3765
Wale Ogunwalef6733932018-06-27 05:14:34 -07003766 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3767 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3768 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3769 if (activityToCallback == null) return;
3770 activityToCallback.setVoiceSessionLocked(voiceSession);
3771
3772 // Inform the activity
3773 try {
3774 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3775 voiceInteractor);
3776 long token = Binder.clearCallingIdentity();
3777 try {
3778 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3779 } finally {
3780 Binder.restoreCallingIdentity(token);
3781 }
3782 // TODO: VI Should we cache the activity so that it's easier to find later
3783 // rather than scan through all the stacks and activities?
3784 } catch (RemoteException re) {
3785 activityToCallback.clearVoiceSessionLocked();
3786 // TODO: VI Should this terminate the voice session?
3787 }
3788 }
3789
3790 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3791 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3792 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3793 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3794 boolean wasRunningVoice = mRunningVoice != null;
3795 mRunningVoice = session;
3796 if (!wasRunningVoice) {
3797 mVoiceWakeLock.acquire();
3798 updateSleepIfNeededLocked();
3799 }
3800 }
3801 }
3802
3803 void finishRunningVoiceLocked() {
3804 if (mRunningVoice != null) {
3805 mRunningVoice = null;
3806 mVoiceWakeLock.release();
3807 updateSleepIfNeededLocked();
3808 }
3809 }
3810
3811 @Override
3812 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3813 synchronized (mGlobalLock) {
3814 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3815 if (keepAwake) {
3816 mVoiceWakeLock.acquire();
3817 } else {
3818 mVoiceWakeLock.release();
3819 }
3820 }
3821 }
3822 }
3823
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003824 @Override
3825 public ComponentName getActivityClassForToken(IBinder token) {
3826 synchronized (mGlobalLock) {
3827 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3828 if (r == null) {
3829 return null;
3830 }
3831 return r.intent.getComponent();
3832 }
3833 }
3834
3835 @Override
3836 public String getPackageForToken(IBinder token) {
3837 synchronized (mGlobalLock) {
3838 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3839 if (r == null) {
3840 return null;
3841 }
3842 return r.packageName;
3843 }
3844 }
3845
3846 @Override
3847 public void showLockTaskEscapeMessage(IBinder token) {
3848 synchronized (mGlobalLock) {
3849 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3850 if (r == null) {
3851 return;
3852 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003853 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 }
3855 }
3856
3857 @Override
3858 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003859 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003860 final long token = Binder.clearCallingIdentity();
3861 try {
3862 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003863 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 }
3865 } finally {
3866 Binder.restoreCallingIdentity(token);
3867 }
3868 }
3869
3870 /**
3871 * Try to place task to provided position. The final position might be different depending on
3872 * current user and stacks state. The task will be moved to target stack if it's currently in
3873 * different stack.
3874 */
3875 @Override
3876 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003877 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 synchronized (mGlobalLock) {
3879 long ident = Binder.clearCallingIdentity();
3880 try {
3881 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3882 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003883 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 if (task == null) {
3885 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3886 + taskId);
3887 }
3888
Wale Ogunwaled32da472018-11-16 07:19:28 -08003889 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890
3891 if (stack == null) {
3892 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3893 + stackId);
3894 }
3895 if (!stack.isActivityTypeStandardOrUndefined()) {
3896 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3897 + " the position of task " + taskId + " in/to non-standard stack");
3898 }
3899
3900 // TODO: Have the callers of this API call a separate reparent method if that is
3901 // what they intended to do vs. having this method also do reparenting.
3902 if (task.getStack() == stack) {
3903 // Change position in current stack.
3904 stack.positionChildAt(task, position);
3905 } else {
3906 // Reparent to new stack.
3907 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3908 !DEFER_RESUME, "positionTaskInStack");
3909 }
3910 } finally {
3911 Binder.restoreCallingIdentity(ident);
3912 }
3913 }
3914 }
3915
3916 @Override
3917 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3918 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3919 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3920 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3921 synchronized (mGlobalLock) {
3922 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3923 if (record == null) {
3924 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3925 + "found for: " + token);
3926 }
3927 record.setSizeConfigurations(horizontalSizeConfiguration,
3928 verticalSizeConfigurations, smallestSizeConfigurations);
3929 }
3930 }
3931
3932 /**
3933 * Dismisses split-screen multi-window mode.
3934 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3935 */
3936 @Override
3937 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003938 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3940 final long ident = Binder.clearCallingIdentity();
3941 try {
3942 synchronized (mGlobalLock) {
3943 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003944 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 if (stack == null) {
3946 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3947 return;
3948 }
3949
3950 if (toTop) {
3951 // Caller wants the current split-screen primary stack to be the top stack after
3952 // it goes fullscreen, so move it to the front.
3953 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003954 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 // In this case the current split-screen primary stack shouldn't be the top
3956 // stack after it goes fullscreen, but it current has focus, so we move the
3957 // focus to the top-most split-screen secondary stack next to it.
3958 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3959 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3960 if (otherStack != null) {
3961 otherStack.moveToFront("dismissSplitScreenMode_other");
3962 }
3963 }
3964
Evan Rosky10475742018-09-05 19:02:48 -07003965 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 }
3967 } finally {
3968 Binder.restoreCallingIdentity(ident);
3969 }
3970 }
3971
3972 /**
3973 * Dismisses Pip
3974 * @param animate True if the dismissal should be animated.
3975 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3976 * default animation duration should be used.
3977 */
3978 @Override
3979 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003980 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 final long ident = Binder.clearCallingIdentity();
3982 try {
3983 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003984 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003985 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003986 if (stack == null) {
3987 Slog.w(TAG, "dismissPip: pinned stack not found.");
3988 return;
3989 }
3990 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3991 throw new IllegalArgumentException("Stack: " + stack
3992 + " doesn't support animated resize.");
3993 }
3994 if (animate) {
3995 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3996 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3997 } else {
3998 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3999 }
4000 }
4001 } finally {
4002 Binder.restoreCallingIdentity(ident);
4003 }
4004 }
4005
4006 @Override
4007 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004008 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 synchronized (mGlobalLock) {
4010 mSuppressResizeConfigChanges = suppress;
4011 }
4012 }
4013
4014 /**
4015 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4016 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4017 * activity and clearing the task at the same time.
4018 */
4019 @Override
4020 // TODO: API should just be about changing windowing modes...
4021 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 "moveTasksToFullscreenStack()");
4024 synchronized (mGlobalLock) {
4025 final long origId = Binder.clearCallingIdentity();
4026 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004027 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 if (stack != null){
4029 if (!stack.isActivityTypeStandardOrUndefined()) {
4030 throw new IllegalArgumentException(
4031 "You can't move tasks from non-standard stacks.");
4032 }
4033 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(origId);
4037 }
4038 }
4039 }
4040
4041 /**
4042 * Moves the top activity in the input stackId to the pinned stack.
4043 *
4044 * @param stackId Id of stack to move the top activity to pinned stack.
4045 * @param bounds Bounds to use for pinned stack.
4046 *
4047 * @return True if the top activity of the input stack was successfully moved to the pinned
4048 * stack.
4049 */
4050 @Override
4051 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 "moveTopActivityToPinnedStack()");
4054 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4057 + "Device doesn't support picture-in-picture mode");
4058 }
4059
4060 long ident = Binder.clearCallingIdentity();
4061 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004062 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 } finally {
4064 Binder.restoreCallingIdentity(ident);
4065 }
4066 }
4067 }
4068
4069 @Override
4070 public boolean isInMultiWindowMode(IBinder token) {
4071 final long origId = Binder.clearCallingIdentity();
4072 try {
4073 synchronized (mGlobalLock) {
4074 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4075 if (r == null) {
4076 return false;
4077 }
4078 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4079 return r.inMultiWindowMode();
4080 }
4081 } finally {
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
4086 @Override
4087 public boolean isInPictureInPictureMode(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 try {
4090 synchronized (mGlobalLock) {
4091 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(origId);
4095 }
4096 }
4097
4098 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004099 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4100 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004101 return false;
4102 }
4103
4104 // If we are animating to fullscreen then we have already dispatched the PIP mode
4105 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004106 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4107 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004108 }
4109
4110 @Override
4111 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4112 final long origId = Binder.clearCallingIdentity();
4113 try {
4114 synchronized (mGlobalLock) {
4115 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4116 "enterPictureInPictureMode", token, params);
4117
4118 // If the activity is already in picture in picture mode, then just return early
4119 if (isInPictureInPictureMode(r)) {
4120 return true;
4121 }
4122
4123 // Activity supports picture-in-picture, now check that we can enter PiP at this
4124 // point, if it is
4125 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4126 false /* beforeStopping */)) {
4127 return false;
4128 }
4129
4130 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004131 synchronized (mGlobalLock) {
4132 // Only update the saved args from the args that are set
4133 r.pictureInPictureArgs.copyOnlySet(params);
4134 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4135 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4136 // Adjust the source bounds by the insets for the transition down
4137 final Rect sourceBounds = new Rect(
4138 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004139 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004140 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004141 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004142 stack.setPictureInPictureAspectRatio(aspectRatio);
4143 stack.setPictureInPictureActions(actions);
4144 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4145 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4146 logPictureInPictureArgs(params);
4147 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 };
4149
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004150 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 // If the keyguard is showing or occluded, then try and dismiss it before
4152 // entering picture-in-picture (this will prompt the user to authenticate if the
4153 // device is currently locked).
4154 dismissKeyguard(token, new KeyguardDismissCallback() {
4155 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 public void onDismissSucceeded() {
4157 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159 }, null /* message */);
4160 } else {
4161 // Enter picture in picture immediately otherwise
4162 enterPipRunnable.run();
4163 }
4164 return true;
4165 }
4166 } finally {
4167 Binder.restoreCallingIdentity(origId);
4168 }
4169 }
4170
4171 @Override
4172 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4173 final long origId = Binder.clearCallingIdentity();
4174 try {
4175 synchronized (mGlobalLock) {
4176 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4177 "setPictureInPictureParams", token, params);
4178
4179 // Only update the saved args from the args that are set
4180 r.pictureInPictureArgs.copyOnlySet(params);
4181 if (r.inPinnedWindowingMode()) {
4182 // If the activity is already in picture-in-picture, update the pinned stack now
4183 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4184 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004185 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 if (!stack.isAnimatingBoundsToFullscreen()) {
4187 stack.setPictureInPictureAspectRatio(
4188 r.pictureInPictureArgs.getAspectRatio());
4189 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4190 }
4191 }
4192 logPictureInPictureArgs(params);
4193 }
4194 } finally {
4195 Binder.restoreCallingIdentity(origId);
4196 }
4197 }
4198
4199 @Override
4200 public int getMaxNumPictureInPictureActions(IBinder token) {
4201 // Currently, this is a static constant, but later, we may change this to be dependent on
4202 // the context of the activity
4203 return 3;
4204 }
4205
4206 private void logPictureInPictureArgs(PictureInPictureParams params) {
4207 if (params.hasSetActions()) {
4208 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4209 params.getActions().size());
4210 }
4211 if (params.hasSetAspectRatio()) {
4212 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4213 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4214 MetricsLogger.action(lm);
4215 }
4216 }
4217
4218 /**
4219 * Checks the state of the system and the activity associated with the given {@param token} to
4220 * verify that picture-in-picture is supported for that activity.
4221 *
4222 * @return the activity record for the given {@param token} if all the checks pass.
4223 */
4224 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4225 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 throw new IllegalStateException(caller
4228 + ": Device doesn't support picture-in-picture mode.");
4229 }
4230
4231 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4232 if (r == null) {
4233 throw new IllegalStateException(caller
4234 + ": Can't find activity for token=" + token);
4235 }
4236
4237 if (!r.supportsPictureInPicture()) {
4238 throw new IllegalStateException(caller
4239 + ": Current activity does not support picture-in-picture.");
4240 }
4241
4242 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004243 && !mWindowManager.isValidPictureInPictureAspectRatio(
4244 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 final float minAspectRatio = mContext.getResources().getFloat(
4246 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4247 final float maxAspectRatio = mContext.getResources().getFloat(
4248 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4249 throw new IllegalArgumentException(String.format(caller
4250 + ": Aspect ratio is too extreme (must be between %f and %f).",
4251 minAspectRatio, maxAspectRatio));
4252 }
4253
4254 // Truncate the number of actions if necessary
4255 params.truncateActions(getMaxNumPictureInPictureActions(token));
4256
4257 return r;
4258 }
4259
4260 @Override
4261 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 synchronized (mGlobalLock) {
4264 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4265 if (r == null) {
4266 throw new IllegalArgumentException("Activity does not exist; token="
4267 + activityToken);
4268 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004269 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 }
4271 }
4272
4273 @Override
4274 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4275 Rect tempDockedTaskInsetBounds,
4276 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004277 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 long ident = Binder.clearCallingIdentity();
4279 try {
4280 synchronized (mGlobalLock) {
4281 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4282 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4283 PRESERVE_WINDOWS);
4284 }
4285 } finally {
4286 Binder.restoreCallingIdentity(ident);
4287 }
4288 }
4289
4290 @Override
4291 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 final long ident = Binder.clearCallingIdentity();
4294 try {
4295 synchronized (mGlobalLock) {
4296 mStackSupervisor.setSplitScreenResizing(resizing);
4297 }
4298 } finally {
4299 Binder.restoreCallingIdentity(ident);
4300 }
4301 }
4302
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004303 /**
4304 * Check that we have the features required for VR-related API calls, and throw an exception if
4305 * not.
4306 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004307 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 if (!mContext.getPackageManager().hasSystemFeature(
4309 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4310 throw new UnsupportedOperationException("VR mode not supported on this device!");
4311 }
4312 }
4313
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 @Override
4315 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317
4318 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4319
4320 ActivityRecord r;
4321 synchronized (mGlobalLock) {
4322 r = ActivityRecord.isInStackLocked(token);
4323 }
4324
4325 if (r == null) {
4326 throw new IllegalArgumentException();
4327 }
4328
4329 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004330 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004331 VrManagerInternal.NO_ERROR) {
4332 return err;
4333 }
4334
4335 // Clear the binder calling uid since this path may call moveToTask().
4336 final long callingId = Binder.clearCallingIdentity();
4337 try {
4338 synchronized (mGlobalLock) {
4339 r.requestedVrComponent = (enabled) ? packageName : null;
4340
4341 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004342 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004343 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004344 }
4345 return 0;
4346 }
4347 } finally {
4348 Binder.restoreCallingIdentity(callingId);
4349 }
4350 }
4351
4352 @Override
4353 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4354 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4355 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004356 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004357 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4358 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4359 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004360 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 || activity.voiceSession != null) {
4362 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4363 return;
4364 }
4365 if (activity.pendingVoiceInteractionStart) {
4366 Slog.w(TAG, "Pending start of voice interaction already.");
4367 return;
4368 }
4369 activity.pendingVoiceInteractionStart = true;
4370 }
4371 LocalServices.getService(VoiceInteractionManagerInternal.class)
4372 .startLocalVoiceInteraction(callingActivity, options);
4373 }
4374
4375 @Override
4376 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4377 LocalServices.getService(VoiceInteractionManagerInternal.class)
4378 .stopLocalVoiceInteraction(callingActivity);
4379 }
4380
4381 @Override
4382 public boolean supportsLocalVoiceInteraction() {
4383 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4384 .supportsLocalVoiceInteraction();
4385 }
4386
4387 /** Notifies all listeners when the pinned stack animation starts. */
4388 @Override
4389 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004390 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 }
4392
4393 /** Notifies all listeners when the pinned stack animation ends. */
4394 @Override
4395 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004396 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 }
4398
4399 @Override
4400 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 final long ident = Binder.clearCallingIdentity();
4403 try {
4404 synchronized (mGlobalLock) {
4405 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4406 }
4407 } finally {
4408 Binder.restoreCallingIdentity(ident);
4409 }
4410 }
4411
4412 @Override
4413 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415
4416 synchronized (mGlobalLock) {
4417 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004418 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 // Call might come when display is not yet added or has already been removed.
4420 if (DEBUG_CONFIGURATION) {
4421 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4422 + displayId);
4423 }
4424 return false;
4425 }
4426
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004427 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004429 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004433 final Message msg = PooledLambda.obtainMessage(
4434 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4435 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 }
4437
4438 final long origId = Binder.clearCallingIdentity();
4439 try {
4440 if (values != null) {
4441 Settings.System.clearConfiguration(values);
4442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4445 return mTmpUpdateConfigurationResult.changes != 0;
4446 } finally {
4447 Binder.restoreCallingIdentity(origId);
4448 }
4449 }
4450 }
4451
4452 @Override
4453 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455
4456 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 }
4461
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004462 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004463 final Message msg = PooledLambda.obtainMessage(
4464 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4465 DEFAULT_DISPLAY);
4466 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 }
4468
4469 final long origId = Binder.clearCallingIdentity();
4470 try {
4471 if (values != null) {
4472 Settings.System.clearConfiguration(values);
4473 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004474 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 UserHandle.USER_NULL, false /* deferResume */,
4476 mTmpUpdateConfigurationResult);
4477 return mTmpUpdateConfigurationResult.changes != 0;
4478 } finally {
4479 Binder.restoreCallingIdentity(origId);
4480 }
4481 }
4482 }
4483
4484 @Override
4485 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4486 CharSequence message) {
4487 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004488 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4490 }
4491 final long callingId = Binder.clearCallingIdentity();
4492 try {
4493 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004494 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 }
4496 } finally {
4497 Binder.restoreCallingIdentity(callingId);
4498 }
4499 }
4500
4501 @Override
4502 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 "cancelTaskWindowTransition()");
4505 final long ident = Binder.clearCallingIdentity();
4506 try {
4507 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004508 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 MATCH_TASK_IN_STACKS_ONLY);
4510 if (task == null) {
4511 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4512 return;
4513 }
4514 task.cancelWindowTransition();
4515 }
4516 } finally {
4517 Binder.restoreCallingIdentity(ident);
4518 }
4519 }
4520
4521 @Override
4522 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004523 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004524 final long ident = Binder.clearCallingIdentity();
4525 try {
4526 final TaskRecord task;
4527 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004528 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4530 if (task == null) {
4531 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4532 return null;
4533 }
4534 }
4535 // Don't call this while holding the lock as this operation might hit the disk.
4536 return task.getSnapshot(reducedResolution);
4537 } finally {
4538 Binder.restoreCallingIdentity(ident);
4539 }
4540 }
4541
4542 @Override
4543 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4544 synchronized (mGlobalLock) {
4545 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4546 if (r == null) {
4547 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4548 + token);
4549 return;
4550 }
4551 final long origId = Binder.clearCallingIdentity();
4552 try {
4553 r.setDisablePreviewScreenshots(disable);
4554 } finally {
4555 Binder.restoreCallingIdentity(origId);
4556 }
4557 }
4558 }
4559
4560 /** Return the user id of the last resumed activity. */
4561 @Override
4562 public @UserIdInt
4563 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004564 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4566 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004567 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004568 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004570 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 }
4572 }
4573
4574 @Override
4575 public void updateLockTaskFeatures(int userId, int flags) {
4576 final int callingUid = Binder.getCallingUid();
4577 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004578 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 "updateLockTaskFeatures()");
4580 }
4581 synchronized (mGlobalLock) {
4582 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4583 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004584 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 }
4586 }
4587
4588 @Override
4589 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4590 synchronized (mGlobalLock) {
4591 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4592 if (r == null) {
4593 return;
4594 }
4595 final long origId = Binder.clearCallingIdentity();
4596 try {
4597 r.setShowWhenLocked(showWhenLocked);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
4604 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004605 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4606 synchronized (mGlobalLock) {
4607 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4608 if (r == null) {
4609 return;
4610 }
4611 final long origId = Binder.clearCallingIdentity();
4612 try {
4613 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4614 } finally {
4615 Binder.restoreCallingIdentity(origId);
4616 }
4617 }
4618 }
4619
4620 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4622 synchronized (mGlobalLock) {
4623 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4624 if (r == null) {
4625 return;
4626 }
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
4629 r.setTurnScreenOn(turnScreenOn);
4630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
4635
4636 @Override
4637 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004638 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 "registerRemoteAnimations");
4640 definition.setCallingPid(Binder.getCallingPid());
4641 synchronized (mGlobalLock) {
4642 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4643 if (r == null) {
4644 return;
4645 }
4646 final long origId = Binder.clearCallingIdentity();
4647 try {
4648 r.registerRemoteAnimations(definition);
4649 } finally {
4650 Binder.restoreCallingIdentity(origId);
4651 }
4652 }
4653 }
4654
4655 @Override
4656 public void registerRemoteAnimationForNextActivityStart(String packageName,
4657 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004659 "registerRemoteAnimationForNextActivityStart");
4660 adapter.setCallingPid(Binder.getCallingPid());
4661 synchronized (mGlobalLock) {
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004664 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004665 packageName, adapter);
4666 } finally {
4667 Binder.restoreCallingIdentity(origId);
4668 }
4669 }
4670 }
4671
Evan Rosky966759f2019-01-15 10:33:58 -08004672 @Override
4673 public void registerRemoteAnimationsForDisplay(int displayId,
4674 RemoteAnimationDefinition definition) {
4675 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4676 "registerRemoteAnimations");
4677 definition.setCallingPid(Binder.getCallingPid());
4678 synchronized (mGlobalLock) {
4679 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4680 if (display == null) {
4681 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4682 return;
4683 }
4684 final long origId = Binder.clearCallingIdentity();
4685 try {
4686 display.mDisplayContent.registerRemoteAnimations(definition);
4687 } finally {
4688 Binder.restoreCallingIdentity(origId);
4689 }
4690 }
4691 }
4692
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004693 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4694 @Override
4695 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4696 synchronized (mGlobalLock) {
4697 final long origId = Binder.clearCallingIdentity();
4698 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004699 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004700 } finally {
4701 Binder.restoreCallingIdentity(origId);
4702 }
4703 }
4704 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004705
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 @Override
4707 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004708 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004710 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004711 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004712 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 }
4714 }
4715
4716 @Override
4717 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004718 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 != PERMISSION_GRANTED) {
4720 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4721 + Binder.getCallingPid()
4722 + ", uid=" + Binder.getCallingUid()
4723 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4724 Slog.w(TAG, msg);
4725 throw new SecurityException(msg);
4726 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004727 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004729 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004730 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004731 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 @Override
4736 public void stopAppSwitches() {
4737 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4738 synchronized (mGlobalLock) {
4739 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004740 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 mDidAppSwitch = false;
4742 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4743 }
4744 }
4745
4746 @Override
4747 public void resumeAppSwitches() {
4748 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4749 synchronized (mGlobalLock) {
4750 // Note that we don't execute any pending app switches... we will
4751 // let those wait until either the timeout, or the next start
4752 // activity request.
4753 mAppSwitchesAllowedTime = 0;
4754 }
4755 }
4756
Ricky Wai906af482019-06-03 17:25:28 +01004757 long getLastStopAppSwitchesTime() {
4758 return mLastStopAppSwitchesTime;
4759 }
4760
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004761 void onStartActivitySetDidAppSwitch() {
4762 if (mDidAppSwitch) {
4763 // This is the second allowed switch since we stopped switches, so now just generally
4764 // allow switches. Use case:
4765 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4766 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4767 // anyone to switch again).
4768 mAppSwitchesAllowedTime = 0;
4769 } else {
4770 mDidAppSwitch = true;
4771 }
4772 }
4773
4774 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 boolean shouldDisableNonVrUiLocked() {
4776 return mVrController.shouldDisableNonVrUiLocked();
4777 }
4778
Wale Ogunwale53783742018-09-16 10:21:51 -07004779 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 // VR apps are expected to run in a main display. If an app is turning on VR for
4781 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4782 // fullscreen stack before enabling VR Mode.
4783 // TODO: The goal of this code is to keep the VR app on the main display. When the
4784 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4785 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4786 // option would be a better choice here.
4787 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4788 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4789 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004790 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004792 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 }
4794 mH.post(() -> {
4795 if (!mVrController.onVrModeChanged(r)) {
4796 return;
4797 }
4798 synchronized (mGlobalLock) {
4799 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4800 mWindowManager.disableNonVrUi(disableNonVrUi);
4801 if (disableNonVrUi) {
4802 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4803 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004804 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 }
4806 }
4807 });
4808 }
4809
Wale Ogunwale53783742018-09-16 10:21:51 -07004810 @Override
4811 public int getPackageScreenCompatMode(String packageName) {
4812 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4813 synchronized (mGlobalLock) {
4814 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4815 }
4816 }
4817
4818 @Override
4819 public void setPackageScreenCompatMode(String packageName, int mode) {
4820 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4821 "setPackageScreenCompatMode");
4822 synchronized (mGlobalLock) {
4823 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4824 }
4825 }
4826
4827 @Override
4828 public boolean getPackageAskScreenCompat(String packageName) {
4829 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4830 synchronized (mGlobalLock) {
4831 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4832 }
4833 }
4834
4835 @Override
4836 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4837 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4838 "setPackageAskScreenCompat");
4839 synchronized (mGlobalLock) {
4840 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4841 }
4842 }
4843
Wale Ogunwale64258362018-10-16 15:13:37 -07004844 public static String relaunchReasonToString(int relaunchReason) {
4845 switch (relaunchReason) {
4846 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4847 return "window_resize";
4848 case RELAUNCH_REASON_FREE_RESIZE:
4849 return "free_resize";
4850 default:
4851 return null;
4852 }
4853 }
4854
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004855 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004856 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004857 }
4858
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004859 /** Pokes the task persister. */
4860 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4861 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4862 }
4863
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004864 boolean isKeyguardLocked() {
4865 return mKeyguardController.isKeyguardLocked();
4866 }
4867
Garfield Tan01548632018-11-27 10:15:48 -08004868 /**
4869 * Clears launch params for the given package.
4870 * @param packageNames the names of the packages of which the launch params are to be cleared
4871 */
4872 @Override
4873 public void clearLaunchParamsForPackages(List<String> packageNames) {
4874 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4875 "clearLaunchParamsForPackages");
4876 synchronized (mGlobalLock) {
4877 for (int i = 0; i < packageNames.size(); ++i) {
4878 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4879 }
4880 }
4881 }
4882
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004883 /**
4884 * Makes the display with the given id a single task instance display. I.e the display can only
4885 * contain one task.
4886 */
4887 @Override
4888 public void setDisplayToSingleTaskInstance(int displayId) {
4889 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4890 "setDisplayToSingleTaskInstance");
4891 final long origId = Binder.clearCallingIdentity();
4892 try {
4893 final ActivityDisplay display =
4894 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4895 if (display != null) {
4896 display.setDisplayToSingleTaskInstance();
4897 }
4898 } finally {
4899 Binder.restoreCallingIdentity(origId);
4900 }
4901 }
4902
Wale Ogunwale31913b52018-10-13 08:29:31 -07004903 void dumpLastANRLocked(PrintWriter pw) {
4904 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4905 if (mLastANRState == null) {
4906 pw.println(" <no ANR has occurred since boot>");
4907 } else {
4908 pw.println(mLastANRState);
4909 }
4910 }
4911
4912 void dumpLastANRTracesLocked(PrintWriter pw) {
4913 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4914
4915 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4916 if (ArrayUtils.isEmpty(files)) {
4917 pw.println(" <no ANR has occurred since boot>");
4918 return;
4919 }
4920 // Find the latest file.
4921 File latest = null;
4922 for (File f : files) {
4923 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4924 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004925 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004926 }
4927 pw.print("File: ");
4928 pw.print(latest.getName());
4929 pw.println();
4930 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4931 String line;
4932 while ((line = in.readLine()) != null) {
4933 pw.println(line);
4934 }
4935 } catch (IOException e) {
4936 pw.print("Unable to read: ");
4937 pw.print(e);
4938 pw.println();
4939 }
4940 }
4941
4942 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4943 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4944 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4945 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4946 }
4947
4948 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4949 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4950 pw.println(header);
4951
Wale Ogunwaled32da472018-11-16 07:19:28 -08004952 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004953 dumpPackage);
4954 boolean needSep = printedAnything;
4955
4956 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004957 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004958 " ResumedActivity: ");
4959 if (printed) {
4960 printedAnything = true;
4961 needSep = false;
4962 }
4963
4964 if (dumpPackage == null) {
4965 if (needSep) {
4966 pw.println();
4967 }
4968 printedAnything = true;
4969 mStackSupervisor.dump(pw, " ");
4970 }
4971
4972 if (!printedAnything) {
4973 pw.println(" (nothing)");
4974 }
4975 }
4976
4977 void dumpActivityContainersLocked(PrintWriter pw) {
4978 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004979 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004980 pw.println(" ");
4981 }
4982
4983 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4984 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4985 getActivityStartController().dump(pw, "", dumpPackage);
4986 }
4987
4988 /**
4989 * There are three things that cmd can be:
4990 * - a flattened component name that matches an existing activity
4991 * - the cmd arg isn't the flattened component name of an existing activity:
4992 * dump all activity whose component contains the cmd as a substring
4993 * - A hex number of the ActivityRecord object instance.
4994 *
4995 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4996 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4997 */
4998 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4999 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5000 ArrayList<ActivityRecord> activities;
5001
5002 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005003 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 dumpFocusedStackOnly);
5005 }
5006
5007 if (activities.size() <= 0) {
5008 return false;
5009 }
5010
5011 String[] newArgs = new String[args.length - opti];
5012 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5013
5014 TaskRecord lastTask = null;
5015 boolean needSep = false;
5016 for (int i = activities.size() - 1; i >= 0; i--) {
5017 ActivityRecord r = activities.get(i);
5018 if (needSep) {
5019 pw.println();
5020 }
5021 needSep = true;
5022 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005023 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005024 if (lastTask != task) {
5025 lastTask = task;
5026 pw.print("TASK "); pw.print(lastTask.affinity);
5027 pw.print(" id="); pw.print(lastTask.taskId);
5028 pw.print(" userId="); pw.println(lastTask.userId);
5029 if (dumpAll) {
5030 lastTask.dump(pw, " ");
5031 }
5032 }
5033 }
5034 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5035 }
5036 return true;
5037 }
5038
5039 /**
5040 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5041 * there is a thread associated with the activity.
5042 */
5043 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5044 final ActivityRecord r, String[] args, boolean dumpAll) {
5045 String innerPrefix = prefix + " ";
5046 synchronized (mGlobalLock) {
5047 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5048 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5049 pw.print(" pid=");
5050 if (r.hasProcess()) pw.println(r.app.getPid());
5051 else pw.println("(not running)");
5052 if (dumpAll) {
5053 r.dump(pw, innerPrefix);
5054 }
5055 }
5056 if (r.attachedToProcess()) {
5057 // flush anything that is already in the PrintWriter since the thread is going
5058 // to write to the file descriptor directly
5059 pw.flush();
5060 try {
5061 TransferPipe tp = new TransferPipe();
5062 try {
5063 r.app.getThread().dumpActivity(tp.getWriteFd(),
5064 r.appToken, innerPrefix, args);
5065 tp.go(fd);
5066 } finally {
5067 tp.kill();
5068 }
5069 } catch (IOException e) {
5070 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5071 } catch (RemoteException e) {
5072 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5073 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005074 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005075 }
5076
sanryhuang498e77e2018-12-06 14:57:01 +08005077 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5078 boolean testPssMode) {
5079 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5080 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5081 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005082 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005083 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5084 st.toString());
5085 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005086 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5087 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5088 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005089 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5090 testPssMode);
5091 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005092 }
5093
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094 int getCurrentUserId() {
5095 return mAmInternal.getCurrentUserId();
5096 }
5097
5098 private void enforceNotIsolatedCaller(String caller) {
5099 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5100 throw new SecurityException("Isolated process not allowed to call " + caller);
5101 }
5102 }
5103
Wale Ogunwalef6733932018-06-27 05:14:34 -07005104 public Configuration getConfiguration() {
5105 Configuration ci;
5106 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005107 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005108 ci.userSetLocale = false;
5109 }
5110 return ci;
5111 }
5112
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005113 /**
5114 * Current global configuration information. Contains general settings for the entire system,
5115 * also corresponds to the merged configuration of the default display.
5116 */
5117 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005118 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 }
5120
5121 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5122 boolean initLocale) {
5123 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5124 }
5125
5126 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5127 boolean initLocale, boolean deferResume) {
5128 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5129 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5130 UserHandle.USER_NULL, deferResume);
5131 }
5132
Wale Ogunwale59507092018-10-29 09:00:30 -07005133 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 final long origId = Binder.clearCallingIdentity();
5135 try {
5136 synchronized (mGlobalLock) {
5137 updateConfigurationLocked(values, null, false, true, userId,
5138 false /* deferResume */);
5139 }
5140 } finally {
5141 Binder.restoreCallingIdentity(origId);
5142 }
5143 }
5144
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005145 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5146 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5147 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5148 deferResume, null /* result */);
5149 }
5150
5151 /**
5152 * Do either or both things: (1) change the current configuration, and (2)
5153 * make sure the given activity is running with the (now) current
5154 * configuration. Returns true if the activity has been left running, or
5155 * false if <var>starting</var> is being destroyed to match the new
5156 * configuration.
5157 *
5158 * @param userId is only used when persistent parameter is set to true to persist configuration
5159 * for that particular user
5160 */
5161 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5162 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5163 ActivityTaskManagerService.UpdateConfigurationResult result) {
5164 int changes = 0;
5165 boolean kept = true;
5166
5167 if (mWindowManager != null) {
5168 mWindowManager.deferSurfaceLayout();
5169 }
5170 try {
5171 if (values != null) {
5172 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5173 deferResume);
5174 }
5175
5176 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5177 } finally {
5178 if (mWindowManager != null) {
5179 mWindowManager.continueSurfaceLayout();
5180 }
5181 }
5182
5183 if (result != null) {
5184 result.changes = changes;
5185 result.activityRelaunched = !kept;
5186 }
5187 return kept;
5188 }
5189
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190 /** Update default (global) configuration and notify listeners about changes. */
5191 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5192 boolean persistent, int userId, boolean deferResume) {
5193 mTempConfig.setTo(getGlobalConfiguration());
5194 final int changes = mTempConfig.updateFrom(values);
5195 if (changes == 0) {
5196 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5197 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5198 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5199 // (even if there are no actual changes) to unfreeze the window.
5200 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5201 return 0;
5202 }
5203
5204 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5205 "Updating global configuration to: " + values);
5206
5207 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5208 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5209 values.colorMode,
5210 values.densityDpi,
5211 values.fontScale,
5212 values.hardKeyboardHidden,
5213 values.keyboard,
5214 values.keyboardHidden,
5215 values.mcc,
5216 values.mnc,
5217 values.navigation,
5218 values.navigationHidden,
5219 values.orientation,
5220 values.screenHeightDp,
5221 values.screenLayout,
5222 values.screenWidthDp,
5223 values.smallestScreenWidthDp,
5224 values.touchscreen,
5225 values.uiMode);
5226
5227
5228 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5229 final LocaleList locales = values.getLocales();
5230 int bestLocaleIndex = 0;
5231 if (locales.size() > 1) {
5232 if (mSupportedSystemLocales == null) {
5233 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5234 }
5235 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5236 }
5237 SystemProperties.set("persist.sys.locale",
5238 locales.get(bestLocaleIndex).toLanguageTag());
5239 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005240
5241 final Message m = PooledLambda.obtainMessage(
5242 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5243 locales.get(bestLocaleIndex));
5244 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 }
5246
Yunfan Chen75157d72018-07-27 14:47:21 +09005247 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248
5249 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005250 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251
5252 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5253 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005254 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255
5256 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258
5259 AttributeCache ac = AttributeCache.instance();
5260 if (ac != null) {
5261 ac.updateConfiguration(mTempConfig);
5262 }
5263
5264 // Make sure all resources in our process are updated right now, so that anyone who is going
5265 // to retrieve resource values after we return will be sure to get the new ones. This is
5266 // especially important during boot, where the first config change needs to guarantee all
5267 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005268 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 // We need another copy of global config because we're scheduling some calls instead of
5271 // running them in place. We need to be sure that object we send will be handled unchanged.
5272 final Configuration configCopy = new Configuration(mTempConfig);
5273 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005274 final Message msg = PooledLambda.obtainMessage(
5275 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5276 this, userId, configCopy);
5277 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
5279
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005280 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5281 for (int i = pidMap.size() - 1; i >= 0; i--) {
5282 final int pid = pidMap.keyAt(i);
5283 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005284 if (DEBUG_CONFIGURATION) {
5285 Slog.v(TAG_CONFIGURATION, "Update process config of "
5286 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005288 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005291 final Message msg = PooledLambda.obtainMessage(
5292 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5293 mAmInternal, changes, initLocale);
5294 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 // Override configuration of the default display duplicates global config, so we need to
5297 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005298 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299 DEFAULT_DISPLAY);
5300
5301 return changes;
5302 }
5303
5304 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5305 boolean deferResume, int displayId) {
5306 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5307 displayId, null /* result */);
5308 }
5309
5310 /**
5311 * Updates override configuration specific for the selected display. If no config is provided,
5312 * new one will be computed in WM based on current display info.
5313 */
5314 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5315 ActivityRecord starting, boolean deferResume, int displayId,
5316 ActivityTaskManagerService.UpdateConfigurationResult result) {
5317 int changes = 0;
5318 boolean kept = true;
5319
5320 if (mWindowManager != null) {
5321 mWindowManager.deferSurfaceLayout();
5322 }
5323 try {
5324 if (values != null) {
5325 if (displayId == DEFAULT_DISPLAY) {
5326 // Override configuration of the default display duplicates global config, so
5327 // we're calling global config update instead for default display. It will also
5328 // apply the correct override config.
5329 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5330 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5331 } else {
5332 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5333 }
5334 }
5335
5336 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5337 } finally {
5338 if (mWindowManager != null) {
5339 mWindowManager.continueSurfaceLayout();
5340 }
5341 }
5342
5343 if (result != null) {
5344 result.changes = changes;
5345 result.activityRelaunched = !kept;
5346 }
5347 return kept;
5348 }
5349
5350 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5351 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005352 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 final int changes = mTempConfig.updateFrom(values);
5354 if (changes != 0) {
5355 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5356 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005357 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005358
5359 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5360 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005361 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362
Wale Ogunwale5c918702018-10-18 11:06:33 -07005363 // Post message to start process to avoid possible deadlock of calling into AMS with
5364 // the ATMS lock held.
5365 final Message msg = PooledLambda.obtainMessage(
5366 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005367 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005368 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369 }
5370 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005371 return changes;
5372 }
5373
Wale Ogunwalef6733932018-06-27 05:14:34 -07005374 private void updateEventDispatchingLocked(boolean booted) {
5375 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5376 }
5377
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5379 final ContentResolver resolver = mContext.getContentResolver();
5380 Settings.System.putConfigurationForUser(resolver, config, userId);
5381 }
5382
5383 private void sendLocaleToMountDaemonMsg(Locale l) {
5384 try {
5385 IBinder service = ServiceManager.getService("mount");
5386 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5387 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5388 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5389 } catch (RemoteException e) {
5390 Log.e(TAG, "Error storing locale for decryption UI", e);
5391 }
5392 }
5393
Alison Cichowlas3e340502018-08-07 17:15:01 -04005394 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5395 mStartActivitySources.remove(permissionToken);
5396 mExpiredStartAsCallerTokens.add(permissionToken);
5397 }
5398
5399 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5400 mExpiredStartAsCallerTokens.remove(permissionToken);
5401 }
5402
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005403 boolean isActivityStartsLoggingEnabled() {
5404 return mAmInternal.isActivityStartsLoggingEnabled();
5405 }
5406
Michal Karpinski8596ded2018-11-14 14:43:48 +00005407 boolean isBackgroundActivityStartsEnabled() {
5408 return mAmInternal.isBackgroundActivityStartsEnabled();
5409 }
5410
Ricky Waiaca8a772019-04-04 16:01:06 +01005411 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5412 if (packageName == null) {
5413 return false;
5414 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005415 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5416 }
5417
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 void enableScreenAfterBoot(boolean booted) {
5419 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5420 SystemClock.uptimeMillis());
5421 mWindowManager.enableScreenAfterBoot();
5422
5423 synchronized (mGlobalLock) {
5424 updateEventDispatchingLocked(booted);
5425 }
5426 }
5427
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005428 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5429 if (r == null || !r.hasProcess()) {
5430 return KEY_DISPATCHING_TIMEOUT_MS;
5431 }
5432 return getInputDispatchingTimeoutLocked(r.app);
5433 }
5434
5435 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005436 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005437 }
5438
Wale Ogunwalef6733932018-06-27 05:14:34 -07005439 /**
5440 * Decide based on the configuration whether we should show the ANR,
5441 * crash, etc dialogs. The idea is that if there is no affordance to
5442 * press the on-screen buttons, or the user experience would be more
5443 * greatly impacted than the crash itself, we shouldn't show the dialog.
5444 *
5445 * A thought: SystemUI might also want to get told about this, the Power
5446 * dialog / global actions also might want different behaviors.
5447 */
5448 private void updateShouldShowDialogsLocked(Configuration config) {
5449 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5450 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5451 && config.navigation == Configuration.NAVIGATION_NONAV);
5452 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5453 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5454 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5455 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5456 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5457 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5458 HIDE_ERROR_DIALOGS, 0) != 0;
5459 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5460 }
5461
5462 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5463 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5464 FONT_SCALE, 1.0f, userId);
5465
5466 synchronized (this) {
5467 if (getGlobalConfiguration().fontScale == scaleFactor) {
5468 return;
5469 }
5470
5471 final Configuration configuration
5472 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5473 configuration.fontScale = scaleFactor;
5474 updatePersistentConfiguration(configuration, userId);
5475 }
5476 }
5477
5478 // Actually is sleeping or shutting down or whatever else in the future
5479 // is an inactive state.
5480 boolean isSleepingOrShuttingDownLocked() {
5481 return isSleepingLocked() || mShuttingDown;
5482 }
5483
5484 boolean isSleepingLocked() {
5485 return mSleeping;
5486 }
5487
Riddle Hsu16567132018-08-16 21:37:47 +08005488 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005490 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005491 if (task.isActivityTypeStandard()) {
5492 if (mCurAppTimeTracker != r.appTimeTracker) {
5493 // We are switching app tracking. Complete the current one.
5494 if (mCurAppTimeTracker != null) {
5495 mCurAppTimeTracker.stop();
5496 mH.obtainMessage(
5497 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005498 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499 mCurAppTimeTracker = null;
5500 }
5501 if (r.appTimeTracker != null) {
5502 mCurAppTimeTracker = r.appTimeTracker;
5503 startTimeTrackingFocusedActivityLocked();
5504 }
5505 } else {
5506 startTimeTrackingFocusedActivityLocked();
5507 }
5508 } else {
5509 r.appTimeTracker = null;
5510 }
5511 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5512 // TODO: Probably not, because we don't want to resume voice on switching
5513 // back to this activity
5514 if (task.voiceInteractor != null) {
5515 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5516 } else {
5517 finishRunningVoiceLocked();
5518
5519 if (mLastResumedActivity != null) {
5520 final IVoiceInteractionSession session;
5521
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005522 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005523 if (lastResumedActivityTask != null
5524 && lastResumedActivityTask.voiceSession != null) {
5525 session = lastResumedActivityTask.voiceSession;
5526 } else {
5527 session = mLastResumedActivity.voiceSession;
5528 }
5529
5530 if (session != null) {
5531 // We had been in a voice interaction session, but now focused has
5532 // move to something different. Just finish the session, we can't
5533 // return to it and retain the proper state and synchronization with
5534 // the voice interaction service.
5535 finishVoiceTask(session);
5536 }
5537 }
5538 }
5539
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005540 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5541 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 }
5543 updateResumedAppTrace(r);
5544 mLastResumedActivity = r;
5545
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005546 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547
5548 applyUpdateLockStateLocked(r);
5549 applyUpdateVrModeLocked(r);
5550
5551 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005552 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553 r == null ? "NULL" : r.shortComponentName,
5554 reason);
5555 }
5556
5557 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5558 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005559 final ActivityTaskManagerInternal.SleepToken token =
5560 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561 updateSleepIfNeededLocked();
5562 return token;
5563 }
5564 }
5565
5566 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005567 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 final boolean wasSleeping = mSleeping;
5569 boolean updateOomAdj = false;
5570
5571 if (!shouldSleep) {
5572 // If wasSleeping is true, we need to wake up activity manager state from when
5573 // we started sleeping. In either case, we need to apply the sleep tokens, which
5574 // will wake up stacks or put them to sleep as appropriate.
5575 if (wasSleeping) {
5576 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005577 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5578 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579 startTimeTrackingFocusedActivityLocked();
5580 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005581 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5583 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005584 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 if (wasSleeping) {
5586 updateOomAdj = true;
5587 }
5588 } else if (!mSleeping && shouldSleep) {
5589 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005590 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5591 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 if (mCurAppTimeTracker != null) {
5593 mCurAppTimeTracker.stop();
5594 }
5595 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005596 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597 mStackSupervisor.goingToSleepLocked();
5598 updateResumedAppTrace(null /* resumed */);
5599 updateOomAdj = true;
5600 }
5601 if (updateOomAdj) {
5602 mH.post(mAmInternal::updateOomAdj);
5603 }
5604 }
5605
5606 void updateOomAdj() {
5607 mH.post(mAmInternal::updateOomAdj);
5608 }
5609
Wale Ogunwale53783742018-09-16 10:21:51 -07005610 void updateCpuStats() {
5611 mH.post(mAmInternal::updateCpuStats);
5612 }
5613
Hui Yu03d12402018-12-06 18:00:37 -08005614 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5615 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005616 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5617 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005618 mH.sendMessage(m);
5619 }
5620
Hui Yu03d12402018-12-06 18:00:37 -08005621 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005622 ComponentName taskRoot = null;
5623 final TaskRecord task = activity.getTaskRecord();
5624 if (task != null) {
5625 final ActivityRecord rootActivity = task.getRootActivity();
5626 if (rootActivity != null) {
5627 taskRoot = rootActivity.mActivityComponent;
5628 }
5629 }
5630
Hui Yu03d12402018-12-06 18:00:37 -08005631 final Message m = PooledLambda.obtainMessage(
5632 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005633 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005634 mH.sendMessage(m);
5635 }
5636
Wale Ogunwale53783742018-09-16 10:21:51 -07005637 void setBooting(boolean booting) {
5638 mAmInternal.setBooting(booting);
5639 }
5640
5641 boolean isBooting() {
5642 return mAmInternal.isBooting();
5643 }
5644
5645 void setBooted(boolean booted) {
5646 mAmInternal.setBooted(booted);
5647 }
5648
5649 boolean isBooted() {
5650 return mAmInternal.isBooted();
5651 }
5652
5653 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5654 mH.post(() -> {
5655 if (finishBooting) {
5656 mAmInternal.finishBooting();
5657 }
5658 if (enableScreen) {
5659 mInternal.enableScreenAfterBoot(isBooted());
5660 }
5661 });
5662 }
5663
5664 void setHeavyWeightProcess(ActivityRecord root) {
5665 mHeavyWeightProcess = root.app;
5666 final Message m = PooledLambda.obtainMessage(
5667 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005668 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005669 mH.sendMessage(m);
5670 }
5671
5672 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5673 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5674 return;
5675 }
5676
5677 mHeavyWeightProcess = null;
5678 final Message m = PooledLambda.obtainMessage(
5679 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5680 proc.mUserId);
5681 mH.sendMessage(m);
5682 }
5683
5684 private void cancelHeavyWeightProcessNotification(int userId) {
5685 final INotificationManager inm = NotificationManager.getService();
5686 if (inm == null) {
5687 return;
5688 }
5689 try {
5690 inm.cancelNotificationWithTag("android", null,
5691 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5692 } catch (RuntimeException e) {
5693 Slog.w(TAG, "Error canceling notification for service", e);
5694 } catch (RemoteException e) {
5695 }
5696
5697 }
5698
5699 private void postHeavyWeightProcessNotification(
5700 WindowProcessController proc, Intent intent, int userId) {
5701 if (proc == null) {
5702 return;
5703 }
5704
5705 final INotificationManager inm = NotificationManager.getService();
5706 if (inm == null) {
5707 return;
5708 }
5709
5710 try {
5711 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5712 String text = mContext.getString(R.string.heavy_weight_notification,
5713 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5714 Notification notification =
5715 new Notification.Builder(context,
5716 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5717 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5718 .setWhen(0)
5719 .setOngoing(true)
5720 .setTicker(text)
5721 .setColor(mContext.getColor(
5722 com.android.internal.R.color.system_notification_accent_color))
5723 .setContentTitle(text)
5724 .setContentText(
5725 mContext.getText(R.string.heavy_weight_notification_detail))
5726 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5727 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5728 new UserHandle(userId)))
5729 .build();
5730 try {
5731 inm.enqueueNotificationWithTag("android", "android", null,
5732 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5733 } catch (RuntimeException e) {
5734 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5735 } catch (RemoteException e) {
5736 }
5737 } catch (PackageManager.NameNotFoundException e) {
5738 Slog.w(TAG, "Unable to create context for heavy notification", e);
5739 }
5740
5741 }
5742
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005743 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5744 IBinder token, String resultWho, int requestCode, Intent[] intents,
5745 String[] resolvedTypes, int flags, Bundle bOptions) {
5746
5747 ActivityRecord activity = null;
5748 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5749 activity = ActivityRecord.isInStackLocked(token);
5750 if (activity == null) {
5751 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5752 return null;
5753 }
5754 if (activity.finishing) {
5755 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5756 return null;
5757 }
5758 }
5759
5760 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5761 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5762 bOptions);
5763 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5764 if (noCreate) {
5765 return rec;
5766 }
5767 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5768 if (activity.pendingResults == null) {
5769 activity.pendingResults = new HashSet<>();
5770 }
5771 activity.pendingResults.add(rec.ref);
5772 }
5773 return rec;
5774 }
5775
Andrii Kulian52d255c2018-07-13 11:32:19 -07005776 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005777 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005778 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005779 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5780 mCurAppTimeTracker.start(resumedActivity.packageName);
5781 }
5782 }
5783
5784 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5785 if (mTracedResumedActivity != null) {
5786 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5787 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5788 }
5789 if (resumed != null) {
5790 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5791 constructResumedTraceName(resumed.packageName), 0);
5792 }
5793 mTracedResumedActivity = resumed;
5794 }
5795
5796 private String constructResumedTraceName(String packageName) {
5797 return "focused app: " + packageName;
5798 }
5799
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005800 /** Applies latest configuration and/or visibility updates if needed. */
5801 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5802 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005803 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005804 // mainStack is null during startup.
5805 if (mainStack != null) {
5806 if (changes != 0 && starting == null) {
5807 // If the configuration changed, and the caller is not already
5808 // in the process of starting an activity, then find the top
5809 // activity to check if its configuration needs to change.
5810 starting = mainStack.topRunningActivityLocked();
5811 }
5812
5813 if (starting != null) {
5814 kept = starting.ensureActivityConfiguration(changes,
5815 false /* preserveWindow */);
5816 // And we need to make sure at this point that all other activities
5817 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005818 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005819 !PRESERVE_WINDOWS);
5820 }
5821 }
5822
5823 return kept;
5824 }
5825
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005826 void scheduleAppGcsLocked() {
5827 mH.post(() -> mAmInternal.scheduleAppGcs());
5828 }
5829
Wale Ogunwale53783742018-09-16 10:21:51 -07005830 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5831 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5832 }
5833
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005834 /**
5835 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5836 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5837 * on demand.
5838 */
5839 IPackageManager getPackageManager() {
5840 return AppGlobals.getPackageManager();
5841 }
5842
5843 PackageManagerInternal getPackageManagerInternalLocked() {
5844 if (mPmInternal == null) {
5845 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5846 }
5847 return mPmInternal;
5848 }
5849
Hai Zhangf4da9be2019-05-01 13:46:06 +08005850 PermissionPolicyInternal getPermissionPolicyInternal() {
5851 if (mPermissionPolicyInternal == null) {
5852 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5853 }
5854 return mPermissionPolicyInternal;
5855 }
5856
Wale Ogunwale008163e2018-07-23 23:11:08 -07005857 AppWarnings getAppWarningsLocked() {
5858 return mAppWarnings;
5859 }
5860
Wale Ogunwale214f3482018-10-04 11:00:47 -07005861 Intent getHomeIntent() {
5862 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5863 intent.setComponent(mTopComponent);
5864 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5865 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5866 intent.addCategory(Intent.CATEGORY_HOME);
5867 }
5868 return intent;
5869 }
5870
Chilun2ef71f72018-11-16 17:57:15 +08005871 /**
5872 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5873 * activities.
5874 *
5875 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5876 * component defined in config_secondaryHomeComponent.
5877 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5878 */
5879 Intent getSecondaryHomeIntent(String preferredPackage) {
5880 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005881 if (preferredPackage == null) {
5882 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005883 final String secondaryHomeComponent = mContext.getResources().getString(
5884 com.android.internal.R.string.config_secondaryHomeComponent);
5885 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5886 } else {
5887 intent.setPackage(preferredPackage);
5888 }
5889 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5890 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5891 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5892 }
5893 return intent;
5894 }
5895
Wale Ogunwale214f3482018-10-04 11:00:47 -07005896 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5897 if (info == null) return null;
5898 ApplicationInfo newInfo = new ApplicationInfo(info);
5899 newInfo.initForUser(userId);
5900 return newInfo;
5901 }
5902
Wale Ogunwale9c103022018-10-18 07:44:54 -07005903 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005904 if (uid == SYSTEM_UID) {
5905 // The system gets to run in any process. If there are multiple processes with the same
5906 // uid, just pick the first (this should never happen).
5907 final SparseArray<WindowProcessController> procs =
5908 mProcessNames.getMap().get(processName);
5909 if (procs == null) return null;
5910 final int procCount = procs.size();
5911 for (int i = 0; i < procCount; i++) {
5912 final int procUid = procs.keyAt(i);
5913 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5914 // Don't use an app process or different user process for system component.
5915 continue;
5916 }
5917 return procs.valueAt(i);
5918 }
5919 }
5920
5921 return mProcessNames.get(processName, uid);
5922 }
5923
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005924 WindowProcessController getProcessController(IApplicationThread thread) {
5925 if (thread == null) {
5926 return null;
5927 }
5928
5929 final IBinder threadBinder = thread.asBinder();
5930 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5931 for (int i = pmap.size()-1; i >= 0; i--) {
5932 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5933 for (int j = procs.size() - 1; j >= 0; j--) {
5934 final WindowProcessController proc = procs.valueAt(j);
5935 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5936 return proc;
5937 }
5938 }
5939 }
5940
5941 return null;
5942 }
5943
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005944 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005945 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005946 if (proc == null) return null;
5947 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5948 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005949 }
5950 return null;
5951 }
5952
Riddle Hsua0536432019-02-16 00:38:59 +08005953 int getUidState(int uid) {
5954 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005955 }
5956
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005957 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005958 // A uid is considered to be foreground if it has a visible non-toast window.
5959 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005960 }
5961
Ricky Wai96f5c352019-04-10 18:40:17 +01005962 boolean isDeviceOwner(int uid) {
5963 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005964 }
5965
Ricky Wai96f5c352019-04-10 18:40:17 +01005966 void setDeviceOwnerUid(int uid) {
5967 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005968 }
5969
Wale Ogunwale9de19442018-10-18 19:05:03 -07005970 /**
5971 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5972 * the whitelist
5973 */
5974 String getPendingTempWhitelistTagForUidLocked(int uid) {
5975 return mPendingTempWhitelist.get(uid);
5976 }
5977
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005978 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5979 if (true || Build.IS_USER) {
5980 return;
5981 }
5982
5983 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5984 StrictMode.allowThreadDiskWrites();
5985 try {
5986 File tracesDir = new File("/data/anr");
5987 File tracesFile = null;
5988 try {
5989 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5990
5991 StringBuilder sb = new StringBuilder();
5992 Time tobj = new Time();
5993 tobj.set(System.currentTimeMillis());
5994 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5995 sb.append(": ");
5996 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5997 sb.append(" since ");
5998 sb.append(msg);
5999 FileOutputStream fos = new FileOutputStream(tracesFile);
6000 fos.write(sb.toString().getBytes());
6001 if (app == null) {
6002 fos.write("\n*** No application process!".getBytes());
6003 }
6004 fos.close();
6005 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6006 } catch (IOException e) {
6007 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6008 return;
6009 }
6010
6011 if (app != null && app.getPid() > 0) {
6012 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6013 firstPids.add(app.getPid());
6014 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6015 }
6016
6017 File lastTracesFile = null;
6018 File curTracesFile = null;
6019 for (int i=9; i>=0; i--) {
6020 String name = String.format(Locale.US, "slow%02d.txt", i);
6021 curTracesFile = new File(tracesDir, name);
6022 if (curTracesFile.exists()) {
6023 if (lastTracesFile != null) {
6024 curTracesFile.renameTo(lastTracesFile);
6025 } else {
6026 curTracesFile.delete();
6027 }
6028 }
6029 lastTracesFile = curTracesFile;
6030 }
6031 tracesFile.renameTo(curTracesFile);
6032 } finally {
6033 StrictMode.setThreadPolicy(oldPolicy);
6034 }
6035 }
6036
Michal Karpinskida34cd42019-04-02 19:46:52 +01006037 boolean isAssociatedCompanionApp(int userId, int uid) {
6038 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6039 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006040 return false;
6041 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006042 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006043 }
6044
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006045 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006046 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006047
6048
Wale Ogunwale98875612018-10-12 07:53:02 -07006049 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6050 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006051
Riddle Hsud93a6c42018-11-29 21:50:06 +08006052 H(Looper looper) {
6053 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006054 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006055
6056 @Override
6057 public void handleMessage(Message msg) {
6058 switch (msg.what) {
6059 case REPORT_TIME_TRACKER_MSG: {
6060 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6061 tracker.deliverResult(mContext);
6062 } break;
6063 }
6064 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006065 }
6066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006067 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006068 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006069
6070 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006071 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006072 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006073
6074 @Override
6075 public void handleMessage(Message msg) {
6076 switch (msg.what) {
6077 case DISMISS_DIALOG_UI_MSG: {
6078 final Dialog d = (Dialog) msg.obj;
6079 d.dismiss();
6080 break;
6081 }
6082 }
6083 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006084 }
6085
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006086 final class LocalService extends ActivityTaskManagerInternal {
6087 @Override
6088 public SleepToken acquireSleepToken(String tag, int displayId) {
6089 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092
6093 @Override
6094 public ComponentName getHomeActivityForUser(int userId) {
6095 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006096 final ActivityRecord homeActivity =
6097 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006098 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 }
6100 }
6101
6102 @Override
6103 public void onLocalVoiceInteractionStarted(IBinder activity,
6104 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6105 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006106 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 }
6108 }
6109
6110 @Override
6111 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6112 synchronized (mGlobalLock) {
6113 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6114 reasons, timestamp);
6115 }
6116 }
6117
6118 @Override
6119 public void notifyAppTransitionFinished() {
6120 synchronized (mGlobalLock) {
6121 mStackSupervisor.notifyAppTransitionDone();
6122 }
6123 }
6124
6125 @Override
6126 public void notifyAppTransitionCancelled() {
6127 synchronized (mGlobalLock) {
6128 mStackSupervisor.notifyAppTransitionDone();
6129 }
6130 }
6131
6132 @Override
6133 public List<IBinder> getTopVisibleActivities() {
6134 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006135 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006136 }
6137 }
6138
6139 @Override
6140 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6141 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006142 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 }
6144 }
6145
6146 @Override
6147 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6148 Bundle bOptions) {
6149 Preconditions.checkNotNull(intents, "intents");
6150 final String[] resolvedTypes = new String[intents.length];
6151
6152 // UID of the package on user userId.
6153 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6154 // packageUid may not be initialized.
6155 int packageUid = 0;
6156 final long ident = Binder.clearCallingIdentity();
6157
6158 try {
6159 for (int i = 0; i < intents.length; i++) {
6160 resolvedTypes[i] =
6161 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6162 }
6163
6164 packageUid = AppGlobals.getPackageManager().getPackageUid(
6165 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6166 } catch (RemoteException e) {
6167 // Shouldn't happen.
6168 } finally {
6169 Binder.restoreCallingIdentity(ident);
6170 }
6171
Riddle Hsu591bf612019-02-14 17:55:31 +08006172 return getActivityStartController().startActivitiesInPackage(
6173 packageUid, packageName,
6174 intents, resolvedTypes, null /* resultTo */,
6175 SafeActivityOptions.fromBundle(bOptions), userId,
6176 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6177 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179
6180 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006181 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6182 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6183 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6184 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006185 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006186 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006187 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6188 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6189 userId, validateIncomingUser, originatingPendingIntent,
6190 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006191 }
6192 }
6193
6194 @Override
6195 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6196 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6197 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6198 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006199 PendingIntentRecord originatingPendingIntent,
6200 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006201 synchronized (mGlobalLock) {
6202 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6203 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6204 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006205 validateIncomingUser, originatingPendingIntent,
6206 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006207 }
6208 }
6209
6210 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6212 Intent intent, Bundle options, int userId) {
6213 return ActivityTaskManagerService.this.startActivityAsUser(
6214 caller, callerPacakge, intent,
6215 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6216 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6217 false /*validateIncomingUser*/);
6218 }
6219
6220 @Override
lumark588a3e82018-07-20 18:53:54 +08006221 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 synchronized (mGlobalLock) {
6223
6224 // We might change the visibilities here, so prepare an empty app transition which
6225 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006226 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006227 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006228 if (activityDisplay == null) {
6229 return;
6230 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006231 final DisplayContent dc = activityDisplay.mDisplayContent;
6232 final boolean wasTransitionSet =
6233 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006235 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006237 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238
6239 // If there was a transition set already we don't want to interfere with it as we
6240 // might be starting it too early.
6241 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006242 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243 }
6244 }
6245 if (callback != null) {
6246 callback.run();
6247 }
6248 }
6249
6250 @Override
6251 public void notifyKeyguardTrustedChanged() {
6252 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006253 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006254 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 }
6256 }
6257 }
6258
6259 /**
6260 * Called after virtual display Id is updated by
6261 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6262 * {@param vrVr2dDisplayId}.
6263 */
6264 @Override
6265 public void setVr2dDisplayId(int vr2dDisplayId) {
6266 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6267 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006268 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
6270 }
6271
6272 @Override
6273 public void setFocusedActivity(IBinder token) {
6274 synchronized (mGlobalLock) {
6275 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6276 if (r == null) {
6277 throw new IllegalArgumentException(
6278 "setFocusedActivity: No activity record matching token=" + token);
6279 }
Louis Chang19443452018-10-09 12:10:21 +08006280 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006281 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
6283 }
6284 }
6285
6286 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006287 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006288 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290
6291 @Override
6292 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006293 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 }
6295
6296 @Override
6297 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006298 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 }
6300
6301 @Override
6302 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6303 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6304 }
6305
6306 @Override
6307 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006308 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006310
6311 @Override
6312 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6313 synchronized (mGlobalLock) {
6314 mActiveVoiceInteractionServiceComponent = component;
6315 }
6316 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006317
6318 @Override
6319 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6320 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6321 return;
6322 }
6323 synchronized (mGlobalLock) {
6324 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6325 if (types == null) {
6326 if (uid < 0) {
6327 return;
6328 }
6329 types = new ArrayMap<>();
6330 mAllowAppSwitchUids.put(userId, types);
6331 }
6332 if (uid < 0) {
6333 types.remove(type);
6334 } else {
6335 types.put(type, uid);
6336 }
6337 }
6338 }
6339
6340 @Override
6341 public void onUserStopped(int userId) {
6342 synchronized (mGlobalLock) {
6343 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6344 mAllowAppSwitchUids.remove(userId);
6345 }
6346 }
6347
6348 @Override
6349 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6350 synchronized (mGlobalLock) {
6351 return ActivityTaskManagerService.this.isGetTasksAllowed(
6352 caller, callingPid, callingUid);
6353 }
6354 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006355
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 onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360 mProcessNames.put(proc.mName, proc.mUid, proc);
6361 }
6362 }
6363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 @Override
6366 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006368 mProcessNames.remove(name, uid);
6369 }
6370 }
6371
Riddle Hsua0536432019-02-16 00:38:59 +08006372 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006373 @Override
6374 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006375 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006376 if (proc == mHomeProcess) {
6377 mHomeProcess = null;
6378 }
6379 if (proc == mPreviousProcess) {
6380 mPreviousProcess = null;
6381 }
6382 }
6383 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 @Override
6387 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006389 return mTopProcessState;
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006394 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006395 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006397 return proc == mHeavyWeightProcess;
6398 }
6399 }
6400
Riddle Hsua0536432019-02-16 00:38:59 +08006401 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 @Override
6403 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006404 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006405 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6406 }
6407 }
6408
6409 @Override
6410 public void finishHeavyWeightApp() {
6411 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006412 if (mHeavyWeightProcess != null) {
6413 mHeavyWeightProcess.finishActivities();
6414 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006415 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6416 mHeavyWeightProcess);
6417 }
6418 }
6419
Riddle Hsua0536432019-02-16 00:38:59 +08006420 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006422 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006423 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006424 return isSleepingLocked();
6425 }
6426 }
6427
6428 @Override
6429 public boolean isShuttingDown() {
6430 synchronized (mGlobalLock) {
6431 return mShuttingDown;
6432 }
6433 }
6434
6435 @Override
6436 public boolean shuttingDown(boolean booted, int timeout) {
6437 synchronized (mGlobalLock) {
6438 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006439 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006440 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006441 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006442 return mStackSupervisor.shutdownLocked(timeout);
6443 }
6444 }
6445
6446 @Override
6447 public void enableScreenAfterBoot(boolean booted) {
6448 synchronized (mGlobalLock) {
6449 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6450 SystemClock.uptimeMillis());
6451 mWindowManager.enableScreenAfterBoot();
6452 updateEventDispatchingLocked(booted);
6453 }
6454 }
6455
6456 @Override
6457 public boolean showStrictModeViolationDialog() {
6458 synchronized (mGlobalLock) {
6459 return mShowDialogs && !mSleeping && !mShuttingDown;
6460 }
6461 }
6462
6463 @Override
6464 public void showSystemReadyErrorDialogsIfNeeded() {
6465 synchronized (mGlobalLock) {
6466 try {
6467 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6468 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6469 + " data partition or your device will be unstable.");
6470 mUiHandler.post(() -> {
6471 if (mShowDialogs) {
6472 AlertDialog d = new BaseErrorDialog(mUiContext);
6473 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6474 d.setCancelable(false);
6475 d.setTitle(mUiContext.getText(R.string.android_system_label));
6476 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6477 d.setButton(DialogInterface.BUTTON_POSITIVE,
6478 mUiContext.getText(R.string.ok),
6479 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6480 d.show();
6481 }
6482 });
6483 }
6484 } catch (RemoteException e) {
6485 }
6486
6487 if (!Build.isBuildConsistent()) {
6488 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6489 mUiHandler.post(() -> {
6490 if (mShowDialogs) {
6491 AlertDialog d = new BaseErrorDialog(mUiContext);
6492 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6493 d.setCancelable(false);
6494 d.setTitle(mUiContext.getText(R.string.android_system_label));
6495 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6496 d.setButton(DialogInterface.BUTTON_POSITIVE,
6497 mUiContext.getText(R.string.ok),
6498 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6499 d.show();
6500 }
6501 });
6502 }
6503 }
6504 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006505
6506 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006507 public void onProcessMapped(int pid, WindowProcessController proc) {
6508 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006509 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006510 }
6511 }
6512
6513 @Override
6514 public void onProcessUnMapped(int pid) {
6515 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006516 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006517 }
6518 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006519
6520 @Override
6521 public void onPackageDataCleared(String name) {
6522 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006523 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006524 mAppWarnings.onPackageDataCleared(name);
6525 }
6526 }
6527
6528 @Override
6529 public void onPackageUninstalled(String name) {
6530 synchronized (mGlobalLock) {
6531 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006532 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006533 }
6534 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006535
6536 @Override
6537 public void onPackageAdded(String name, boolean replacing) {
6538 synchronized (mGlobalLock) {
6539 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6540 }
6541 }
6542
6543 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006544 public void onPackageReplaced(ApplicationInfo aInfo) {
6545 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006546 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006547 }
6548 }
6549
6550 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6552 synchronized (mGlobalLock) {
6553 return compatibilityInfoForPackageLocked(ai);
6554 }
6555 }
6556
Yunfan Chen75157d72018-07-27 14:47:21 +09006557 /**
6558 * Set the corresponding display information for the process global configuration. To be
6559 * called when we need to show IME on a different display.
6560 *
6561 * @param pid The process id associated with the IME window.
6562 * @param displayId The ID of the display showing the IME.
6563 */
6564 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006565 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006566 // Don't update process-level configuration for Multi-Client IME process since other
6567 // IMEs on other displays will also receive this configuration change due to IME
6568 // services use the same application config/context.
6569 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006570
Yunfan Chen75157d72018-07-27 14:47:21 +09006571 if (pid == MY_PID || pid < 0) {
6572 if (DEBUG_CONFIGURATION) {
6573 Slog.w(TAG,
6574 "Trying to update display configuration for system/invalid process.");
6575 }
6576 return;
6577 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006578 synchronized (mGlobalLock) {
6579 final ActivityDisplay activityDisplay =
6580 mRootActivityContainer.getActivityDisplay(displayId);
6581 if (activityDisplay == null) {
6582 // Call might come when display is not yet added or has been removed.
6583 if (DEBUG_CONFIGURATION) {
6584 Slog.w(TAG, "Trying to update display configuration for non-existing "
6585 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006587 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006588 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006589 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006590 if (process == null) {
6591 if (DEBUG_CONFIGURATION) {
6592 Slog.w(TAG, "Trying to update display configuration for invalid "
6593 + "process, pid=" + pid);
6594 }
6595 return;
6596 }
6597 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6598 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006599 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006600
6601 @Override
6602 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6603 int requestCode, int resultCode, Intent data) {
6604 synchronized (mGlobalLock) {
6605 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006606 if (r != null && r.getActivityStack() != null) {
6607 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6608 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006609 }
6610 }
6611 }
6612
6613 @Override
6614 public void clearPendingResultForActivity(IBinder activityToken,
6615 WeakReference<PendingIntentRecord> pir) {
6616 synchronized (mGlobalLock) {
6617 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6618 if (r != null && r.pendingResults != null) {
6619 r.pendingResults.remove(pir);
6620 }
6621 }
6622 }
6623
6624 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006625 public ActivityTokens getTopActivityForTask(int taskId) {
6626 synchronized (mGlobalLock) {
6627 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6628 if (taskRecord == null) {
6629 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6630 + " Requested task not found");
6631 return null;
6632 }
6633 final ActivityRecord activity = taskRecord.getTopActivity();
6634 if (activity == null) {
6635 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6636 + " Requested activity not found");
6637 return null;
6638 }
6639 if (!activity.attachedToProcess()) {
6640 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6641 + activity);
6642 return null;
6643 }
6644 return new ActivityTokens(activity.appToken, activity.assistToken,
6645 activity.app.getThread());
6646 }
6647 }
6648
6649 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006650 public IIntentSender getIntentSender(int type, String packageName,
6651 int callingUid, int userId, IBinder token, String resultWho,
6652 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6653 Bundle bOptions) {
6654 synchronized (mGlobalLock) {
6655 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6656 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6657 }
6658 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006659
6660 @Override
6661 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6662 synchronized (mGlobalLock) {
6663 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6664 if (r == null) {
6665 return null;
6666 }
6667 if (r.mServiceConnectionsHolder == null) {
6668 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6669 ActivityTaskManagerService.this, r);
6670 }
6671
6672 return r.mServiceConnectionsHolder;
6673 }
6674 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006675
6676 @Override
6677 public Intent getHomeIntent() {
6678 synchronized (mGlobalLock) {
6679 return ActivityTaskManagerService.this.getHomeIntent();
6680 }
6681 }
6682
6683 @Override
6684 public boolean startHomeActivity(int userId, String reason) {
6685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006686 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006687 }
6688 }
6689
6690 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006691 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006692 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006693 synchronized (mGlobalLock) {
6694 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006695 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006696 }
Chilun8b1f1be2019-03-13 17:14:36 +08006697 }
6698
6699 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006700 public boolean startHomeOnAllDisplays(int userId, String reason) {
6701 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006702 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006703 }
6704 }
6705
Riddle Hsua0536432019-02-16 00:38:59 +08006706 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006707 @Override
6708 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006709 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006710 if (mFactoryTest == FACTORY_TEST_OFF) {
6711 return false;
6712 }
6713 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6714 && wpc.mName.equals(mTopComponent.getPackageName())) {
6715 return true;
6716 }
6717 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6718 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6719 }
6720 }
6721
6722 @Override
6723 public void updateTopComponentForFactoryTest() {
6724 synchronized (mGlobalLock) {
6725 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6726 return;
6727 }
6728 final ResolveInfo ri = mContext.getPackageManager()
6729 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6730 final CharSequence errorMsg;
6731 if (ri != null) {
6732 final ActivityInfo ai = ri.activityInfo;
6733 final ApplicationInfo app = ai.applicationInfo;
6734 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6735 mTopAction = Intent.ACTION_FACTORY_TEST;
6736 mTopData = null;
6737 mTopComponent = new ComponentName(app.packageName, ai.name);
6738 errorMsg = null;
6739 } else {
6740 errorMsg = mContext.getResources().getText(
6741 com.android.internal.R.string.factorytest_not_system);
6742 }
6743 } else {
6744 errorMsg = mContext.getResources().getText(
6745 com.android.internal.R.string.factorytest_no_action);
6746 }
6747 if (errorMsg == null) {
6748 return;
6749 }
6750
6751 mTopAction = null;
6752 mTopData = null;
6753 mTopComponent = null;
6754 mUiHandler.post(() -> {
6755 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6756 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006757 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006758 });
6759 }
6760 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761
Riddle Hsua0536432019-02-16 00:38:59 +08006762 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 @Override
6764 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6765 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006766 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006768 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006769
6770 wpc.clearRecentTasks();
6771 wpc.clearActivities();
6772
6773 if (wpc.isInstrumenting()) {
6774 finishInstrumentationCallback.run();
6775 }
6776
Jorim Jaggid0752812018-10-16 16:07:20 +02006777 if (!restarting && hasVisibleActivities) {
6778 mWindowManager.deferSurfaceLayout();
6779 try {
6780 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6781 // If there was nothing to resume, and we are not already restarting
6782 // this process, but there is a visible activity that is hosted by the
6783 // process...then make sure all visible activities are running, taking
6784 // care of restarting this process.
6785 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6786 !PRESERVE_WINDOWS);
6787 }
6788 } finally {
6789 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 }
6792 }
6793 }
6794
6795 @Override
6796 public void closeSystemDialogs(String reason) {
6797 enforceNotIsolatedCaller("closeSystemDialogs");
6798
6799 final int pid = Binder.getCallingPid();
6800 final int uid = Binder.getCallingUid();
6801 final long origId = Binder.clearCallingIdentity();
6802 try {
6803 synchronized (mGlobalLock) {
6804 // Only allow this from foreground processes, so that background
6805 // applications can't abuse it to prevent system UI from being shown.
6806 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006807 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006808 if (!proc.isPerceptible()) {
6809 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6810 + " from background process " + proc);
6811 return;
6812 }
6813 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 mWindowManager.closeSystemDialogs(reason);
6815
Wale Ogunwaled32da472018-11-16 07:19:28 -08006816 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006818 // Call into AM outside the synchronized block.
6819 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 } finally {
6821 Binder.restoreCallingIdentity(origId);
6822 }
6823 }
6824
6825 @Override
6826 public void cleanupDisabledPackageComponents(
6827 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6828 synchronized (mGlobalLock) {
6829 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006830 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006831 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006832 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 mStackSupervisor.scheduleIdleLocked();
6834 }
6835
6836 // Clean-up disabled tasks
6837 getRecentTasks().cleanupDisabledPackageTasksLocked(
6838 packageName, disabledClasses, userId);
6839 }
6840 }
6841
6842 @Override
6843 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6844 int userId) {
6845 synchronized (mGlobalLock) {
6846
6847 boolean didSomething =
6848 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006849 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 null, doit, evenPersistent, userId);
6851 return didSomething;
6852 }
6853 }
6854
6855 @Override
6856 public void resumeTopActivities(boolean scheduleIdle) {
6857 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006858 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 if (scheduleIdle) {
6860 mStackSupervisor.scheduleIdleLocked();
6861 }
6862 }
6863 }
6864
Riddle Hsua0536432019-02-16 00:38:59 +08006865 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 @Override
6867 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006868 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6870 }
6871 }
6872
Riddle Hsua0536432019-02-16 00:38:59 +08006873 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 @Override
6875 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006876 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006877 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 }
6879 }
6880
6881 @Override
6882 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6883 try {
6884 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6885 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6886 }
6887 } catch (RemoteException ex) {
6888 throw new SecurityException("Fail to check is caller a privileged app", ex);
6889 }
6890
6891 synchronized (mGlobalLock) {
6892 final long ident = Binder.clearCallingIdentity();
6893 try {
6894 if (mAmInternal.shouldConfirmCredentials(userId)) {
6895 if (mKeyguardController.isKeyguardLocked()) {
6896 // Showing launcher to avoid user entering credential twice.
6897 startHomeActivity(currentUserId, "notifyLockedProfile");
6898 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006899 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 }
6901 } finally {
6902 Binder.restoreCallingIdentity(ident);
6903 }
6904 }
6905 }
6906
6907 @Override
6908 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6909 mAmInternal.enforceCallingPermission(
6910 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6911
6912 synchronized (mGlobalLock) {
6913 final long ident = Binder.clearCallingIdentity();
6914 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006915 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6916 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006917 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6919 UserHandle.CURRENT);
6920 } finally {
6921 Binder.restoreCallingIdentity(ident);
6922 }
6923 }
6924 }
6925
6926 @Override
6927 public void writeActivitiesToProto(ProtoOutputStream proto) {
6928 synchronized (mGlobalLock) {
6929 // The output proto of "activity --proto activities"
6930 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006931 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006932 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6933 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 }
6935 }
6936
6937 @Override
6938 public void saveANRState(String reason) {
6939 synchronized (mGlobalLock) {
6940 final StringWriter sw = new StringWriter();
6941 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6942 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6943 if (reason != null) {
6944 pw.println(" Reason: " + reason);
6945 }
6946 pw.println();
6947 getActivityStartController().dump(pw, " ", null);
6948 pw.println();
6949 pw.println("-------------------------------------------------------------------------------");
6950 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6951 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6952 "" /* header */);
6953 pw.println();
6954 pw.close();
6955
6956 mLastANRState = sw.toString();
6957 }
6958 }
6959
6960 @Override
6961 public void clearSavedANRState() {
6962 synchronized (mGlobalLock) {
6963 mLastANRState = null;
6964 }
6965 }
6966
6967 @Override
6968 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6969 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6970 synchronized (mGlobalLock) {
6971 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6972 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6973 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6974 dumpLastANRLocked(pw);
6975 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6976 dumpLastANRTracesLocked(pw);
6977 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6978 dumpActivityStarterLocked(pw, dumpPackage);
6979 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6980 dumpActivityContainersLocked(pw);
6981 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6982 if (getRecentTasks() != null) {
6983 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6984 }
6985 }
6986 }
6987 }
6988
6989 @Override
6990 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6991 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6992 int wakefulness) {
6993 synchronized (mGlobalLock) {
6994 if (mHomeProcess != null && (dumpPackage == null
6995 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6996 if (needSep) {
6997 pw.println();
6998 needSep = false;
6999 }
7000 pw.println(" mHomeProcess: " + mHomeProcess);
7001 }
7002 if (mPreviousProcess != null && (dumpPackage == null
7003 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7004 if (needSep) {
7005 pw.println();
7006 needSep = false;
7007 }
7008 pw.println(" mPreviousProcess: " + mPreviousProcess);
7009 }
7010 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7011 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7012 StringBuilder sb = new StringBuilder(128);
7013 sb.append(" mPreviousProcessVisibleTime: ");
7014 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7015 pw.println(sb);
7016 }
7017 if (mHeavyWeightProcess != null && (dumpPackage == null
7018 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7019 if (needSep) {
7020 pw.println();
7021 needSep = false;
7022 }
7023 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7024 }
7025 if (dumpPackage == null) {
7026 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007027 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007028 }
7029 if (dumpAll) {
7030 if (dumpPackage == null) {
7031 pw.println(" mConfigWillChange: "
7032 + getTopDisplayFocusedStack().mConfigWillChange);
7033 }
7034 if (mCompatModePackages.getPackages().size() > 0) {
7035 boolean printed = false;
7036 for (Map.Entry<String, Integer> entry
7037 : mCompatModePackages.getPackages().entrySet()) {
7038 String pkg = entry.getKey();
7039 int mode = entry.getValue();
7040 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7041 continue;
7042 }
7043 if (!printed) {
7044 pw.println(" mScreenCompatPackages:");
7045 printed = true;
7046 }
7047 pw.println(" " + pkg + ": " + mode);
7048 }
7049 }
7050 }
7051
7052 if (dumpPackage == null) {
7053 pw.println(" mWakefulness="
7054 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007055 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007056 if (mRunningVoice != null) {
7057 pw.println(" mRunningVoice=" + mRunningVoice);
7058 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7059 }
7060 pw.println(" mSleeping=" + mSleeping);
7061 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7062 pw.println(" mVrController=" + mVrController);
7063 }
7064 if (mCurAppTimeTracker != null) {
7065 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7066 }
7067 if (mAllowAppSwitchUids.size() > 0) {
7068 boolean printed = false;
7069 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7070 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7071 for (int j = 0; j < types.size(); j++) {
7072 if (dumpPackage == null ||
7073 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7074 if (needSep) {
7075 pw.println();
7076 needSep = false;
7077 }
7078 if (!printed) {
7079 pw.println(" mAllowAppSwitchUids:");
7080 printed = true;
7081 }
7082 pw.print(" User ");
7083 pw.print(mAllowAppSwitchUids.keyAt(i));
7084 pw.print(": Type ");
7085 pw.print(types.keyAt(j));
7086 pw.print(" = ");
7087 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7088 pw.println();
7089 }
7090 }
7091 }
7092 }
7093 if (dumpPackage == null) {
7094 if (mController != null) {
7095 pw.println(" mController=" + mController
7096 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7097 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007098 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7099 pw.println(" mLaunchingActivityWakeLock="
7100 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 }
7102
7103 return needSep;
7104 }
7105 }
7106
7107 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007108 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7109 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 synchronized (mGlobalLock) {
7111 if (dumpPackage == null) {
7112 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7113 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007114 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7115 if (mRunningVoice != null) {
7116 final long vrToken = proto.start(
7117 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7118 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7119 mRunningVoice.toString());
7120 mVoiceWakeLock.writeToProto(
7121 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7122 proto.end(vrToken);
7123 }
7124 mVrController.writeToProto(proto,
7125 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 if (mController != null) {
7127 final long token = proto.start(CONTROLLER);
7128 proto.write(CONTROLLER, mController.toString());
7129 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7130 proto.end(token);
7131 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007132 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7133 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7134 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 }
7136
7137 if (mHomeProcess != null && (dumpPackage == null
7138 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007139 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141
7142 if (mPreviousProcess != null && (dumpPackage == null
7143 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007144 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7146 }
7147
7148 if (mHeavyWeightProcess != null && (dumpPackage == null
7149 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007150 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 for (Map.Entry<String, Integer> entry
7154 : mCompatModePackages.getPackages().entrySet()) {
7155 String pkg = entry.getKey();
7156 int mode = entry.getValue();
7157 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7158 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7159 proto.write(PACKAGE, pkg);
7160 proto.write(MODE, mode);
7161 proto.end(compatToken);
7162 }
7163 }
7164
7165 if (mCurAppTimeTracker != null) {
7166 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7167 }
7168
7169 }
7170 }
7171
7172 @Override
7173 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7174 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7175 boolean dumpFocusedStackOnly) {
7176 synchronized (mGlobalLock) {
7177 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7178 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7179 }
7180 }
7181
7182 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007183 public void dumpForOom(PrintWriter pw) {
7184 synchronized (mGlobalLock) {
7185 pw.println(" mHomeProcess: " + mHomeProcess);
7186 pw.println(" mPreviousProcess: " + mPreviousProcess);
7187 if (mHeavyWeightProcess != null) {
7188 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7189 }
7190 }
7191 }
7192
7193 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 public boolean canGcNow() {
7195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007196 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 }
7198 }
7199
Riddle Hsua0536432019-02-16 00:38:59 +08007200 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007201 @Override
7202 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007203 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007204 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007205 return top != null ? top.app : null;
7206 }
7207 }
7208
Riddle Hsua0536432019-02-16 00:38:59 +08007209 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 @Override
7211 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007212 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007213 if (mRootActivityContainer != null) {
7214 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 }
7216 }
7217 }
7218
7219 @Override
7220 public void scheduleDestroyAllActivities(String reason) {
7221 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007222 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224 }
7225
7226 @Override
7227 public void removeUser(int userId) {
7228 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007229 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 }
7231 }
7232
7233 @Override
7234 public boolean switchUser(int userId, UserState userState) {
7235 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007236 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 }
7238 }
7239
7240 @Override
7241 public void onHandleAppCrash(WindowProcessController wpc) {
7242 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007243 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007246
7247 @Override
7248 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7249 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007250 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007251 }
7252 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007253
Riddle Hsua0536432019-02-16 00:38:59 +08007254 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007255 @Override
7256 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007257 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007258 }
7259
Riddle Hsua0536432019-02-16 00:38:59 +08007260 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007261 @Override
7262 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007263 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007264 }
7265
Riddle Hsua0536432019-02-16 00:38:59 +08007266 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007267 @Override
7268 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007269 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007270 }
7271
Riddle Hsua0536432019-02-16 00:38:59 +08007272 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007273 @Override
7274 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007275 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007276 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007277
7278 @Override
7279 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007280 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007281 mPendingTempWhitelist.put(uid, tag);
7282 }
7283 }
7284
7285 @Override
7286 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007287 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007288 mPendingTempWhitelist.remove(uid);
7289 }
7290 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007291
7292 @Override
7293 public boolean handleAppCrashInActivityController(String processName, int pid,
7294 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7295 Runnable killCrashingAppCallback) {
7296 synchronized (mGlobalLock) {
7297 if (mController == null) {
7298 return false;
7299 }
7300
7301 try {
7302 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7303 stackTrace)) {
7304 killCrashingAppCallback.run();
7305 return true;
7306 }
7307 } catch (RemoteException e) {
7308 mController = null;
7309 Watchdog.getInstance().setActivityController(null);
7310 }
7311 return false;
7312 }
7313 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007314
7315 @Override
7316 public void removeRecentTasksByPackageName(String packageName, int userId) {
7317 synchronized (mGlobalLock) {
7318 mRecentTasks.removeTasksByPackageName(packageName, userId);
7319 }
7320 }
7321
7322 @Override
7323 public void cleanupRecentTasksForUser(int userId) {
7324 synchronized (mGlobalLock) {
7325 mRecentTasks.cleanupLocked(userId);
7326 }
7327 }
7328
7329 @Override
7330 public void loadRecentTasksForUser(int userId) {
7331 synchronized (mGlobalLock) {
7332 mRecentTasks.loadUserRecentsLocked(userId);
7333 }
7334 }
7335
7336 @Override
7337 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7338 synchronized (mGlobalLock) {
7339 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7340 }
7341 }
7342
7343 @Override
7344 public void flushRecentTasks() {
7345 mRecentTasks.flush();
7346 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007347
7348 @Override
7349 public WindowProcessController getHomeProcess() {
7350 synchronized (mGlobalLock) {
7351 return mHomeProcess;
7352 }
7353 }
7354
7355 @Override
7356 public WindowProcessController getPreviousProcess() {
7357 synchronized (mGlobalLock) {
7358 return mPreviousProcess;
7359 }
7360 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007361
7362 @Override
7363 public void clearLockedTasks(String reason) {
7364 synchronized (mGlobalLock) {
7365 getLockTaskController().clearLockedTasks(reason);
7366 }
7367 }
7368
7369 @Override
7370 public void updateUserConfiguration() {
7371 synchronized (mGlobalLock) {
7372 final Configuration configuration = new Configuration(getGlobalConfiguration());
7373 final int currentUserId = mAmInternal.getCurrentUserId();
7374 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7375 configuration, currentUserId, Settings.System.canWrite(mContext));
7376 updateConfigurationLocked(configuration, null /* starting */,
7377 false /* initLocale */, false /* persistent */, currentUserId,
7378 false /* deferResume */);
7379 }
7380 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007381
7382 @Override
7383 public boolean canShowErrorDialogs() {
7384 synchronized (mGlobalLock) {
7385 return mShowDialogs && !mSleeping && !mShuttingDown
7386 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7387 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7388 mAmInternal.getCurrentUserId())
7389 && !(UserManager.isDeviceInDemoMode(mContext)
7390 && mAmInternal.getCurrentUser().isDemo());
7391 }
7392 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007393
7394 @Override
7395 public void setProfileApp(String profileApp) {
7396 synchronized (mGlobalLock) {
7397 mProfileApp = profileApp;
7398 }
7399 }
7400
7401 @Override
7402 public void setProfileProc(WindowProcessController wpc) {
7403 synchronized (mGlobalLock) {
7404 mProfileProc = wpc;
7405 }
7406 }
7407
7408 @Override
7409 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7410 synchronized (mGlobalLock) {
7411 mProfilerInfo = profilerInfo;
7412 }
7413 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007414
7415 @Override
7416 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7417 synchronized (mGlobalLock) {
7418 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7419 }
7420 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007421
7422 @Override
7423 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7424 synchronized (mGlobalLock) {
7425 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7426 }
7427 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007428
7429 @Override
7430 public boolean isUidForeground(int uid) {
7431 synchronized (mGlobalLock) {
7432 return ActivityTaskManagerService.this.isUidForeground(uid);
7433 }
7434 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007435
7436 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007437 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007438 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007439 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007440 }
7441 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007442
7443 @Override
7444 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007445 // Translate package names into UIDs
7446 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007447 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007448 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7449 if (uid >= 0) {
7450 result.add(uid);
7451 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007452 }
7453 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007454 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007455 }
7456 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007457 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007458}