blob: 747837bc933fbc608dade92ce235490e1edccc41 [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
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001037 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 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
Riddle Hsu609a8e22019-06-27 16:46:29 -06001454 /**
1455 * Start the recents activity to perform the recents animation.
1456 *
1457 * @param intent The intent to start the recents activity.
1458 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1459 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001461 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1462 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001465 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 final long origId = Binder.clearCallingIdentity();
1467 try {
1468 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001469 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1470 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001471 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472
1473 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001474 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001475 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001476 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001477 if (recentsAnimationRunner == null) {
1478 anim.preloadRecentsActivity();
1479 } else {
1480 anim.startRecentsActivity(recentsAnimationRunner);
1481 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 }
1483 } finally {
1484 Binder.restoreCallingIdentity(origId);
1485 }
1486 }
1487
1488 @Override
1489 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001490 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 "startActivityFromRecents()");
1492
1493 final int callingPid = Binder.getCallingPid();
1494 final int callingUid = Binder.getCallingUid();
1495 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1496 final long origId = Binder.clearCallingIdentity();
1497 try {
1498 synchronized (mGlobalLock) {
1499 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1500 safeOptions);
1501 }
1502 } finally {
1503 Binder.restoreCallingIdentity(origId);
1504 }
1505 }
1506
1507 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001508 * Public API to check if the client is allowed to start an activity on specified display.
1509 *
1510 * If the target display is private or virtual, some restrictions will apply.
1511 *
1512 * @param displayId Target display id.
1513 * @param intent Intent used to launch the activity.
1514 * @param resolvedType The MIME type of the intent.
1515 * @param userId The id of the user for whom the call is made.
1516 * @return {@code true} if a call to start an activity on the target display should succeed and
1517 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1518 */
1519 @Override
1520 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1521 String resolvedType, int userId) {
1522 final int callingUid = Binder.getCallingUid();
1523 final int callingPid = Binder.getCallingPid();
1524 final long origId = Binder.clearCallingIdentity();
1525
1526 try {
1527 // Collect information about the target of the Intent.
1528 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1529 0 /* startFlags */, null /* profilerInfo */, userId,
1530 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1531 UserHandle.USER_NULL));
1532 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1533
1534 synchronized (mGlobalLock) {
1535 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1536 aInfo);
1537 }
1538 } finally {
1539 Binder.restoreCallingIdentity(origId);
1540 }
1541 }
1542
1543 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001544 * This is the internal entry point for handling Activity.finish().
1545 *
1546 * @param token The Binder token referencing the Activity we want to finish.
1547 * @param resultCode Result code, if any, from this Activity.
1548 * @param resultData Result data (Intent), if any, from this Activity.
1549 * @param finishTask Whether to finish the task associated with this Activity.
1550 *
1551 * @return Returns true if the activity successfully finished, or false if it is still running.
1552 */
1553 @Override
1554 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1555 int finishTask) {
1556 // Refuse possible leaked file descriptors
1557 if (resultData != null && resultData.hasFileDescriptors()) {
1558 throw new IllegalArgumentException("File descriptors passed in Intent");
1559 }
1560
1561 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001562 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 if (r == null) {
1564 return true;
1565 }
1566 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001567 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 ActivityRecord rootR = tr.getRootActivity();
1569 if (rootR == null) {
1570 Slog.w(TAG, "Finishing task with all activities already finished");
1571 }
1572 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1573 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001574 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 return false;
1576 }
1577
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001578 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1579 // We should consolidate.
1580 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001582 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 if (next != null) {
1584 // ask watcher if this is allowed
1585 boolean resumeOK = true;
1586 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001587 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001589 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 Watchdog.getInstance().setActivityController(null);
1591 }
1592
1593 if (!resumeOK) {
1594 Slog.i(TAG, "Not finishing activity because controller resumed");
1595 return false;
1596 }
1597 }
1598 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001599
1600 // note down that the process has finished an activity and is in background activity
1601 // starts grace period
1602 if (r.app != null) {
1603 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1604 }
1605
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 final long origId = Binder.clearCallingIdentity();
1607 try {
1608 boolean res;
1609 final boolean finishWithRootActivity =
1610 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1611 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1612 || (finishWithRootActivity && r == rootR)) {
1613 // If requested, remove the task that is associated to this activity only if it
1614 // was the root activity in the task. The result code and data is ignored
1615 // because we don't support returning them across task boundaries. Also, to
1616 // keep backwards compatibility we remove the task from recents when finishing
1617 // task with root activity.
1618 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1619 finishWithRootActivity, "finish-activity");
1620 if (!res) {
1621 Slog.i(TAG, "Removing task failed to finish activity");
1622 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001623 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001624 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 } else {
1626 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001627 resultData, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 if (!res) {
1629 Slog.i(TAG, "Failed to finish by app-request");
1630 }
1631 }
1632 return res;
1633 } finally {
1634 Binder.restoreCallingIdentity(origId);
1635 }
1636 }
1637 }
1638
1639 @Override
1640 public boolean finishActivityAffinity(IBinder token) {
1641 synchronized (mGlobalLock) {
1642 final long origId = Binder.clearCallingIdentity();
1643 try {
1644 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1645 if (r == null) {
1646 return false;
1647 }
1648
1649 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1650 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001651 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001652 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 return false;
1654 }
1655 return task.getStack().finishActivityAffinityLocked(r);
1656 } finally {
1657 Binder.restoreCallingIdentity(origId);
1658 }
1659 }
1660 }
1661
1662 @Override
1663 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1664 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001665 try {
1666 WindowProcessController proc = null;
1667 synchronized (mGlobalLock) {
1668 ActivityStack stack = ActivityRecord.getStackLocked(token);
1669 if (stack == null) {
1670 return;
1671 }
1672 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1673 false /* fromTimeout */, false /* processPausingActivities */, config);
1674 if (r != null) {
1675 proc = r.app;
1676 }
1677 if (stopProfiling && proc != null) {
1678 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 }
1680 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001681 } finally {
1682 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685
1686 @Override
1687 public final void activityResumed(IBinder token) {
1688 final long origId = Binder.clearCallingIdentity();
1689 synchronized (mGlobalLock) {
1690 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001691 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 }
1693 Binder.restoreCallingIdentity(origId);
1694 }
1695
1696 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001697 public final void activityTopResumedStateLost() {
1698 final long origId = Binder.clearCallingIdentity();
1699 synchronized (mGlobalLock) {
1700 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1701 }
1702 Binder.restoreCallingIdentity(origId);
1703 }
1704
1705 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 public final void activityPaused(IBinder token) {
1707 final long origId = Binder.clearCallingIdentity();
1708 synchronized (mGlobalLock) {
1709 ActivityStack stack = ActivityRecord.getStackLocked(token);
1710 if (stack != null) {
1711 stack.activityPausedLocked(token, false);
1712 }
1713 }
1714 Binder.restoreCallingIdentity(origId);
1715 }
1716
1717 @Override
1718 public final void activityStopped(IBinder token, Bundle icicle,
1719 PersistableBundle persistentState, CharSequence description) {
1720 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1721
1722 // Refuse possible leaked file descriptors
1723 if (icicle != null && icicle.hasFileDescriptors()) {
1724 throw new IllegalArgumentException("File descriptors passed in Bundle");
1725 }
1726
1727 final long origId = Binder.clearCallingIdentity();
1728
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001729 String restartingName = null;
1730 int restartingUid = 0;
1731 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001733 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001735 if (r.attachedToProcess()
1736 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1737 // The activity was requested to restart from
1738 // {@link #restartActivityProcessIfVisible}.
1739 restartingName = r.app.mName;
1740 restartingUid = r.app.mUid;
1741 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 r.activityStoppedLocked(icicle, persistentState, description);
1743 }
1744 }
1745
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001746 if (restartingName != null) {
1747 // In order to let the foreground activity can be restarted with its saved state from
1748 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1749 // until the activity reports stopped with the state. And the activity record will be
1750 // kept because the record state is restarting, then the activity will be restarted
1751 // immediately if it is still the top one.
1752 mStackSupervisor.removeRestartTimeouts(r);
1753 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1754 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001755 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756
1757 Binder.restoreCallingIdentity(origId);
1758 }
1759
1760 @Override
1761 public final void activityDestroyed(IBinder token) {
1762 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1763 synchronized (mGlobalLock) {
1764 ActivityStack stack = ActivityRecord.getStackLocked(token);
1765 if (stack != null) {
1766 stack.activityDestroyedLocked(token, "activityDestroyed");
1767 }
1768 }
1769 }
1770
1771 @Override
1772 public final void activityRelaunched(IBinder token) {
1773 final long origId = Binder.clearCallingIdentity();
1774 synchronized (mGlobalLock) {
1775 mStackSupervisor.activityRelaunchedLocked(token);
1776 }
1777 Binder.restoreCallingIdentity(origId);
1778 }
1779
1780 public final void activitySlept(IBinder token) {
1781 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1782
1783 final long origId = Binder.clearCallingIdentity();
1784
1785 synchronized (mGlobalLock) {
1786 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r != null) {
1788 mStackSupervisor.activitySleptLocked(r);
1789 }
1790 }
1791
1792 Binder.restoreCallingIdentity(origId);
1793 }
1794
1795 @Override
1796 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1797 synchronized (mGlobalLock) {
1798 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1799 if (r == null) {
1800 return;
1801 }
1802 final long origId = Binder.clearCallingIdentity();
1803 try {
1804 r.setRequestedOrientation(requestedOrientation);
1805 } finally {
1806 Binder.restoreCallingIdentity(origId);
1807 }
1808 }
1809 }
1810
1811 @Override
1812 public int getRequestedOrientation(IBinder token) {
1813 synchronized (mGlobalLock) {
1814 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1815 if (r == null) {
1816 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1817 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001818 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 }
1820 }
1821
1822 @Override
1823 public void setImmersive(IBinder token, boolean immersive) {
1824 synchronized (mGlobalLock) {
1825 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1826 if (r == null) {
1827 throw new IllegalArgumentException();
1828 }
1829 r.immersive = immersive;
1830
1831 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001832 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001834 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 }
1836 }
1837 }
1838
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 void applyUpdateLockStateLocked(ActivityRecord r) {
1840 // Modifications to the UpdateLock state are done on our handler, outside
1841 // the activity manager's locks. The new state is determined based on the
1842 // state *now* of the relevant activity record. The object is passed to
1843 // the handler solely for logging detail, not to be consulted/modified.
1844 final boolean nextState = r != null && r.immersive;
1845 mH.post(() -> {
1846 if (mUpdateLock.isHeld() != nextState) {
1847 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1848 "Applying new update lock state '" + nextState + "' for " + r);
1849 if (nextState) {
1850 mUpdateLock.acquire();
1851 } else {
1852 mUpdateLock.release();
1853 }
1854 }
1855 });
1856 }
1857
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 @Override
1859 public boolean isImmersive(IBinder token) {
1860 synchronized (mGlobalLock) {
1861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1862 if (r == null) {
1863 throw new IllegalArgumentException();
1864 }
1865 return r.immersive;
1866 }
1867 }
1868
1869 @Override
1870 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001873 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 return (r != null) ? r.immersive : false;
1875 }
1876 }
1877
1878 @Override
1879 public void overridePendingTransition(IBinder token, String packageName,
1880 int enterAnim, int exitAnim) {
1881 synchronized (mGlobalLock) {
1882 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1883 if (self == null) {
1884 return;
1885 }
1886
1887 final long origId = Binder.clearCallingIdentity();
1888
1889 if (self.isState(
1890 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001891 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001892 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001903 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 if (r == null) {
1905 return ActivityManager.COMPAT_MODE_UNKNOWN;
1906 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001907 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001908 }
1909 }
1910
1911 @Override
1912 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001913 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001917 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 if (r == null) {
1919 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1920 return;
1921 }
1922 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001923 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 }
1925 }
1926
1927 @Override
1928 public int getLaunchedFromUid(IBinder activityToken) {
1929 ActivityRecord srec;
1930 synchronized (mGlobalLock) {
1931 srec = ActivityRecord.forTokenLocked(activityToken);
1932 }
1933 if (srec == null) {
1934 return -1;
1935 }
1936 return srec.launchedFromUid;
1937 }
1938
1939 @Override
1940 public String getLaunchedFromPackage(IBinder activityToken) {
1941 ActivityRecord srec;
1942 synchronized (mGlobalLock) {
1943 srec = ActivityRecord.forTokenLocked(activityToken);
1944 }
1945 if (srec == null) {
1946 return null;
1947 }
1948 return srec.launchedFromPackage;
1949 }
1950
1951 @Override
1952 public boolean convertFromTranslucent(IBinder token) {
1953 final long origId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
1956 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1957 if (r == null) {
1958 return false;
1959 }
1960 final boolean translucentChanged = r.changeWindowTranslucency(true);
1961 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001962 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001964 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 return translucentChanged;
1966 }
1967 } finally {
1968 Binder.restoreCallingIdentity(origId);
1969 }
1970 }
1971
1972 @Override
1973 public boolean convertToTranslucent(IBinder token, Bundle options) {
1974 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1975 final long origId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
1978 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1979 if (r == null) {
1980 return false;
1981 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001982 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 int index = task.mActivities.lastIndexOf(r);
1984 if (index > 0) {
1985 ActivityRecord under = task.mActivities.get(index - 1);
1986 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1987 }
1988 final boolean translucentChanged = r.changeWindowTranslucency(false);
1989 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001990 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001992 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001993 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 return translucentChanged;
1995 }
1996 } finally {
1997 Binder.restoreCallingIdentity(origId);
1998 }
1999 }
2000
2001 @Override
2002 public void notifyActivityDrawn(IBinder token) {
2003 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2004 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002005 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002007 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 }
2009 }
2010 }
2011
2012 @Override
2013 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2014 synchronized (mGlobalLock) {
2015 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2016 if (r == null) {
2017 return;
2018 }
2019 r.reportFullyDrawnLocked(restoredFromBundle);
2020 }
2021 }
2022
2023 @Override
2024 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2025 synchronized (mGlobalLock) {
2026 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2027 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2028 return stack.mDisplayId;
2029 }
2030 return DEFAULT_DISPLAY;
2031 }
2032 }
2033
2034 @Override
2035 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002036 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 long ident = Binder.clearCallingIdentity();
2038 try {
2039 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002040 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002041 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002042 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 }
2044 return null;
2045 }
2046 } finally {
2047 Binder.restoreCallingIdentity(ident);
2048 }
2049 }
2050
2051 @Override
2052 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002053 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2055 final long callingId = Binder.clearCallingIdentity();
2056 try {
2057 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002058 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 if (stack == null) {
2060 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2061 return;
2062 }
2063 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002064 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002065 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 }
2067 }
2068 } finally {
2069 Binder.restoreCallingIdentity(callingId);
2070 }
2071 }
2072
2073 @Override
2074 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002075 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2077 final long callingId = Binder.clearCallingIdentity();
2078 try {
2079 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002080 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002081 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002082 if (task == null) {
2083 return;
2084 }
2085 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002086 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002087 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002088 }
2089 }
2090 } finally {
2091 Binder.restoreCallingIdentity(callingId);
2092 }
2093 }
2094
2095 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002096 public void restartActivityProcessIfVisible(IBinder activityToken) {
2097 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2098 final long callingId = Binder.clearCallingIdentity();
2099 try {
2100 synchronized (mGlobalLock) {
2101 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2102 if (r == null) {
2103 return;
2104 }
2105 r.restartProcessIfVisible();
2106 }
2107 } finally {
2108 Binder.restoreCallingIdentity(callingId);
2109 }
2110 }
2111
2112 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002114 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 synchronized (mGlobalLock) {
2116 final long ident = Binder.clearCallingIdentity();
2117 try {
2118 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2119 "remove-task");
2120 } finally {
2121 Binder.restoreCallingIdentity(ident);
2122 }
2123 }
2124 }
2125
2126 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002127 public void removeAllVisibleRecentTasks() {
2128 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2129 synchronized (mGlobalLock) {
2130 final long ident = Binder.clearCallingIdentity();
2131 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002132 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002133 } finally {
2134 Binder.restoreCallingIdentity(ident);
2135 }
2136 }
2137 }
2138
2139 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2141 synchronized (mGlobalLock) {
2142 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2143 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002144 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 }
2146 }
2147 return false;
2148 }
2149
2150 @Override
2151 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2152 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002153
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002154 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002155 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2156 if (r != null) {
2157 return r.getActivityStack().navigateUpToLocked(
2158 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002159 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002160 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 }
2162 }
2163
2164 /**
2165 * Attempts to move a task backwards in z-order (the order of activities within the task is
2166 * unchanged).
2167 *
2168 * There are several possible results of this call:
2169 * - if the task is locked, then we will show the lock toast
2170 * - if there is a task behind the provided task, then that task is made visible and resumed as
2171 * this task is moved to the back
2172 * - otherwise, if there are no other tasks in the stack:
2173 * - if this task is in the pinned stack, then we remove the stack completely, which will
2174 * have the effect of moving the task to the top or bottom of the fullscreen stack
2175 * (depending on whether it is visible)
2176 * - otherwise, we simply return home and hide this task
2177 *
2178 * @param token A reference to the activity we wish to move
2179 * @param nonRoot If false then this only works if the activity is the root
2180 * of a task; if true it will work for any activity in a task.
2181 * @return Returns true if the move completed, false if not.
2182 */
2183 @Override
2184 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002185 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 synchronized (mGlobalLock) {
2187 final long origId = Binder.clearCallingIdentity();
2188 try {
2189 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002190 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 if (task != null) {
2192 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(origId);
2196 }
2197 }
2198 return false;
2199 }
2200
2201 @Override
2202 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002203 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 long ident = Binder.clearCallingIdentity();
2205 Rect rect = new Rect();
2206 try {
2207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002208 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2210 if (task == null) {
2211 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2212 return rect;
2213 }
2214 if (task.getStack() != null) {
2215 // Return the bounds from window manager since it will be adjusted for various
2216 // things like the presense of a docked stack for tasks that aren't resizeable.
2217 task.getWindowContainerBounds(rect);
2218 } else {
2219 // Task isn't in window manager yet since it isn't associated with a stack.
2220 // Return the persist value from activity manager
2221 if (!task.matchParentBounds()) {
2222 rect.set(task.getBounds());
2223 } else if (task.mLastNonFullscreenBounds != null) {
2224 rect.set(task.mLastNonFullscreenBounds);
2225 }
2226 }
2227 }
2228 } finally {
2229 Binder.restoreCallingIdentity(ident);
2230 }
2231 return rect;
2232 }
2233
2234 @Override
2235 public ActivityManager.TaskDescription getTaskDescription(int id) {
2236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002237 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002239 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2241 if (tr != null) {
2242 return tr.lastTaskDescription;
2243 }
2244 }
2245 return null;
2246 }
2247
2248 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2250 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2251 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2252 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2253 return;
2254 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002255 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002256 synchronized (mGlobalLock) {
2257 final long ident = Binder.clearCallingIdentity();
2258 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002259 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002260 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002261 if (task == null) {
2262 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2263 return;
2264 }
2265
2266 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2267 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2268
2269 if (!task.isActivityTypeStandardOrUndefined()) {
2270 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2271 + " non-standard task " + taskId + " to windowing mode="
2272 + windowingMode);
2273 }
2274
2275 final ActivityStack stack = task.getStack();
2276 if (toTop) {
2277 stack.moveToFront("setTaskWindowingMode", task);
2278 }
2279 stack.setWindowingMode(windowingMode);
2280 } finally {
2281 Binder.restoreCallingIdentity(ident);
2282 }
2283 }
2284 }
2285
2286 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002287 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002288 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 ActivityRecord r = getCallingRecordLocked(token);
2290 return r != null ? r.info.packageName : null;
2291 }
2292 }
2293
2294 @Override
2295 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 ActivityRecord r = getCallingRecordLocked(token);
2298 return r != null ? r.intent.getComponent() : null;
2299 }
2300 }
2301
2302 private ActivityRecord getCallingRecordLocked(IBinder token) {
2303 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2304 if (r == null) {
2305 return null;
2306 }
2307 return r.resultTo;
2308 }
2309
2310 @Override
2311 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002312 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313
2314 synchronized (mGlobalLock) {
2315 final long origId = Binder.clearCallingIdentity();
2316 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002317 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 } finally {
2319 Binder.restoreCallingIdentity(origId);
2320 }
2321 }
2322 }
2323
Mark Renouf446251d2019-04-26 10:22:41 -04002324 @Override
2325 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2326 synchronized (mGlobalLock) {
2327 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2328 if (r == null) {
2329 return;
2330 }
2331 ActivityStack stack = r.getActivityStack();
2332 if (stack != null && stack.isSingleTaskInstance()) {
2333 // Single-task stacks are used for activities which are presented in floating
2334 // windows above full screen activities. Instead of directly finishing the
2335 // task, a task change listener is used to notify SystemUI so the action can be
2336 // handled specially.
2337 final TaskRecord task = r.getTaskRecord();
2338 mTaskChangeNotificationController
2339 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2340 } else {
2341 try {
2342 callback.requestFinish();
2343 } catch (RemoteException e) {
2344 Slog.e(TAG, "Failed to invoke request finish callback", e);
2345 }
2346 }
2347 }
2348 }
2349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 /**
2351 * TODO: Add mController hook
2352 */
2353 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2355 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002356 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357
2358 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2359 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2361 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002362 }
2363 }
2364
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2366 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002368
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 final int callingPid = Binder.getCallingPid();
2370 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002371 if (!isSameApp(callingUid, callingPackage)) {
2372 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2373 + Binder.getCallingPid() + " as package " + callingPackage;
2374 Slog.w(TAG, msg);
2375 throw new SecurityException(msg);
2376 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 SafeActivityOptions.abort(options);
2379 return;
2380 }
2381 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002382 WindowProcessController callerApp = null;
2383 if (appThread != null) {
2384 callerApp = getProcessController(appThread);
2385 }
2386 final ActivityStarter starter = getActivityStartController().obtainStarter(
2387 null /* intent */, "moveTaskToFront");
2388 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2389 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002390 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 return;
2392 }
2393 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002395 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 if (task == null) {
2397 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002398 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 return;
2400 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002401 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002403 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 return;
2405 }
2406 ActivityOptions realOptions = options != null
2407 ? options.getOptions(mStackSupervisor)
2408 : null;
2409 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2410 false /* forceNonResizable */);
2411
2412 final ActivityRecord topActivity = task.getTopActivity();
2413 if (topActivity != null) {
2414
2415 // We are reshowing a task, use a starting window to hide the initial draw delay
2416 // so the transition can start earlier.
2417 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2418 true /* taskSwitch */, fromRecents);
2419 }
2420 } finally {
2421 Binder.restoreCallingIdentity(origId);
2422 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423 }
2424
Ricky Waiaca8a772019-04-04 16:01:06 +01002425 /**
2426 * Return true if callingUid is system, or packageName belongs to that callingUid.
2427 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002428 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002429 try {
2430 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2431 if (packageName == null) {
2432 return false;
2433 }
2434 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2435 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2436 UserHandle.getUserId(callingUid));
2437 return UserHandle.isSameApp(callingUid, uid);
2438 }
2439 } catch (RemoteException e) {
2440 // Should not happen
2441 }
2442 return true;
2443 }
2444
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002445 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2446 int callingPid, int callingUid, String name) {
2447 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2448 return true;
2449 }
2450
2451 if (getRecentTasks().isCallerRecents(sourceUid)) {
2452 return true;
2453 }
2454
2455 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2456 if (perm == PackageManager.PERMISSION_GRANTED) {
2457 return true;
2458 }
2459 if (checkAllowAppSwitchUid(sourceUid)) {
2460 return true;
2461 }
2462
2463 // If the actual IPC caller is different from the logical source, then
2464 // also see if they are allowed to control app switches.
2465 if (callingUid != -1 && callingUid != sourceUid) {
2466 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(callingUid)) {
2471 return true;
2472 }
2473 }
2474
2475 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2476 return false;
2477 }
2478
2479 private boolean checkAllowAppSwitchUid(int uid) {
2480 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2481 if (types != null) {
2482 for (int i = types.size() - 1; i >= 0; i--) {
2483 if (types.valueAt(i).intValue() == uid) {
2484 return true;
2485 }
2486 }
2487 }
2488 return false;
2489 }
2490
2491 @Override
2492 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2493 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2494 "setActivityController()");
2495 synchronized (mGlobalLock) {
2496 mController = controller;
2497 mControllerIsAMonkey = imAMonkey;
2498 Watchdog.getInstance().setActivityController(controller);
2499 }
2500 }
2501
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002502 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002503 synchronized (mGlobalLock) {
2504 return mController != null && mControllerIsAMonkey;
2505 }
2506 }
2507
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002508 @Override
2509 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2510 synchronized (mGlobalLock) {
2511 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2512 }
2513 }
2514
2515 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002516 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2517 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2518 }
2519
2520 @Override
2521 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2522 @WindowConfiguration.ActivityType int ignoreActivityType,
2523 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2524 final int callingUid = Binder.getCallingUid();
2525 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2526
2527 synchronized (mGlobalLock) {
2528 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2529
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002530 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002531 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002532 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002533 ignoreWindowingMode, callingUid, allowed);
2534 }
2535
2536 return list;
2537 }
2538
2539 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2541 synchronized (mGlobalLock) {
2542 final long origId = Binder.clearCallingIdentity();
2543 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2544 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002545 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 }
2547 Binder.restoreCallingIdentity(origId);
2548 }
2549 }
2550
2551 @Override
2552 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002553 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 ActivityStack stack = ActivityRecord.getStackLocked(token);
2555 if (stack != null) {
2556 return stack.willActivityBeVisibleLocked(token);
2557 }
2558 return false;
2559 }
2560 }
2561
2562 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002564 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 synchronized (mGlobalLock) {
2566 final long ident = Binder.clearCallingIdentity();
2567 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002568 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002569 if (task == null) {
2570 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2571 return;
2572 }
2573
2574 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2575 + " to stackId=" + stackId + " toTop=" + toTop);
2576
Wale Ogunwaled32da472018-11-16 07:19:28 -08002577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 if (stack == null) {
2579 throw new IllegalStateException(
2580 "moveTaskToStack: No stack for stackId=" + stackId);
2581 }
2582 if (!stack.isActivityTypeStandardOrUndefined()) {
2583 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2584 + taskId + " to stack " + stackId);
2585 }
2586 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002587 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2589 }
2590 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2591 "moveTaskToStack");
2592 } finally {
2593 Binder.restoreCallingIdentity(ident);
2594 }
2595 }
2596 }
2597
2598 @Override
2599 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2600 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002601 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602
2603 final long ident = Binder.clearCallingIdentity();
2604 try {
2605 synchronized (mGlobalLock) {
2606 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002607 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 if (stack == null) {
2609 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2610 return;
2611 }
2612 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2613 throw new IllegalArgumentException("Stack: " + stackId
2614 + " doesn't support animated resize.");
2615 }
2616 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2617 animationDuration, false /* fromFullscreen */);
2618 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002620 if (stack == null) {
2621 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2622 return;
2623 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002624 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002625 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2626 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2627 }
2628 }
2629 } finally {
2630 Binder.restoreCallingIdentity(ident);
2631 }
2632 }
2633
wilsonshih5c4cf522019-01-25 09:03:47 +08002634 @Override
2635 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2636 int animationDuration) {
2637 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2638
2639 final long ident = Binder.clearCallingIdentity();
2640 try {
2641 synchronized (mGlobalLock) {
2642 if (xOffset == 0 && yOffset == 0) {
2643 return;
2644 }
2645 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2646 if (stack == null) {
2647 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2648 return;
2649 }
2650 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2651 throw new IllegalArgumentException("Stack: " + stackId
2652 + " doesn't support animated resize.");
2653 }
2654 final Rect destBounds = new Rect();
2655 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002656 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002657 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2658 return;
2659 }
2660 destBounds.offset(xOffset, yOffset);
2661 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2662 animationDuration, false /* fromFullscreen */);
2663 }
2664 } finally {
2665 Binder.restoreCallingIdentity(ident);
2666 }
2667 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 /**
2669 * Moves the specified task to the primary-split-screen stack.
2670 *
2671 * @param taskId Id of task to move.
2672 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2673 * exist already. See
2674 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2675 * and
2676 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2677 * @param toTop If the task and stack should be moved to the top.
2678 * @param animate Whether we should play an animation for the moving the task.
2679 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2680 * stack. Pass {@code null} to use default bounds.
2681 * @param showRecents If the recents activity should be shown on the other side of the task
2682 * going into split-screen mode.
2683 */
2684 @Override
2685 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2686 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002687 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 "setTaskWindowingModeSplitScreenPrimary()");
2689 synchronized (mGlobalLock) {
2690 final long ident = Binder.clearCallingIdentity();
2691 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002692 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002693 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002694 if (task == null) {
2695 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2696 return false;
2697 }
2698 if (DEBUG_STACK) Slog.d(TAG_STACK,
2699 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2700 + " to createMode=" + createMode + " toTop=" + toTop);
2701 if (!task.isActivityTypeStandardOrUndefined()) {
2702 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2703 + " non-standard task " + taskId + " to split-screen windowing mode");
2704 }
2705
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002706 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 final int windowingMode = task.getWindowingMode();
2708 final ActivityStack stack = task.getStack();
2709 if (toTop) {
2710 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2711 }
2712 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002713 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2714 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 return windowingMode != task.getWindowingMode();
2716 } finally {
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720 }
2721
2722 /**
2723 * Removes stacks in the input windowing modes from the system if they are of activity type
2724 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2725 */
2726 @Override
2727 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002728 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002729 "removeStacksInWindowingModes()");
2730
2731 synchronized (mGlobalLock) {
2732 final long ident = Binder.clearCallingIdentity();
2733 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002734 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002735 } finally {
2736 Binder.restoreCallingIdentity(ident);
2737 }
2738 }
2739 }
2740
2741 @Override
2742 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002743 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002744 "removeStacksWithActivityTypes()");
2745
2746 synchronized (mGlobalLock) {
2747 final long ident = Binder.clearCallingIdentity();
2748 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002749 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755
2756 @Override
2757 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2758 int userId) {
2759 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2761 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002763 final boolean detailed = checkGetTasksPermission(
2764 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2765 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 == PackageManager.PERMISSION_GRANTED;
2767
2768 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002769 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770 callingUid);
2771 }
2772 }
2773
2774 @Override
2775 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 long ident = Binder.clearCallingIdentity();
2778 try {
2779 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002780 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781 }
2782 } finally {
2783 Binder.restoreCallingIdentity(ident);
2784 }
2785 }
2786
2787 @Override
2788 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 long ident = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002793 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 }
2795 } finally {
2796 Binder.restoreCallingIdentity(ident);
2797 }
2798 }
2799
2800 @Override
2801 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002802 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002803 final long callingUid = Binder.getCallingUid();
2804 final long origId = Binder.clearCallingIdentity();
2805 try {
2806 synchronized (mGlobalLock) {
2807 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002808 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2810 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2811 }
2812 } finally {
2813 Binder.restoreCallingIdentity(origId);
2814 }
2815 }
2816
2817 @Override
2818 public void startLockTaskModeByToken(IBinder token) {
2819 synchronized (mGlobalLock) {
2820 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2821 if (r == null) {
2822 return;
2823 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002824 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002825 }
2826 }
2827
2828 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002829 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002830 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 // This makes inner call to look as if it was initiated by system.
2832 long ident = Binder.clearCallingIdentity();
2833 try {
2834 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002835 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002836 MATCH_TASK_IN_STACKS_ONLY);
2837 if (task == null) {
2838 return;
2839 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840
2841 // When starting lock task mode the stack must be in front and focused
2842 task.getStack().moveToFront("startSystemLockTaskMode");
2843 startLockTaskModeLocked(task, true /* isSystemCaller */);
2844 }
2845 } finally {
2846 Binder.restoreCallingIdentity(ident);
2847 }
2848 }
2849
2850 @Override
2851 public void stopLockTaskModeByToken(IBinder token) {
2852 synchronized (mGlobalLock) {
2853 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2854 if (r == null) {
2855 return;
2856 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002857 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002858 }
2859 }
2860
2861 /**
2862 * This API should be called by SystemUI only when user perform certain action to dismiss
2863 * lock task mode. We should only dismiss pinned lock task mode in this case.
2864 */
2865 @Override
2866 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002867 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2869 }
2870
2871 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2872 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2873 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2874 return;
2875 }
2876
Wale Ogunwaled32da472018-11-16 07:19:28 -08002877 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878 if (stack == null || task != stack.topTask()) {
2879 throw new IllegalArgumentException("Invalid task, not in foreground");
2880 }
2881
2882 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2883 // system or a specific app.
2884 // * System-initiated requests will only start the pinned mode (screen pinning)
2885 // * App-initiated requests
2886 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2887 // - will start the pinned mode, otherwise
2888 final int callingUid = Binder.getCallingUid();
2889 long ident = Binder.clearCallingIdentity();
2890 try {
2891 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002892 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002894 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 } finally {
2896 Binder.restoreCallingIdentity(ident);
2897 }
2898 }
2899
2900 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2901 final int callingUid = Binder.getCallingUid();
2902 long ident = Binder.clearCallingIdentity();
2903 try {
2904 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002905 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 }
2907 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2908 // task and jumping straight into a call in the case of emergency call back.
2909 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2910 if (tm != null) {
2911 tm.showInCallScreen(false);
2912 }
2913 } finally {
2914 Binder.restoreCallingIdentity(ident);
2915 }
2916 }
2917
2918 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002919 public void updateLockTaskPackages(int userId, String[] packages) {
2920 final int callingUid = Binder.getCallingUid();
2921 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2922 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2923 "updateLockTaskPackages()");
2924 }
2925 synchronized (this) {
2926 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2927 + Arrays.toString(packages));
2928 getLockTaskController().updateLockTaskPackages(userId, packages);
2929 }
2930 }
2931
2932 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 public boolean isInLockTaskMode() {
2934 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2935 }
2936
2937 @Override
2938 public int getLockTaskModeState() {
2939 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002940 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 }
2942 }
2943
2944 @Override
2945 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2946 synchronized (mGlobalLock) {
2947 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2948 if (r != null) {
2949 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002952 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 }
2954 }
2955 }
2956
2957 @Override
2958 public Bundle getActivityOptions(IBinder token) {
2959 final long origId = Binder.clearCallingIdentity();
2960 try {
2961 synchronized (mGlobalLock) {
2962 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2963 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002964 final ActivityOptions activityOptions = r.takeOptionsLocked(
2965 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 return activityOptions == null ? null : activityOptions.toBundle();
2967 }
2968 return null;
2969 }
2970 } finally {
2971 Binder.restoreCallingIdentity(origId);
2972 }
2973 }
2974
2975 @Override
2976 public List<IBinder> getAppTasks(String callingPackage) {
2977 int callingUid = Binder.getCallingUid();
2978 long ident = Binder.clearCallingIdentity();
2979 try {
2980 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002981 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 }
2983 } finally {
2984 Binder.restoreCallingIdentity(ident);
2985 }
2986 }
2987
2988 @Override
2989 public void finishVoiceTask(IVoiceInteractionSession session) {
2990 synchronized (mGlobalLock) {
2991 final long origId = Binder.clearCallingIdentity();
2992 try {
2993 // TODO: VI Consider treating local voice interactions and voice tasks
2994 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002995 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 } finally {
2997 Binder.restoreCallingIdentity(origId);
2998 }
2999 }
3000
3001 }
3002
3003 @Override
3004 public boolean isTopOfTask(IBinder token) {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003007 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 }
3009 }
3010
3011 @Override
3012 public void notifyLaunchTaskBehindComplete(IBinder token) {
3013 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3014 }
3015
3016 @Override
3017 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003018 mH.post(() -> {
3019 synchronized (mGlobalLock) {
3020 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003021 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003022 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003023 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003024 } catch (RemoteException e) {
3025 }
3026 }
3027 }
3028
3029 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 }
3031
3032 /** Called from an app when assist data is ready. */
3033 @Override
3034 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3035 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003036 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 synchronized (pae) {
3038 pae.result = extras;
3039 pae.structure = structure;
3040 pae.content = content;
3041 if (referrer != null) {
3042 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3043 }
3044 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003045 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003046 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3047 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 structure.setHomeActivity(pae.isHome);
3049 }
3050 pae.haveResult = true;
3051 pae.notifyAll();
3052 if (pae.intent == null && pae.receiver == null) {
3053 // Caller is just waiting for the result.
3054 return;
3055 }
3056 }
3057 // We are now ready to launch the assist activity.
3058 IAssistDataReceiver sendReceiver = null;
3059 Bundle sendBundle = null;
3060 synchronized (mGlobalLock) {
3061 buildAssistBundleLocked(pae, extras);
3062 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003063 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003064 if (!exists) {
3065 // Timed out.
3066 return;
3067 }
3068
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003069 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 // Caller wants result sent back to them.
3071 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003072 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3073 pae.activity.getTaskRecord().taskId);
3074 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3075 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3077 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3078 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3079 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3080 }
3081 }
3082 if (sendReceiver != null) {
3083 try {
3084 sendReceiver.onHandleAssistData(sendBundle);
3085 } catch (RemoteException e) {
3086 }
3087 return;
3088 }
3089
3090 final long ident = Binder.clearCallingIdentity();
3091 try {
3092 if (TextUtils.equals(pae.intent.getAction(),
3093 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3094 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003095
3096 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 } else {
3098 pae.intent.replaceExtras(pae.extras);
3099 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3100 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3101 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003102 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103
3104 try {
3105 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3106 } catch (ActivityNotFoundException e) {
3107 Slog.w(TAG, "No activity to handle assist action.", e);
3108 }
3109 }
3110 } finally {
3111 Binder.restoreCallingIdentity(ident);
3112 }
3113 }
3114
Marvin Ramin830d4e32019-03-12 13:16:58 +01003115 /**
3116 * Workaround for historical API which starts the Assist service with a non-foreground
3117 * {@code startService()} call.
3118 */
3119 private void startVoiceInteractionServiceAsUser(
3120 Intent intent, int userHandle, String reason) {
3121 // Resolve the intent to find out which package we need to whitelist.
3122 ResolveInfo resolveInfo =
3123 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3124 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3125 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3126 return;
3127 }
3128 intent.setPackage(resolveInfo.serviceInfo.packageName);
3129
3130 // Whitelist background services temporarily.
3131 LocalServices.getService(DeviceIdleController.LocalService.class)
3132 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3133 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3134
3135 // Finally, try to start the service.
3136 try {
3137 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3138 } catch (RuntimeException e) {
3139 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3140 }
3141 }
3142
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 @Override
3144 public int addAppTask(IBinder activityToken, Intent intent,
3145 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3146 final int callingUid = Binder.getCallingUid();
3147 final long callingIdent = Binder.clearCallingIdentity();
3148
3149 try {
3150 synchronized (mGlobalLock) {
3151 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3152 if (r == null) {
3153 throw new IllegalArgumentException("Activity does not exist; token="
3154 + activityToken);
3155 }
3156 ComponentName comp = intent.getComponent();
3157 if (comp == null) {
3158 throw new IllegalArgumentException("Intent " + intent
3159 + " must specify explicit component");
3160 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003161 if (thumbnail.getWidth() != mThumbnailWidth
3162 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 throw new IllegalArgumentException("Bad thumbnail size: got "
3164 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003165 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 }
3167 if (intent.getSelector() != null) {
3168 intent.setSelector(null);
3169 }
3170 if (intent.getSourceBounds() != null) {
3171 intent.setSourceBounds(null);
3172 }
3173 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3174 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3175 // The caller has added this as an auto-remove task... that makes no
3176 // sense, so turn off auto-remove.
3177 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3178 }
3179 }
3180 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3181 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3182 if (ainfo.applicationInfo.uid != callingUid) {
3183 throw new SecurityException(
3184 "Can't add task for another application: target uid="
3185 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3186 }
3187
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003188 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003190 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003192 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 // The app has too many tasks already and we can't add any more
3194 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3195 return INVALID_TASK_ID;
3196 }
3197 task.lastTaskDescription.copyFrom(description);
3198
3199 // TODO: Send the thumbnail to WM to store it.
3200
3201 return task.taskId;
3202 }
3203 } finally {
3204 Binder.restoreCallingIdentity(callingIdent);
3205 }
3206 }
3207
3208 @Override
3209 public Point getAppTaskThumbnailSize() {
3210 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 }
3213 }
3214
3215 @Override
3216 public void setTaskResizeable(int taskId, int resizeableMode) {
3217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003218 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3220 if (task == null) {
3221 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3222 return;
3223 }
3224 task.setResizeMode(resizeableMode);
3225 }
3226 }
3227
3228 @Override
3229 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003230 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003231 long ident = Binder.clearCallingIdentity();
3232 try {
3233 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003234 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003235 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003236 if (task == null) {
3237 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3238 return;
3239 }
3240 // Place the task in the right stack if it isn't there already based on
3241 // the requested bounds.
3242 // The stack transition logic is:
3243 // - a null bounds on a freeform task moves that task to fullscreen
3244 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3245 // that task to freeform
3246 // - otherwise the task is not moved
3247 ActivityStack stack = task.getStack();
3248 if (!task.getWindowConfiguration().canResizeTask()) {
3249 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3250 }
3251 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3252 stack = stack.getDisplay().getOrCreateStack(
3253 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3254 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3255 stack = stack.getDisplay().getOrCreateStack(
3256 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3257 }
3258
3259 // Reparent the task to the right stack if necessary
3260 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3261 if (stack != task.getStack()) {
3262 // Defer resume until the task is resized below
3263 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3264 DEFER_RESUME, "resizeTask");
3265 preserveWindow = false;
3266 }
3267
3268 // After reparenting (which only resizes the task to the stack bounds), resize the
3269 // task to the actual bounds provided
3270 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3271 }
3272 } finally {
3273 Binder.restoreCallingIdentity(ident);
3274 }
3275 }
3276
3277 @Override
3278 public boolean releaseActivityInstance(IBinder token) {
3279 synchronized (mGlobalLock) {
3280 final long origId = Binder.clearCallingIdentity();
3281 try {
3282 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3283 if (r == null) {
3284 return false;
3285 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003286 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003287 } finally {
3288 Binder.restoreCallingIdentity(origId);
3289 }
3290 }
3291 }
3292
3293 @Override
3294 public void releaseSomeActivities(IApplicationThread appInt) {
3295 synchronized (mGlobalLock) {
3296 final long origId = Binder.clearCallingIdentity();
3297 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003298 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003299 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003300 } finally {
3301 Binder.restoreCallingIdentity(origId);
3302 }
3303 }
3304 }
3305
3306 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003307 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003308 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 != PackageManager.PERMISSION_GRANTED) {
3310 throw new SecurityException("Requires permission "
3311 + android.Manifest.permission.DEVICE_POWER);
3312 }
3313
3314 synchronized (mGlobalLock) {
3315 long ident = Binder.clearCallingIdentity();
3316 if (mKeyguardShown != keyguardShowing) {
3317 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003318 final Message msg = PooledLambda.obtainMessage(
3319 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3320 keyguardShowing);
3321 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 }
3323 try {
wilsonshih177261f2019-02-22 12:02:18 +08003324 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 } finally {
3326 Binder.restoreCallingIdentity(ident);
3327 }
3328 }
3329
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003330 mH.post(() -> {
3331 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3332 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3333 }
3334 });
3335 }
3336
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003337 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003338 mH.post(() -> {
3339 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3340 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3341 }
3342 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 }
3344
3345 @Override
3346 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003347 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3348 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349
3350 final File passedIconFile = new File(filePath);
3351 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3352 passedIconFile.getName());
3353 if (!legitIconFile.getPath().equals(filePath)
3354 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3355 throw new IllegalArgumentException("Bad file path: " + filePath
3356 + " passed for userId " + userId);
3357 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003358 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 }
3360
3361 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003362 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3364 final ActivityOptions activityOptions = safeOptions != null
3365 ? safeOptions.getOptions(mStackSupervisor)
3366 : null;
3367 if (activityOptions == null
3368 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3369 || activityOptions.getCustomInPlaceResId() == 0) {
3370 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3371 "with valid animation");
3372 }
lumark588a3e82018-07-20 18:53:54 +08003373 // Get top display of front most application.
3374 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3375 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003376 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3377 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3378 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003379 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003380 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003381 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 }
3383
3384 @Override
3385 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 synchronized (mGlobalLock) {
3388 final long ident = Binder.clearCallingIdentity();
3389 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003390 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 if (stack == null) {
3392 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3393 return;
3394 }
3395 if (!stack.isActivityTypeStandardOrUndefined()) {
3396 throw new IllegalArgumentException(
3397 "Removing non-standard stack is not allowed.");
3398 }
3399 mStackSupervisor.removeStack(stack);
3400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
3404 }
3405
3406 @Override
3407 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409
3410 synchronized (mGlobalLock) {
3411 final long ident = Binder.clearCallingIdentity();
3412 try {
3413 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3414 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003415 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 } finally {
3417 Binder.restoreCallingIdentity(ident);
3418 }
3419 }
3420 }
3421
3422 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003423 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 synchronized (mGlobalLock) {
3425 long ident = Binder.clearCallingIdentity();
3426 try {
3427 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3428 if (r == null) {
3429 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003430 "toggleFreeformWindowingMode: No activity record matching token="
3431 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003434 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003435 if (stack == null) {
3436 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3437 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
Yunfan Chend967af82019-01-17 18:30:18 +09003440 if (!stack.inFreeformWindowingMode()
3441 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3442 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3443 + "toggle between fullscreen and freeform.");
3444 }
3445
3446 if (stack.inFreeformWindowingMode()) {
3447 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003448 } else if (stack.getParent().inFreeformWindowingMode()) {
3449 // If the window is on a freeform display, set it to undefined. It will be
3450 // resolved to freeform and it can adjust windowing mode when the display mode
3451 // changes in runtime.
3452 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003453 } else {
3454 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3455 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 } finally {
3457 Binder.restoreCallingIdentity(ident);
3458 }
3459 }
3460 }
3461
3462 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3463 @Override
3464 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003467 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 }
3469
3470 /** Unregister a task stack listener so that it stops receiving callbacks. */
3471 @Override
3472 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003473 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003475 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 @Override
3479 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3480 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3481 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3482 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3483 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3484 }
3485
3486 @Override
3487 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3488 IBinder activityToken, int flags) {
3489 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3490 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3491 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3492 }
3493
3494 @Override
3495 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3496 Bundle args) {
3497 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3498 true /* focused */, true /* newSessionId */, userHandle, args,
3499 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3500 }
3501
3502 @Override
3503 public Bundle getAssistContextExtras(int requestType) {
3504 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3505 null, null, true /* focused */, true /* newSessionId */,
3506 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3507 if (pae == null) {
3508 return null;
3509 }
3510 synchronized (pae) {
3511 while (!pae.haveResult) {
3512 try {
3513 pae.wait();
3514 } catch (InterruptedException e) {
3515 }
3516 }
3517 }
3518 synchronized (mGlobalLock) {
3519 buildAssistBundleLocked(pae, pae.result);
3520 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 }
3523 return pae.extras;
3524 }
3525
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 /**
3527 * Binder IPC calls go through the public entry point.
3528 * This can be called with or without the global lock held.
3529 */
3530 private static int checkCallingPermission(String permission) {
3531 return checkPermission(
3532 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3533 }
3534
3535 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003536 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003537 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3538 mAmInternal.enforceCallingPermission(permission, func);
3539 }
3540 }
3541
3542 @VisibleForTesting
3543 int checkGetTasksPermission(String permission, int pid, int uid) {
3544 return checkPermission(permission, pid, uid);
3545 }
3546
3547 static int checkPermission(String permission, int pid, int uid) {
3548 if (permission == null) {
3549 return PackageManager.PERMISSION_DENIED;
3550 }
3551 return checkComponentPermission(permission, pid, uid, -1, true);
3552 }
3553
Wale Ogunwale214f3482018-10-04 11:00:47 -07003554 public static int checkComponentPermission(String permission, int pid, int uid,
3555 int owningUid, boolean exported) {
3556 return ActivityManagerService.checkComponentPermission(
3557 permission, pid, uid, owningUid, exported);
3558 }
3559
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003560 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3561 if (getRecentTasks().isCallerRecents(callingUid)) {
3562 // Always allow the recents component to get tasks
3563 return true;
3564 }
3565
3566 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3567 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3568 if (!allowed) {
3569 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3570 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3571 // Temporary compatibility: some existing apps on the system image may
3572 // still be requesting the old permission and not switched to the new
3573 // one; if so, we'll still allow them full access. This means we need
3574 // to see if they are holding the old permission and are a system app.
3575 try {
3576 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3577 allowed = true;
3578 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3579 + " is using old GET_TASKS but privileged; allowing");
3580 }
3581 } catch (RemoteException e) {
3582 }
3583 }
3584 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3585 + " does not hold REAL_GET_TASKS; limiting output");
3586 }
3587 return allowed;
3588 }
3589
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3591 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3592 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3593 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003594 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 "enqueueAssistContext()");
3596
3597 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003598 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 if (activity == null) {
3600 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3601 return null;
3602 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003603 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003604 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3605 return null;
3606 }
3607 if (focused) {
3608 if (activityToken != null) {
3609 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3610 if (activity != caller) {
3611 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3612 + " is not current top " + activity);
3613 return null;
3614 }
3615 }
3616 } else {
3617 activity = ActivityRecord.forTokenLocked(activityToken);
3618 if (activity == null) {
3619 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3620 + " couldn't be found");
3621 return null;
3622 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003623 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3625 return null;
3626 }
3627 }
3628
3629 PendingAssistExtras pae;
3630 Bundle extras = new Bundle();
3631 if (args != null) {
3632 extras.putAll(args);
3633 }
3634 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003635 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636
3637 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3638 userHandle);
3639 pae.isHome = activity.isActivityTypeHome();
3640
3641 // Increment the sessionId if necessary
3642 if (newSessionId) {
3643 mViSessionId++;
3644 }
3645 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003646 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3647 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 } catch (RemoteException e) {
3651 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3652 return null;
3653 }
3654 return pae;
3655 }
3656 }
3657
3658 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3659 if (result != null) {
3660 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3661 }
3662 if (pae.hint != null) {
3663 pae.extras.putBoolean(pae.hint, true);
3664 }
3665 }
3666
3667 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3668 IAssistDataReceiver receiver;
3669 synchronized (mGlobalLock) {
3670 mPendingAssistExtras.remove(pae);
3671 receiver = pae.receiver;
3672 }
3673 if (receiver != null) {
3674 // Caller wants result sent back to them.
3675 Bundle sendBundle = new Bundle();
3676 // At least return the receiver extras
3677 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3678 try {
3679 pae.receiver.onHandleAssistData(sendBundle);
3680 } catch (RemoteException e) {
3681 }
3682 }
3683 }
3684
3685 public class PendingAssistExtras extends Binder implements Runnable {
3686 public final ActivityRecord activity;
3687 public boolean isHome;
3688 public final Bundle extras;
3689 public final Intent intent;
3690 public final String hint;
3691 public final IAssistDataReceiver receiver;
3692 public final int userHandle;
3693 public boolean haveResult = false;
3694 public Bundle result = null;
3695 public AssistStructure structure = null;
3696 public AssistContent content = null;
3697 public Bundle receiverExtras;
3698
3699 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3700 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3701 int _userHandle) {
3702 activity = _activity;
3703 extras = _extras;
3704 intent = _intent;
3705 hint = _hint;
3706 receiver = _receiver;
3707 receiverExtras = _receiverExtras;
3708 userHandle = _userHandle;
3709 }
3710
3711 @Override
3712 public void run() {
3713 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3714 synchronized (this) {
3715 haveResult = true;
3716 notifyAll();
3717 }
3718 pendingAssistExtrasTimedOut(this);
3719 }
3720 }
3721
3722 @Override
3723 public boolean isAssistDataAllowedOnCurrentActivity() {
3724 int userId;
3725 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003726 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003727 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3728 return false;
3729 }
3730
3731 final ActivityRecord activity = focusedStack.getTopActivity();
3732 if (activity == null) {
3733 return false;
3734 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003735 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 }
3737 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3738 }
3739
3740 @Override
3741 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3742 long ident = Binder.clearCallingIdentity();
3743 try {
3744 synchronized (mGlobalLock) {
3745 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003746 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003747 if (top != caller) {
3748 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3749 + " is not current top " + top);
3750 return false;
3751 }
3752 if (!top.nowVisible) {
3753 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3754 + " is not visible");
3755 return false;
3756 }
3757 }
3758 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3759 token);
3760 } finally {
3761 Binder.restoreCallingIdentity(ident);
3762 }
3763 }
3764
3765 @Override
3766 public boolean isRootVoiceInteraction(IBinder token) {
3767 synchronized (mGlobalLock) {
3768 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3769 if (r == null) {
3770 return false;
3771 }
3772 return r.rootVoiceInteraction;
3773 }
3774 }
3775
Wale Ogunwalef6733932018-06-27 05:14:34 -07003776 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3777 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3778 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3779 if (activityToCallback == null) return;
3780 activityToCallback.setVoiceSessionLocked(voiceSession);
3781
3782 // Inform the activity
3783 try {
3784 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3785 voiceInteractor);
3786 long token = Binder.clearCallingIdentity();
3787 try {
3788 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3789 } finally {
3790 Binder.restoreCallingIdentity(token);
3791 }
3792 // TODO: VI Should we cache the activity so that it's easier to find later
3793 // rather than scan through all the stacks and activities?
3794 } catch (RemoteException re) {
3795 activityToCallback.clearVoiceSessionLocked();
3796 // TODO: VI Should this terminate the voice session?
3797 }
3798 }
3799
3800 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3801 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3802 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3803 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3804 boolean wasRunningVoice = mRunningVoice != null;
3805 mRunningVoice = session;
3806 if (!wasRunningVoice) {
3807 mVoiceWakeLock.acquire();
3808 updateSleepIfNeededLocked();
3809 }
3810 }
3811 }
3812
3813 void finishRunningVoiceLocked() {
3814 if (mRunningVoice != null) {
3815 mRunningVoice = null;
3816 mVoiceWakeLock.release();
3817 updateSleepIfNeededLocked();
3818 }
3819 }
3820
3821 @Override
3822 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3823 synchronized (mGlobalLock) {
3824 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3825 if (keepAwake) {
3826 mVoiceWakeLock.acquire();
3827 } else {
3828 mVoiceWakeLock.release();
3829 }
3830 }
3831 }
3832 }
3833
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 @Override
3835 public ComponentName getActivityClassForToken(IBinder token) {
3836 synchronized (mGlobalLock) {
3837 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3838 if (r == null) {
3839 return null;
3840 }
3841 return r.intent.getComponent();
3842 }
3843 }
3844
3845 @Override
3846 public String getPackageForToken(IBinder token) {
3847 synchronized (mGlobalLock) {
3848 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3849 if (r == null) {
3850 return null;
3851 }
3852 return r.packageName;
3853 }
3854 }
3855
3856 @Override
3857 public void showLockTaskEscapeMessage(IBinder token) {
3858 synchronized (mGlobalLock) {
3859 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3860 if (r == null) {
3861 return;
3862 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003863 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 }
3865 }
3866
3867 @Override
3868 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003869 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 final long token = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003873 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 }
3875 } finally {
3876 Binder.restoreCallingIdentity(token);
3877 }
3878 }
3879
3880 /**
3881 * Try to place task to provided position. The final position might be different depending on
3882 * current user and stacks state. The task will be moved to target stack if it's currently in
3883 * different stack.
3884 */
3885 @Override
3886 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003887 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 synchronized (mGlobalLock) {
3889 long ident = Binder.clearCallingIdentity();
3890 try {
3891 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3892 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003893 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 if (task == null) {
3895 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3896 + taskId);
3897 }
3898
Wale Ogunwaled32da472018-11-16 07:19:28 -08003899 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900
3901 if (stack == null) {
3902 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3903 + stackId);
3904 }
3905 if (!stack.isActivityTypeStandardOrUndefined()) {
3906 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3907 + " the position of task " + taskId + " in/to non-standard stack");
3908 }
3909
3910 // TODO: Have the callers of this API call a separate reparent method if that is
3911 // what they intended to do vs. having this method also do reparenting.
3912 if (task.getStack() == stack) {
3913 // Change position in current stack.
3914 stack.positionChildAt(task, position);
3915 } else {
3916 // Reparent to new stack.
3917 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3918 !DEFER_RESUME, "positionTaskInStack");
3919 }
3920 } finally {
3921 Binder.restoreCallingIdentity(ident);
3922 }
3923 }
3924 }
3925
3926 @Override
3927 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3928 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3929 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3930 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3931 synchronized (mGlobalLock) {
3932 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3933 if (record == null) {
3934 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3935 + "found for: " + token);
3936 }
3937 record.setSizeConfigurations(horizontalSizeConfiguration,
3938 verticalSizeConfigurations, smallestSizeConfigurations);
3939 }
3940 }
3941
3942 /**
3943 * Dismisses split-screen multi-window mode.
3944 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3945 */
3946 @Override
3947 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003948 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003949 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3950 final long ident = Binder.clearCallingIdentity();
3951 try {
3952 synchronized (mGlobalLock) {
3953 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003954 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 if (stack == null) {
3956 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3957 return;
3958 }
3959
3960 if (toTop) {
3961 // Caller wants the current split-screen primary stack to be the top stack after
3962 // it goes fullscreen, so move it to the front.
3963 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003964 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 // In this case the current split-screen primary stack shouldn't be the top
3966 // stack after it goes fullscreen, but it current has focus, so we move the
3967 // focus to the top-most split-screen secondary stack next to it.
3968 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3969 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3970 if (otherStack != null) {
3971 otherStack.moveToFront("dismissSplitScreenMode_other");
3972 }
3973 }
3974
Evan Rosky10475742018-09-05 19:02:48 -07003975 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 }
3977 } finally {
3978 Binder.restoreCallingIdentity(ident);
3979 }
3980 }
3981
3982 /**
3983 * Dismisses Pip
3984 * @param animate True if the dismissal should be animated.
3985 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3986 * default animation duration should be used.
3987 */
3988 @Override
3989 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 final long ident = Binder.clearCallingIdentity();
3992 try {
3993 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003994 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003995 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 if (stack == null) {
3997 Slog.w(TAG, "dismissPip: pinned stack not found.");
3998 return;
3999 }
4000 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4001 throw new IllegalArgumentException("Stack: " + stack
4002 + " doesn't support animated resize.");
4003 }
4004 if (animate) {
4005 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4006 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4007 } else {
4008 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4009 }
4010 }
4011 } finally {
4012 Binder.restoreCallingIdentity(ident);
4013 }
4014 }
4015
4016 @Override
4017 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004018 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 synchronized (mGlobalLock) {
4020 mSuppressResizeConfigChanges = suppress;
4021 }
4022 }
4023
4024 /**
4025 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4026 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4027 * activity and clearing the task at the same time.
4028 */
4029 @Override
4030 // TODO: API should just be about changing windowing modes...
4031 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 "moveTasksToFullscreenStack()");
4034 synchronized (mGlobalLock) {
4035 final long origId = Binder.clearCallingIdentity();
4036 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004037 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 if (stack != null){
4039 if (!stack.isActivityTypeStandardOrUndefined()) {
4040 throw new IllegalArgumentException(
4041 "You can't move tasks from non-standard stacks.");
4042 }
4043 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(origId);
4047 }
4048 }
4049 }
4050
4051 /**
4052 * Moves the top activity in the input stackId to the pinned stack.
4053 *
4054 * @param stackId Id of stack to move the top activity to pinned stack.
4055 * @param bounds Bounds to use for pinned stack.
4056 *
4057 * @return True if the top activity of the input stack was successfully moved to the pinned
4058 * stack.
4059 */
4060 @Override
4061 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004062 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 "moveTopActivityToPinnedStack()");
4064 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004065 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4067 + "Device doesn't support picture-in-picture mode");
4068 }
4069
4070 long ident = Binder.clearCallingIdentity();
4071 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004072 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 } finally {
4074 Binder.restoreCallingIdentity(ident);
4075 }
4076 }
4077 }
4078
4079 @Override
4080 public boolean isInMultiWindowMode(IBinder token) {
4081 final long origId = Binder.clearCallingIdentity();
4082 try {
4083 synchronized (mGlobalLock) {
4084 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4085 if (r == null) {
4086 return false;
4087 }
4088 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4089 return r.inMultiWindowMode();
4090 }
4091 } finally {
4092 Binder.restoreCallingIdentity(origId);
4093 }
4094 }
4095
4096 @Override
4097 public boolean isInPictureInPictureMode(IBinder token) {
4098 final long origId = Binder.clearCallingIdentity();
4099 try {
4100 synchronized (mGlobalLock) {
4101 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4102 }
4103 } finally {
4104 Binder.restoreCallingIdentity(origId);
4105 }
4106 }
4107
4108 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004109 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4110 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 return false;
4112 }
4113
4114 // If we are animating to fullscreen then we have already dispatched the PIP mode
4115 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004116 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4117 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 }
4119
4120 @Override
4121 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4122 final long origId = Binder.clearCallingIdentity();
4123 try {
4124 synchronized (mGlobalLock) {
4125 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4126 "enterPictureInPictureMode", token, params);
4127
4128 // If the activity is already in picture in picture mode, then just return early
4129 if (isInPictureInPictureMode(r)) {
4130 return true;
4131 }
4132
4133 // Activity supports picture-in-picture, now check that we can enter PiP at this
4134 // point, if it is
4135 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4136 false /* beforeStopping */)) {
4137 return false;
4138 }
4139
4140 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 synchronized (mGlobalLock) {
4142 // Only update the saved args from the args that are set
4143 r.pictureInPictureArgs.copyOnlySet(params);
4144 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4145 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4146 // Adjust the source bounds by the insets for the transition down
4147 final Rect sourceBounds = new Rect(
4148 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004149 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004150 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004151 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004152 stack.setPictureInPictureAspectRatio(aspectRatio);
4153 stack.setPictureInPictureActions(actions);
4154 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4155 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4156 logPictureInPictureArgs(params);
4157 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 };
4159
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004160 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 // If the keyguard is showing or occluded, then try and dismiss it before
4162 // entering picture-in-picture (this will prompt the user to authenticate if the
4163 // device is currently locked).
4164 dismissKeyguard(token, new KeyguardDismissCallback() {
4165 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004166 public void onDismissSucceeded() {
4167 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 }
4169 }, null /* message */);
4170 } else {
4171 // Enter picture in picture immediately otherwise
4172 enterPipRunnable.run();
4173 }
4174 return true;
4175 }
4176 } finally {
4177 Binder.restoreCallingIdentity(origId);
4178 }
4179 }
4180
4181 @Override
4182 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4183 final long origId = Binder.clearCallingIdentity();
4184 try {
4185 synchronized (mGlobalLock) {
4186 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4187 "setPictureInPictureParams", token, params);
4188
4189 // Only update the saved args from the args that are set
4190 r.pictureInPictureArgs.copyOnlySet(params);
4191 if (r.inPinnedWindowingMode()) {
4192 // If the activity is already in picture-in-picture, update the pinned stack now
4193 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4194 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004195 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004196 if (!stack.isAnimatingBoundsToFullscreen()) {
4197 stack.setPictureInPictureAspectRatio(
4198 r.pictureInPictureArgs.getAspectRatio());
4199 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4200 }
4201 }
4202 logPictureInPictureArgs(params);
4203 }
4204 } finally {
4205 Binder.restoreCallingIdentity(origId);
4206 }
4207 }
4208
4209 @Override
4210 public int getMaxNumPictureInPictureActions(IBinder token) {
4211 // Currently, this is a static constant, but later, we may change this to be dependent on
4212 // the context of the activity
4213 return 3;
4214 }
4215
4216 private void logPictureInPictureArgs(PictureInPictureParams params) {
4217 if (params.hasSetActions()) {
4218 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4219 params.getActions().size());
4220 }
4221 if (params.hasSetAspectRatio()) {
4222 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4223 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4224 MetricsLogger.action(lm);
4225 }
4226 }
4227
4228 /**
4229 * Checks the state of the system and the activity associated with the given {@param token} to
4230 * verify that picture-in-picture is supported for that activity.
4231 *
4232 * @return the activity record for the given {@param token} if all the checks pass.
4233 */
4234 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4235 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 throw new IllegalStateException(caller
4238 + ": Device doesn't support picture-in-picture mode.");
4239 }
4240
4241 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4242 if (r == null) {
4243 throw new IllegalStateException(caller
4244 + ": Can't find activity for token=" + token);
4245 }
4246
4247 if (!r.supportsPictureInPicture()) {
4248 throw new IllegalStateException(caller
4249 + ": Current activity does not support picture-in-picture.");
4250 }
4251
4252 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004253 && !mWindowManager.isValidPictureInPictureAspectRatio(
4254 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 final float minAspectRatio = mContext.getResources().getFloat(
4256 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4257 final float maxAspectRatio = mContext.getResources().getFloat(
4258 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4259 throw new IllegalArgumentException(String.format(caller
4260 + ": Aspect ratio is too extreme (must be between %f and %f).",
4261 minAspectRatio, maxAspectRatio));
4262 }
4263
4264 // Truncate the number of actions if necessary
4265 params.truncateActions(getMaxNumPictureInPictureActions(token));
4266
4267 return r;
4268 }
4269
4270 @Override
4271 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004272 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 synchronized (mGlobalLock) {
4274 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4275 if (r == null) {
4276 throw new IllegalArgumentException("Activity does not exist; token="
4277 + activityToken);
4278 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004279 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 }
4281 }
4282
4283 @Override
4284 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4285 Rect tempDockedTaskInsetBounds,
4286 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 long ident = Binder.clearCallingIdentity();
4289 try {
4290 synchronized (mGlobalLock) {
4291 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4292 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4293 PRESERVE_WINDOWS);
4294 }
4295 } finally {
4296 Binder.restoreCallingIdentity(ident);
4297 }
4298 }
4299
4300 @Override
4301 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 final long ident = Binder.clearCallingIdentity();
4304 try {
4305 synchronized (mGlobalLock) {
4306 mStackSupervisor.setSplitScreenResizing(resizing);
4307 }
4308 } finally {
4309 Binder.restoreCallingIdentity(ident);
4310 }
4311 }
4312
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004313 /**
4314 * Check that we have the features required for VR-related API calls, and throw an exception if
4315 * not.
4316 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004317 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 if (!mContext.getPackageManager().hasSystemFeature(
4319 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4320 throw new UnsupportedOperationException("VR mode not supported on this device!");
4321 }
4322 }
4323
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 @Override
4325 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004326 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327
4328 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4329
4330 ActivityRecord r;
4331 synchronized (mGlobalLock) {
4332 r = ActivityRecord.isInStackLocked(token);
4333 }
4334
4335 if (r == null) {
4336 throw new IllegalArgumentException();
4337 }
4338
4339 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004340 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 VrManagerInternal.NO_ERROR) {
4342 return err;
4343 }
4344
4345 // Clear the binder calling uid since this path may call moveToTask().
4346 final long callingId = Binder.clearCallingIdentity();
4347 try {
4348 synchronized (mGlobalLock) {
4349 r.requestedVrComponent = (enabled) ? packageName : null;
4350
4351 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004352 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004353 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 }
4355 return 0;
4356 }
4357 } finally {
4358 Binder.restoreCallingIdentity(callingId);
4359 }
4360 }
4361
4362 @Override
4363 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4364 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4365 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004366 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4368 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4369 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004370 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 || activity.voiceSession != null) {
4372 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4373 return;
4374 }
4375 if (activity.pendingVoiceInteractionStart) {
4376 Slog.w(TAG, "Pending start of voice interaction already.");
4377 return;
4378 }
4379 activity.pendingVoiceInteractionStart = true;
4380 }
4381 LocalServices.getService(VoiceInteractionManagerInternal.class)
4382 .startLocalVoiceInteraction(callingActivity, options);
4383 }
4384
4385 @Override
4386 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4387 LocalServices.getService(VoiceInteractionManagerInternal.class)
4388 .stopLocalVoiceInteraction(callingActivity);
4389 }
4390
4391 @Override
4392 public boolean supportsLocalVoiceInteraction() {
4393 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4394 .supportsLocalVoiceInteraction();
4395 }
4396
4397 /** Notifies all listeners when the pinned stack animation starts. */
4398 @Override
4399 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004400 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 }
4402
4403 /** Notifies all listeners when the pinned stack animation ends. */
4404 @Override
4405 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004406 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 }
4408
4409 @Override
4410 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 final long ident = Binder.clearCallingIdentity();
4413 try {
4414 synchronized (mGlobalLock) {
4415 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4416 }
4417 } finally {
4418 Binder.restoreCallingIdentity(ident);
4419 }
4420 }
4421
4422 @Override
4423 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425
4426 synchronized (mGlobalLock) {
4427 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004428 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 // Call might come when display is not yet added or has already been removed.
4430 if (DEBUG_CONFIGURATION) {
4431 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4432 + displayId);
4433 }
4434 return false;
4435 }
4436
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 }
4441
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004443 final Message msg = PooledLambda.obtainMessage(
4444 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4445 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 }
4447
4448 final long origId = Binder.clearCallingIdentity();
4449 try {
4450 if (values != null) {
4451 Settings.System.clearConfiguration(values);
4452 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4455 return mTmpUpdateConfigurationResult.changes != 0;
4456 } finally {
4457 Binder.restoreCallingIdentity(origId);
4458 }
4459 }
4460 }
4461
4462 @Override
4463 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004464 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465
4466 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004469 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004470 }
4471
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004473 final Message msg = PooledLambda.obtainMessage(
4474 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4475 DEFAULT_DISPLAY);
4476 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 }
4478
4479 final long origId = Binder.clearCallingIdentity();
4480 try {
4481 if (values != null) {
4482 Settings.System.clearConfiguration(values);
4483 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004484 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 UserHandle.USER_NULL, false /* deferResume */,
4486 mTmpUpdateConfigurationResult);
4487 return mTmpUpdateConfigurationResult.changes != 0;
4488 } finally {
4489 Binder.restoreCallingIdentity(origId);
4490 }
4491 }
4492 }
4493
4494 @Override
4495 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4496 CharSequence message) {
4497 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4500 }
4501 final long callingId = Binder.clearCallingIdentity();
4502 try {
4503 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004504 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 }
4506 } finally {
4507 Binder.restoreCallingIdentity(callingId);
4508 }
4509 }
4510
4511 @Override
4512 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004513 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 "cancelTaskWindowTransition()");
4515 final long ident = Binder.clearCallingIdentity();
4516 try {
4517 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004518 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004519 MATCH_TASK_IN_STACKS_ONLY);
4520 if (task == null) {
4521 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4522 return;
4523 }
4524 task.cancelWindowTransition();
4525 }
4526 } finally {
4527 Binder.restoreCallingIdentity(ident);
4528 }
4529 }
4530
4531 @Override
4532 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004533 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 final long ident = Binder.clearCallingIdentity();
4535 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004536 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 } finally {
4538 Binder.restoreCallingIdentity(ident);
4539 }
4540 }
4541
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004542 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4543 boolean restoreFromDisk) {
4544 final TaskRecord task;
4545 synchronized (mGlobalLock) {
4546 task = mRootActivityContainer.anyTaskForId(taskId,
4547 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4548 if (task == null) {
4549 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4550 return null;
4551 }
4552 }
4553 // Don't call this while holding the lock as this operation might hit the disk.
4554 return task.getSnapshot(reducedResolution, restoreFromDisk);
4555 }
4556
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 @Override
4558 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4559 synchronized (mGlobalLock) {
4560 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4561 if (r == null) {
4562 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4563 + token);
4564 return;
4565 }
4566 final long origId = Binder.clearCallingIdentity();
4567 try {
4568 r.setDisablePreviewScreenshots(disable);
4569 } finally {
4570 Binder.restoreCallingIdentity(origId);
4571 }
4572 }
4573 }
4574
4575 /** Return the user id of the last resumed activity. */
4576 @Override
4577 public @UserIdInt
4578 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004579 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4581 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004582 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004583 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004584 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004585 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004586 }
4587 }
4588
4589 @Override
4590 public void updateLockTaskFeatures(int userId, int flags) {
4591 final int callingUid = Binder.getCallingUid();
4592 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004593 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 "updateLockTaskFeatures()");
4595 }
4596 synchronized (mGlobalLock) {
4597 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4598 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004599 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 }
4601 }
4602
4603 @Override
4604 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4605 synchronized (mGlobalLock) {
4606 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4607 if (r == null) {
4608 return;
4609 }
4610 final long origId = Binder.clearCallingIdentity();
4611 try {
4612 r.setShowWhenLocked(showWhenLocked);
4613 } finally {
4614 Binder.restoreCallingIdentity(origId);
4615 }
4616 }
4617 }
4618
4619 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004620 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4621 synchronized (mGlobalLock) {
4622 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4623 if (r == null) {
4624 return;
4625 }
4626 final long origId = Binder.clearCallingIdentity();
4627 try {
4628 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4629 } finally {
4630 Binder.restoreCallingIdentity(origId);
4631 }
4632 }
4633 }
4634
4635 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004636 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4637 synchronized (mGlobalLock) {
4638 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4639 if (r == null) {
4640 return;
4641 }
4642 final long origId = Binder.clearCallingIdentity();
4643 try {
4644 r.setTurnScreenOn(turnScreenOn);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
4651 @Override
4652 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004653 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004654 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004655 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004656 synchronized (mGlobalLock) {
4657 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4658 if (r == null) {
4659 return;
4660 }
4661 final long origId = Binder.clearCallingIdentity();
4662 try {
4663 r.registerRemoteAnimations(definition);
4664 } finally {
4665 Binder.restoreCallingIdentity(origId);
4666 }
4667 }
4668 }
4669
4670 @Override
4671 public void registerRemoteAnimationForNextActivityStart(String packageName,
4672 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004674 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004675 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004676 synchronized (mGlobalLock) {
4677 final long origId = Binder.clearCallingIdentity();
4678 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004679 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004680 packageName, adapter);
4681 } finally {
4682 Binder.restoreCallingIdentity(origId);
4683 }
4684 }
4685 }
4686
Evan Rosky966759f2019-01-15 10:33:58 -08004687 @Override
4688 public void registerRemoteAnimationsForDisplay(int displayId,
4689 RemoteAnimationDefinition definition) {
4690 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4691 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004692 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004693 synchronized (mGlobalLock) {
4694 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4695 if (display == null) {
4696 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4697 return;
4698 }
4699 final long origId = Binder.clearCallingIdentity();
4700 try {
4701 display.mDisplayContent.registerRemoteAnimations(definition);
4702 } finally {
4703 Binder.restoreCallingIdentity(origId);
4704 }
4705 }
4706 }
4707
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004708 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4709 @Override
4710 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4711 synchronized (mGlobalLock) {
4712 final long origId = Binder.clearCallingIdentity();
4713 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004714 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004715 } finally {
4716 Binder.restoreCallingIdentity(origId);
4717 }
4718 }
4719 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004720
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 @Override
4722 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004723 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004725 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004726 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004727 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 }
4729 }
4730
4731 @Override
4732 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 != PERMISSION_GRANTED) {
4735 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4736 + Binder.getCallingPid()
4737 + ", uid=" + Binder.getCallingUid()
4738 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4739 Slog.w(TAG, msg);
4740 throw new SecurityException(msg);
4741 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004742 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004744 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004745 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004746 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004747 }
4748 }
4749
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004750 @Override
4751 public void stopAppSwitches() {
4752 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4753 synchronized (mGlobalLock) {
4754 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004755 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004756 mDidAppSwitch = false;
4757 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4758 }
4759 }
4760
4761 @Override
4762 public void resumeAppSwitches() {
4763 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4764 synchronized (mGlobalLock) {
4765 // Note that we don't execute any pending app switches... we will
4766 // let those wait until either the timeout, or the next start
4767 // activity request.
4768 mAppSwitchesAllowedTime = 0;
4769 }
4770 }
4771
Ricky Wai906af482019-06-03 17:25:28 +01004772 long getLastStopAppSwitchesTime() {
4773 return mLastStopAppSwitchesTime;
4774 }
4775
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004776 void onStartActivitySetDidAppSwitch() {
4777 if (mDidAppSwitch) {
4778 // This is the second allowed switch since we stopped switches, so now just generally
4779 // allow switches. Use case:
4780 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4781 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4782 // anyone to switch again).
4783 mAppSwitchesAllowedTime = 0;
4784 } else {
4785 mDidAppSwitch = true;
4786 }
4787 }
4788
4789 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 boolean shouldDisableNonVrUiLocked() {
4791 return mVrController.shouldDisableNonVrUiLocked();
4792 }
4793
Wale Ogunwale53783742018-09-16 10:21:51 -07004794 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004796 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004798 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4799 + " to main display for VR");
4800 mRootActivityContainer.moveStackToDisplay(
4801 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 }
4803 mH.post(() -> {
4804 if (!mVrController.onVrModeChanged(r)) {
4805 return;
4806 }
4807 synchronized (mGlobalLock) {
4808 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4809 mWindowManager.disableNonVrUi(disableNonVrUi);
4810 if (disableNonVrUi) {
4811 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4812 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004813 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004814 }
4815 }
4816 });
4817 }
4818
Wale Ogunwale53783742018-09-16 10:21:51 -07004819 @Override
4820 public int getPackageScreenCompatMode(String packageName) {
4821 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4822 synchronized (mGlobalLock) {
4823 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4824 }
4825 }
4826
4827 @Override
4828 public void setPackageScreenCompatMode(String packageName, int mode) {
4829 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4830 "setPackageScreenCompatMode");
4831 synchronized (mGlobalLock) {
4832 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4833 }
4834 }
4835
4836 @Override
4837 public boolean getPackageAskScreenCompat(String packageName) {
4838 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4839 synchronized (mGlobalLock) {
4840 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4841 }
4842 }
4843
4844 @Override
4845 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4846 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4847 "setPackageAskScreenCompat");
4848 synchronized (mGlobalLock) {
4849 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4850 }
4851 }
4852
Wale Ogunwale64258362018-10-16 15:13:37 -07004853 public static String relaunchReasonToString(int relaunchReason) {
4854 switch (relaunchReason) {
4855 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4856 return "window_resize";
4857 case RELAUNCH_REASON_FREE_RESIZE:
4858 return "free_resize";
4859 default:
4860 return null;
4861 }
4862 }
4863
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004864 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004865 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004866 }
4867
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004868 /** Pokes the task persister. */
4869 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4870 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4871 }
4872
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004873 boolean isKeyguardLocked() {
4874 return mKeyguardController.isKeyguardLocked();
4875 }
4876
Garfield Tan01548632018-11-27 10:15:48 -08004877 /**
4878 * Clears launch params for the given package.
4879 * @param packageNames the names of the packages of which the launch params are to be cleared
4880 */
4881 @Override
4882 public void clearLaunchParamsForPackages(List<String> packageNames) {
4883 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4884 "clearLaunchParamsForPackages");
4885 synchronized (mGlobalLock) {
4886 for (int i = 0; i < packageNames.size(); ++i) {
4887 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4888 }
4889 }
4890 }
4891
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004892 /**
4893 * Makes the display with the given id a single task instance display. I.e the display can only
4894 * contain one task.
4895 */
4896 @Override
4897 public void setDisplayToSingleTaskInstance(int displayId) {
4898 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4899 "setDisplayToSingleTaskInstance");
4900 final long origId = Binder.clearCallingIdentity();
4901 try {
4902 final ActivityDisplay display =
4903 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4904 if (display != null) {
4905 display.setDisplayToSingleTaskInstance();
4906 }
4907 } finally {
4908 Binder.restoreCallingIdentity(origId);
4909 }
4910 }
4911
Wale Ogunwale31913b52018-10-13 08:29:31 -07004912 void dumpLastANRLocked(PrintWriter pw) {
4913 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4914 if (mLastANRState == null) {
4915 pw.println(" <no ANR has occurred since boot>");
4916 } else {
4917 pw.println(mLastANRState);
4918 }
4919 }
4920
4921 void dumpLastANRTracesLocked(PrintWriter pw) {
4922 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4923
4924 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4925 if (ArrayUtils.isEmpty(files)) {
4926 pw.println(" <no ANR has occurred since boot>");
4927 return;
4928 }
4929 // Find the latest file.
4930 File latest = null;
4931 for (File f : files) {
4932 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4933 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004934 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 }
4936 pw.print("File: ");
4937 pw.print(latest.getName());
4938 pw.println();
4939 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4940 String line;
4941 while ((line = in.readLine()) != null) {
4942 pw.println(line);
4943 }
4944 } catch (IOException e) {
4945 pw.print("Unable to read: ");
4946 pw.print(e);
4947 pw.println();
4948 }
4949 }
4950
4951 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4952 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4953 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4954 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4955 }
4956
4957 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4958 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4959 pw.println(header);
4960
Wale Ogunwaled32da472018-11-16 07:19:28 -08004961 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 dumpPackage);
4963 boolean needSep = printedAnything;
4964
4965 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004966 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 " ResumedActivity: ");
4968 if (printed) {
4969 printedAnything = true;
4970 needSep = false;
4971 }
4972
4973 if (dumpPackage == null) {
4974 if (needSep) {
4975 pw.println();
4976 }
4977 printedAnything = true;
4978 mStackSupervisor.dump(pw, " ");
4979 }
4980
4981 if (!printedAnything) {
4982 pw.println(" (nothing)");
4983 }
4984 }
4985
4986 void dumpActivityContainersLocked(PrintWriter pw) {
4987 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004988 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004989 pw.println(" ");
4990 }
4991
4992 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4993 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4994 getActivityStartController().dump(pw, "", dumpPackage);
4995 }
4996
4997 /**
4998 * There are three things that cmd can be:
4999 * - a flattened component name that matches an existing activity
5000 * - the cmd arg isn't the flattened component name of an existing activity:
5001 * dump all activity whose component contains the cmd as a substring
5002 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005003 * <p>
5004 * The caller should not hold lock when calling this method because it will wait for the
5005 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005006 *
5007 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5008 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5009 */
5010 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5011 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5012 ArrayList<ActivityRecord> activities;
5013
5014 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005015 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005016 dumpFocusedStackOnly);
5017 }
5018
5019 if (activities.size() <= 0) {
5020 return false;
5021 }
5022
5023 String[] newArgs = new String[args.length - opti];
5024 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5025
5026 TaskRecord lastTask = null;
5027 boolean needSep = false;
5028 for (int i = activities.size() - 1; i >= 0; i--) {
5029 ActivityRecord r = activities.get(i);
5030 if (needSep) {
5031 pw.println();
5032 }
5033 needSep = true;
5034 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005035 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005036 if (lastTask != task) {
5037 lastTask = task;
5038 pw.print("TASK "); pw.print(lastTask.affinity);
5039 pw.print(" id="); pw.print(lastTask.taskId);
5040 pw.print(" userId="); pw.println(lastTask.userId);
5041 if (dumpAll) {
5042 lastTask.dump(pw, " ");
5043 }
5044 }
5045 }
5046 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5047 }
5048 return true;
5049 }
5050
5051 /**
5052 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5053 * there is a thread associated with the activity.
5054 */
5055 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5056 final ActivityRecord r, String[] args, boolean dumpAll) {
5057 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005058 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005059 synchronized (mGlobalLock) {
5060 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5061 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5062 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005063 if (r.hasProcess()) {
5064 pw.println(r.app.getPid());
5065 appThread = r.app.getThread();
5066 } else {
5067 pw.println("(not running)");
5068 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005069 if (dumpAll) {
5070 r.dump(pw, innerPrefix);
5071 }
5072 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005073 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 // flush anything that is already in the PrintWriter since the thread is going
5075 // to write to the file descriptor directly
5076 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005077 try (TransferPipe tp = new TransferPipe()) {
5078 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5079 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005080 } catch (IOException e) {
5081 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5082 } catch (RemoteException e) {
5083 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5084 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005085 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005086 }
5087
sanryhuang498e77e2018-12-06 14:57:01 +08005088 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5089 boolean testPssMode) {
5090 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5091 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5092 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005093 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005094 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5095 st.toString());
5096 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005097 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5098 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5099 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005100 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5101 testPssMode);
5102 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005103 }
5104
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 int getCurrentUserId() {
5106 return mAmInternal.getCurrentUserId();
5107 }
5108
5109 private void enforceNotIsolatedCaller(String caller) {
5110 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5111 throw new SecurityException("Isolated process not allowed to call " + caller);
5112 }
5113 }
5114
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 public Configuration getConfiguration() {
5116 Configuration ci;
5117 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005118 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005119 ci.userSetLocale = false;
5120 }
5121 return ci;
5122 }
5123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 /**
5125 * Current global configuration information. Contains general settings for the entire system,
5126 * also corresponds to the merged configuration of the default display.
5127 */
5128 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005129 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 }
5131
5132 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5133 boolean initLocale) {
5134 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5135 }
5136
5137 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5138 boolean initLocale, boolean deferResume) {
5139 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5140 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5141 UserHandle.USER_NULL, deferResume);
5142 }
5143
Wale Ogunwale59507092018-10-29 09:00:30 -07005144 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005145 final long origId = Binder.clearCallingIdentity();
5146 try {
5147 synchronized (mGlobalLock) {
5148 updateConfigurationLocked(values, null, false, true, userId,
5149 false /* deferResume */);
5150 }
5151 } finally {
5152 Binder.restoreCallingIdentity(origId);
5153 }
5154 }
5155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005156 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5157 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5158 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5159 deferResume, null /* result */);
5160 }
5161
5162 /**
5163 * Do either or both things: (1) change the current configuration, and (2)
5164 * make sure the given activity is running with the (now) current
5165 * configuration. Returns true if the activity has been left running, or
5166 * false if <var>starting</var> is being destroyed to match the new
5167 * configuration.
5168 *
5169 * @param userId is only used when persistent parameter is set to true to persist configuration
5170 * for that particular user
5171 */
5172 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5173 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5174 ActivityTaskManagerService.UpdateConfigurationResult result) {
5175 int changes = 0;
5176 boolean kept = true;
5177
5178 if (mWindowManager != null) {
5179 mWindowManager.deferSurfaceLayout();
5180 }
5181 try {
5182 if (values != null) {
5183 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5184 deferResume);
5185 }
5186
5187 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5188 } finally {
5189 if (mWindowManager != null) {
5190 mWindowManager.continueSurfaceLayout();
5191 }
5192 }
5193
5194 if (result != null) {
5195 result.changes = changes;
5196 result.activityRelaunched = !kept;
5197 }
5198 return kept;
5199 }
5200
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201 /** Update default (global) configuration and notify listeners about changes. */
5202 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5203 boolean persistent, int userId, boolean deferResume) {
5204 mTempConfig.setTo(getGlobalConfiguration());
5205 final int changes = mTempConfig.updateFrom(values);
5206 if (changes == 0) {
5207 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5208 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5209 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5210 // (even if there are no actual changes) to unfreeze the window.
5211 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5212 return 0;
5213 }
5214
5215 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5216 "Updating global configuration to: " + values);
5217
5218 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5219 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5220 values.colorMode,
5221 values.densityDpi,
5222 values.fontScale,
5223 values.hardKeyboardHidden,
5224 values.keyboard,
5225 values.keyboardHidden,
5226 values.mcc,
5227 values.mnc,
5228 values.navigation,
5229 values.navigationHidden,
5230 values.orientation,
5231 values.screenHeightDp,
5232 values.screenLayout,
5233 values.screenWidthDp,
5234 values.smallestScreenWidthDp,
5235 values.touchscreen,
5236 values.uiMode);
5237
5238
5239 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5240 final LocaleList locales = values.getLocales();
5241 int bestLocaleIndex = 0;
5242 if (locales.size() > 1) {
5243 if (mSupportedSystemLocales == null) {
5244 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5245 }
5246 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5247 }
5248 SystemProperties.set("persist.sys.locale",
5249 locales.get(bestLocaleIndex).toLanguageTag());
5250 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005251
5252 final Message m = PooledLambda.obtainMessage(
5253 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5254 locales.get(bestLocaleIndex));
5255 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256 }
5257
Yunfan Chen75157d72018-07-27 14:47:21 +09005258 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259
5260 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005261 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5264 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005265 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266
5267 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 AttributeCache ac = AttributeCache.instance();
5271 if (ac != null) {
5272 ac.updateConfiguration(mTempConfig);
5273 }
5274
5275 // Make sure all resources in our process are updated right now, so that anyone who is going
5276 // to retrieve resource values after we return will be sure to get the new ones. This is
5277 // especially important during boot, where the first config change needs to guarantee all
5278 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005279 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280
5281 // We need another copy of global config because we're scheduling some calls instead of
5282 // running them in place. We need to be sure that object we send will be handled unchanged.
5283 final Configuration configCopy = new Configuration(mTempConfig);
5284 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005285 final Message msg = PooledLambda.obtainMessage(
5286 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5287 this, userId, configCopy);
5288 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005291 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5292 for (int i = pidMap.size() - 1; i >= 0; i--) {
5293 final int pid = pidMap.keyAt(i);
5294 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005295 if (DEBUG_CONFIGURATION) {
5296 Slog.v(TAG_CONFIGURATION, "Update process config of "
5297 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005299 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300 }
5301
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005302 final Message msg = PooledLambda.obtainMessage(
5303 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5304 mAmInternal, changes, initLocale);
5305 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306
5307 // Override configuration of the default display duplicates global config, so we need to
5308 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005309 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005310 DEFAULT_DISPLAY);
5311
5312 return changes;
5313 }
5314
5315 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5316 boolean deferResume, int displayId) {
5317 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5318 displayId, null /* result */);
5319 }
5320
5321 /**
5322 * Updates override configuration specific for the selected display. If no config is provided,
5323 * new one will be computed in WM based on current display info.
5324 */
5325 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5326 ActivityRecord starting, boolean deferResume, int displayId,
5327 ActivityTaskManagerService.UpdateConfigurationResult result) {
5328 int changes = 0;
5329 boolean kept = true;
5330
5331 if (mWindowManager != null) {
5332 mWindowManager.deferSurfaceLayout();
5333 }
5334 try {
5335 if (values != null) {
5336 if (displayId == DEFAULT_DISPLAY) {
5337 // Override configuration of the default display duplicates global config, so
5338 // we're calling global config update instead for default display. It will also
5339 // apply the correct override config.
5340 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5341 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5342 } else {
5343 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5344 }
5345 }
5346
5347 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5348 } finally {
5349 if (mWindowManager != null) {
5350 mWindowManager.continueSurfaceLayout();
5351 }
5352 }
5353
5354 if (result != null) {
5355 result.changes = changes;
5356 result.activityRelaunched = !kept;
5357 }
5358 return kept;
5359 }
5360
5361 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5362 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005363 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364 final int changes = mTempConfig.updateFrom(values);
5365 if (changes != 0) {
5366 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5367 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005368 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369
5370 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5371 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005372 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005373
Wale Ogunwale5c918702018-10-18 11:06:33 -07005374 // Post message to start process to avoid possible deadlock of calling into AMS with
5375 // the ATMS lock held.
5376 final Message msg = PooledLambda.obtainMessage(
5377 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005378 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005379 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005380 }
5381 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382 return changes;
5383 }
5384
Wale Ogunwalef6733932018-06-27 05:14:34 -07005385 private void updateEventDispatchingLocked(boolean booted) {
5386 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5387 }
5388
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005389 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5390 final ContentResolver resolver = mContext.getContentResolver();
5391 Settings.System.putConfigurationForUser(resolver, config, userId);
5392 }
5393
5394 private void sendLocaleToMountDaemonMsg(Locale l) {
5395 try {
5396 IBinder service = ServiceManager.getService("mount");
5397 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5398 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5399 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5400 } catch (RemoteException e) {
5401 Log.e(TAG, "Error storing locale for decryption UI", e);
5402 }
5403 }
5404
Alison Cichowlas3e340502018-08-07 17:15:01 -04005405 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5406 mStartActivitySources.remove(permissionToken);
5407 mExpiredStartAsCallerTokens.add(permissionToken);
5408 }
5409
5410 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5411 mExpiredStartAsCallerTokens.remove(permissionToken);
5412 }
5413
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005414 boolean isActivityStartsLoggingEnabled() {
5415 return mAmInternal.isActivityStartsLoggingEnabled();
5416 }
5417
Michal Karpinski8596ded2018-11-14 14:43:48 +00005418 boolean isBackgroundActivityStartsEnabled() {
5419 return mAmInternal.isBackgroundActivityStartsEnabled();
5420 }
5421
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 void enableScreenAfterBoot(boolean booted) {
5423 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5424 SystemClock.uptimeMillis());
5425 mWindowManager.enableScreenAfterBoot();
5426
5427 synchronized (mGlobalLock) {
5428 updateEventDispatchingLocked(booted);
5429 }
5430 }
5431
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005432 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5433 if (r == null || !r.hasProcess()) {
5434 return KEY_DISPATCHING_TIMEOUT_MS;
5435 }
5436 return getInputDispatchingTimeoutLocked(r.app);
5437 }
5438
5439 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005440 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005441 }
5442
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 /**
5444 * Decide based on the configuration whether we should show the ANR,
5445 * crash, etc dialogs. The idea is that if there is no affordance to
5446 * press the on-screen buttons, or the user experience would be more
5447 * greatly impacted than the crash itself, we shouldn't show the dialog.
5448 *
5449 * A thought: SystemUI might also want to get told about this, the Power
5450 * dialog / global actions also might want different behaviors.
5451 */
5452 private void updateShouldShowDialogsLocked(Configuration config) {
5453 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5454 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5455 && config.navigation == Configuration.NAVIGATION_NONAV);
5456 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5457 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5458 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5459 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5460 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5461 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5462 HIDE_ERROR_DIALOGS, 0) != 0;
5463 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5464 }
5465
5466 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5467 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5468 FONT_SCALE, 1.0f, userId);
5469
5470 synchronized (this) {
5471 if (getGlobalConfiguration().fontScale == scaleFactor) {
5472 return;
5473 }
5474
5475 final Configuration configuration
5476 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5477 configuration.fontScale = scaleFactor;
5478 updatePersistentConfiguration(configuration, userId);
5479 }
5480 }
5481
5482 // Actually is sleeping or shutting down or whatever else in the future
5483 // is an inactive state.
5484 boolean isSleepingOrShuttingDownLocked() {
5485 return isSleepingLocked() || mShuttingDown;
5486 }
5487
5488 boolean isSleepingLocked() {
5489 return mSleeping;
5490 }
5491
Riddle Hsu16567132018-08-16 21:37:47 +08005492 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005494 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 if (task.isActivityTypeStandard()) {
5496 if (mCurAppTimeTracker != r.appTimeTracker) {
5497 // We are switching app tracking. Complete the current one.
5498 if (mCurAppTimeTracker != null) {
5499 mCurAppTimeTracker.stop();
5500 mH.obtainMessage(
5501 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005502 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 mCurAppTimeTracker = null;
5504 }
5505 if (r.appTimeTracker != null) {
5506 mCurAppTimeTracker = r.appTimeTracker;
5507 startTimeTrackingFocusedActivityLocked();
5508 }
5509 } else {
5510 startTimeTrackingFocusedActivityLocked();
5511 }
5512 } else {
5513 r.appTimeTracker = null;
5514 }
5515 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5516 // TODO: Probably not, because we don't want to resume voice on switching
5517 // back to this activity
5518 if (task.voiceInteractor != null) {
5519 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5520 } else {
5521 finishRunningVoiceLocked();
5522
5523 if (mLastResumedActivity != null) {
5524 final IVoiceInteractionSession session;
5525
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005526 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 if (lastResumedActivityTask != null
5528 && lastResumedActivityTask.voiceSession != null) {
5529 session = lastResumedActivityTask.voiceSession;
5530 } else {
5531 session = mLastResumedActivity.voiceSession;
5532 }
5533
5534 if (session != null) {
5535 // We had been in a voice interaction session, but now focused has
5536 // move to something different. Just finish the session, we can't
5537 // return to it and retain the proper state and synchronization with
5538 // the voice interaction service.
5539 finishVoiceTask(session);
5540 }
5541 }
5542 }
5543
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005544 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5545 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 }
5547 updateResumedAppTrace(r);
5548 mLastResumedActivity = r;
5549
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005550 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551
5552 applyUpdateLockStateLocked(r);
5553 applyUpdateVrModeLocked(r);
5554
5555 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005556 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 r == null ? "NULL" : r.shortComponentName,
5558 reason);
5559 }
5560
5561 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5562 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005563 final ActivityTaskManagerInternal.SleepToken token =
5564 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005565 updateSleepIfNeededLocked();
5566 return token;
5567 }
5568 }
5569
5570 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005571 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 final boolean wasSleeping = mSleeping;
5573 boolean updateOomAdj = false;
5574
5575 if (!shouldSleep) {
5576 // If wasSleeping is true, we need to wake up activity manager state from when
5577 // we started sleeping. In either case, we need to apply the sleep tokens, which
5578 // will wake up stacks or put them to sleep as appropriate.
5579 if (wasSleeping) {
5580 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005581 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5582 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005583 startTimeTrackingFocusedActivityLocked();
5584 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005585 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5587 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005588 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 if (wasSleeping) {
5590 updateOomAdj = true;
5591 }
5592 } else if (!mSleeping && shouldSleep) {
5593 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005594 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5595 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596 if (mCurAppTimeTracker != null) {
5597 mCurAppTimeTracker.stop();
5598 }
5599 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005600 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 mStackSupervisor.goingToSleepLocked();
5602 updateResumedAppTrace(null /* resumed */);
5603 updateOomAdj = true;
5604 }
5605 if (updateOomAdj) {
5606 mH.post(mAmInternal::updateOomAdj);
5607 }
5608 }
5609
5610 void updateOomAdj() {
5611 mH.post(mAmInternal::updateOomAdj);
5612 }
5613
Wale Ogunwale53783742018-09-16 10:21:51 -07005614 void updateCpuStats() {
5615 mH.post(mAmInternal::updateCpuStats);
5616 }
5617
Hui Yu03d12402018-12-06 18:00:37 -08005618 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5619 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005620 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5621 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005622 mH.sendMessage(m);
5623 }
5624
Hui Yu03d12402018-12-06 18:00:37 -08005625 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005626 ComponentName taskRoot = null;
5627 final TaskRecord task = activity.getTaskRecord();
5628 if (task != null) {
5629 final ActivityRecord rootActivity = task.getRootActivity();
5630 if (rootActivity != null) {
5631 taskRoot = rootActivity.mActivityComponent;
5632 }
5633 }
5634
Hui Yu03d12402018-12-06 18:00:37 -08005635 final Message m = PooledLambda.obtainMessage(
5636 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005637 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005638 mH.sendMessage(m);
5639 }
5640
Wale Ogunwale53783742018-09-16 10:21:51 -07005641 void setBooting(boolean booting) {
5642 mAmInternal.setBooting(booting);
5643 }
5644
5645 boolean isBooting() {
5646 return mAmInternal.isBooting();
5647 }
5648
5649 void setBooted(boolean booted) {
5650 mAmInternal.setBooted(booted);
5651 }
5652
5653 boolean isBooted() {
5654 return mAmInternal.isBooted();
5655 }
5656
5657 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5658 mH.post(() -> {
5659 if (finishBooting) {
5660 mAmInternal.finishBooting();
5661 }
5662 if (enableScreen) {
5663 mInternal.enableScreenAfterBoot(isBooted());
5664 }
5665 });
5666 }
5667
5668 void setHeavyWeightProcess(ActivityRecord root) {
5669 mHeavyWeightProcess = root.app;
5670 final Message m = PooledLambda.obtainMessage(
5671 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005672 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005673 mH.sendMessage(m);
5674 }
5675
5676 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5677 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5678 return;
5679 }
5680
5681 mHeavyWeightProcess = null;
5682 final Message m = PooledLambda.obtainMessage(
5683 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5684 proc.mUserId);
5685 mH.sendMessage(m);
5686 }
5687
5688 private void cancelHeavyWeightProcessNotification(int userId) {
5689 final INotificationManager inm = NotificationManager.getService();
5690 if (inm == null) {
5691 return;
5692 }
5693 try {
5694 inm.cancelNotificationWithTag("android", null,
5695 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5696 } catch (RuntimeException e) {
5697 Slog.w(TAG, "Error canceling notification for service", e);
5698 } catch (RemoteException e) {
5699 }
5700
5701 }
5702
5703 private void postHeavyWeightProcessNotification(
5704 WindowProcessController proc, Intent intent, int userId) {
5705 if (proc == null) {
5706 return;
5707 }
5708
5709 final INotificationManager inm = NotificationManager.getService();
5710 if (inm == null) {
5711 return;
5712 }
5713
5714 try {
5715 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5716 String text = mContext.getString(R.string.heavy_weight_notification,
5717 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5718 Notification notification =
5719 new Notification.Builder(context,
5720 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5721 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5722 .setWhen(0)
5723 .setOngoing(true)
5724 .setTicker(text)
5725 .setColor(mContext.getColor(
5726 com.android.internal.R.color.system_notification_accent_color))
5727 .setContentTitle(text)
5728 .setContentText(
5729 mContext.getText(R.string.heavy_weight_notification_detail))
5730 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5731 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5732 new UserHandle(userId)))
5733 .build();
5734 try {
5735 inm.enqueueNotificationWithTag("android", "android", null,
5736 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5737 } catch (RuntimeException e) {
5738 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5739 } catch (RemoteException e) {
5740 }
5741 } catch (PackageManager.NameNotFoundException e) {
5742 Slog.w(TAG, "Unable to create context for heavy notification", e);
5743 }
5744
5745 }
5746
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005747 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5748 IBinder token, String resultWho, int requestCode, Intent[] intents,
5749 String[] resolvedTypes, int flags, Bundle bOptions) {
5750
5751 ActivityRecord activity = null;
5752 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5753 activity = ActivityRecord.isInStackLocked(token);
5754 if (activity == null) {
5755 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5756 return null;
5757 }
5758 if (activity.finishing) {
5759 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5760 return null;
5761 }
5762 }
5763
5764 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5765 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5766 bOptions);
5767 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5768 if (noCreate) {
5769 return rec;
5770 }
5771 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5772 if (activity.pendingResults == null) {
5773 activity.pendingResults = new HashSet<>();
5774 }
5775 activity.pendingResults.add(rec.ref);
5776 }
5777 return rec;
5778 }
5779
Andrii Kulian52d255c2018-07-13 11:32:19 -07005780 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005781 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005782 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005783 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5784 mCurAppTimeTracker.start(resumedActivity.packageName);
5785 }
5786 }
5787
5788 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5789 if (mTracedResumedActivity != null) {
5790 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5791 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5792 }
5793 if (resumed != null) {
5794 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5795 constructResumedTraceName(resumed.packageName), 0);
5796 }
5797 mTracedResumedActivity = resumed;
5798 }
5799
5800 private String constructResumedTraceName(String packageName) {
5801 return "focused app: " + packageName;
5802 }
5803
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005804 /** Applies latest configuration and/or visibility updates if needed. */
5805 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5806 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005807 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005808 // mainStack is null during startup.
5809 if (mainStack != null) {
5810 if (changes != 0 && starting == null) {
5811 // If the configuration changed, and the caller is not already
5812 // in the process of starting an activity, then find the top
5813 // activity to check if its configuration needs to change.
5814 starting = mainStack.topRunningActivityLocked();
5815 }
5816
5817 if (starting != null) {
5818 kept = starting.ensureActivityConfiguration(changes,
5819 false /* preserveWindow */);
5820 // And we need to make sure at this point that all other activities
5821 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005822 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005823 !PRESERVE_WINDOWS);
5824 }
5825 }
5826
5827 return kept;
5828 }
5829
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005830 void scheduleAppGcsLocked() {
5831 mH.post(() -> mAmInternal.scheduleAppGcs());
5832 }
5833
Wale Ogunwale53783742018-09-16 10:21:51 -07005834 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5835 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5836 }
5837
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005838 /**
5839 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5840 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5841 * on demand.
5842 */
5843 IPackageManager getPackageManager() {
5844 return AppGlobals.getPackageManager();
5845 }
5846
5847 PackageManagerInternal getPackageManagerInternalLocked() {
5848 if (mPmInternal == null) {
5849 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5850 }
5851 return mPmInternal;
5852 }
5853
Hai Zhangf4da9be2019-05-01 13:46:06 +08005854 PermissionPolicyInternal getPermissionPolicyInternal() {
5855 if (mPermissionPolicyInternal == null) {
5856 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5857 }
5858 return mPermissionPolicyInternal;
5859 }
5860
Wale Ogunwale008163e2018-07-23 23:11:08 -07005861 AppWarnings getAppWarningsLocked() {
5862 return mAppWarnings;
5863 }
5864
Wale Ogunwale214f3482018-10-04 11:00:47 -07005865 Intent getHomeIntent() {
5866 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5867 intent.setComponent(mTopComponent);
5868 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5869 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5870 intent.addCategory(Intent.CATEGORY_HOME);
5871 }
5872 return intent;
5873 }
5874
Chilun2ef71f72018-11-16 17:57:15 +08005875 /**
5876 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5877 * activities.
5878 *
5879 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5880 * component defined in config_secondaryHomeComponent.
5881 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5882 */
5883 Intent getSecondaryHomeIntent(String preferredPackage) {
5884 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005885 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5886 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5887 if (preferredPackage == null || useSystemProvidedLauncher) {
5888 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005889 final String secondaryHomeComponent = mContext.getResources().getString(
5890 com.android.internal.R.string.config_secondaryHomeComponent);
5891 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5892 } else {
5893 intent.setPackage(preferredPackage);
5894 }
5895 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5896 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5897 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5898 }
5899 return intent;
5900 }
5901
Wale Ogunwale214f3482018-10-04 11:00:47 -07005902 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5903 if (info == null) return null;
5904 ApplicationInfo newInfo = new ApplicationInfo(info);
5905 newInfo.initForUser(userId);
5906 return newInfo;
5907 }
5908
Wale Ogunwale9c103022018-10-18 07:44:54 -07005909 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005910 if (uid == SYSTEM_UID) {
5911 // The system gets to run in any process. If there are multiple processes with the same
5912 // uid, just pick the first (this should never happen).
5913 final SparseArray<WindowProcessController> procs =
5914 mProcessNames.getMap().get(processName);
5915 if (procs == null) return null;
5916 final int procCount = procs.size();
5917 for (int i = 0; i < procCount; i++) {
5918 final int procUid = procs.keyAt(i);
5919 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5920 // Don't use an app process or different user process for system component.
5921 continue;
5922 }
5923 return procs.valueAt(i);
5924 }
5925 }
5926
5927 return mProcessNames.get(processName, uid);
5928 }
5929
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005930 WindowProcessController getProcessController(IApplicationThread thread) {
5931 if (thread == null) {
5932 return null;
5933 }
5934
5935 final IBinder threadBinder = thread.asBinder();
5936 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5937 for (int i = pmap.size()-1; i >= 0; i--) {
5938 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5939 for (int j = procs.size() - 1; j >= 0; j--) {
5940 final WindowProcessController proc = procs.valueAt(j);
5941 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5942 return proc;
5943 }
5944 }
5945 }
5946
5947 return null;
5948 }
5949
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005950 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005951 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005952 if (proc == null) return null;
5953 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5954 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005955 }
5956 return null;
5957 }
5958
Riddle Hsua0536432019-02-16 00:38:59 +08005959 int getUidState(int uid) {
5960 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005961 }
5962
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005963 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005964 // A uid is considered to be foreground if it has a visible non-toast window.
5965 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005966 }
5967
Ricky Wai96f5c352019-04-10 18:40:17 +01005968 boolean isDeviceOwner(int uid) {
5969 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005970 }
5971
Ricky Wai96f5c352019-04-10 18:40:17 +01005972 void setDeviceOwnerUid(int uid) {
5973 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005974 }
5975
Wale Ogunwale9de19442018-10-18 19:05:03 -07005976 /**
5977 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5978 * the whitelist
5979 */
5980 String getPendingTempWhitelistTagForUidLocked(int uid) {
5981 return mPendingTempWhitelist.get(uid);
5982 }
5983
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005984 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5985 if (true || Build.IS_USER) {
5986 return;
5987 }
5988
5989 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5990 StrictMode.allowThreadDiskWrites();
5991 try {
5992 File tracesDir = new File("/data/anr");
5993 File tracesFile = null;
5994 try {
5995 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5996
5997 StringBuilder sb = new StringBuilder();
5998 Time tobj = new Time();
5999 tobj.set(System.currentTimeMillis());
6000 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
6001 sb.append(": ");
6002 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6003 sb.append(" since ");
6004 sb.append(msg);
6005 FileOutputStream fos = new FileOutputStream(tracesFile);
6006 fos.write(sb.toString().getBytes());
6007 if (app == null) {
6008 fos.write("\n*** No application process!".getBytes());
6009 }
6010 fos.close();
6011 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6012 } catch (IOException e) {
6013 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6014 return;
6015 }
6016
6017 if (app != null && app.getPid() > 0) {
6018 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6019 firstPids.add(app.getPid());
6020 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6021 }
6022
6023 File lastTracesFile = null;
6024 File curTracesFile = null;
6025 for (int i=9; i>=0; i--) {
6026 String name = String.format(Locale.US, "slow%02d.txt", i);
6027 curTracesFile = new File(tracesDir, name);
6028 if (curTracesFile.exists()) {
6029 if (lastTracesFile != null) {
6030 curTracesFile.renameTo(lastTracesFile);
6031 } else {
6032 curTracesFile.delete();
6033 }
6034 }
6035 lastTracesFile = curTracesFile;
6036 }
6037 tracesFile.renameTo(curTracesFile);
6038 } finally {
6039 StrictMode.setThreadPolicy(oldPolicy);
6040 }
6041 }
6042
Michal Karpinskida34cd42019-04-02 19:46:52 +01006043 boolean isAssociatedCompanionApp(int userId, int uid) {
6044 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6045 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006046 return false;
6047 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006048 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006049 }
6050
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006051 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006052 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006053
6054
Wale Ogunwale98875612018-10-12 07:53:02 -07006055 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6056 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057
Riddle Hsud93a6c42018-11-29 21:50:06 +08006058 H(Looper looper) {
6059 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006060 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006061
6062 @Override
6063 public void handleMessage(Message msg) {
6064 switch (msg.what) {
6065 case REPORT_TIME_TRACKER_MSG: {
6066 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6067 tracker.deliverResult(mContext);
6068 } break;
6069 }
6070 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006071 }
6072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006073 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006074 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006075
6076 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006077 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006078 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079
6080 @Override
6081 public void handleMessage(Message msg) {
6082 switch (msg.what) {
6083 case DISMISS_DIALOG_UI_MSG: {
6084 final Dialog d = (Dialog) msg.obj;
6085 d.dismiss();
6086 break;
6087 }
6088 }
6089 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006090 }
6091
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006092 final class LocalService extends ActivityTaskManagerInternal {
6093 @Override
6094 public SleepToken acquireSleepToken(String tag, int displayId) {
6095 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006096 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006097 }
6098
6099 @Override
6100 public ComponentName getHomeActivityForUser(int userId) {
6101 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006102 final ActivityRecord homeActivity =
6103 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006104 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006105 }
6106 }
6107
6108 @Override
6109 public void onLocalVoiceInteractionStarted(IBinder activity,
6110 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6111 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006112 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006113 }
6114 }
6115
6116 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006117 public void notifyAppTransitionStarting(SparseIntArray reasons,
6118 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 synchronized (mGlobalLock) {
6120 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6121 reasons, timestamp);
6122 }
6123 }
6124
6125 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006126 public void notifySingleTaskDisplayDrawn(int displayId) {
6127 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6128 }
6129
6130 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 public void notifyAppTransitionFinished() {
6132 synchronized (mGlobalLock) {
6133 mStackSupervisor.notifyAppTransitionDone();
6134 }
6135 }
6136
6137 @Override
6138 public void notifyAppTransitionCancelled() {
6139 synchronized (mGlobalLock) {
6140 mStackSupervisor.notifyAppTransitionDone();
6141 }
6142 }
6143
6144 @Override
6145 public List<IBinder> getTopVisibleActivities() {
6146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006147 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150
6151 @Override
6152 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6153 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006154 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 }
6156 }
6157
6158 @Override
6159 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6160 Bundle bOptions) {
6161 Preconditions.checkNotNull(intents, "intents");
6162 final String[] resolvedTypes = new String[intents.length];
6163
6164 // UID of the package on user userId.
6165 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6166 // packageUid may not be initialized.
6167 int packageUid = 0;
6168 final long ident = Binder.clearCallingIdentity();
6169
6170 try {
6171 for (int i = 0; i < intents.length; i++) {
6172 resolvedTypes[i] =
6173 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6174 }
6175
6176 packageUid = AppGlobals.getPackageManager().getPackageUid(
6177 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6178 } catch (RemoteException e) {
6179 // Shouldn't happen.
6180 } finally {
6181 Binder.restoreCallingIdentity(ident);
6182 }
6183
Riddle Hsu591bf612019-02-14 17:55:31 +08006184 return getActivityStartController().startActivitiesInPackage(
6185 packageUid, packageName,
6186 intents, resolvedTypes, null /* resultTo */,
6187 SafeActivityOptions.fromBundle(bOptions), userId,
6188 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6189 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 }
6191
6192 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006193 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6194 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6195 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6196 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006197 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006198 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006199 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6200 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6201 userId, validateIncomingUser, originatingPendingIntent,
6202 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006203 }
6204 }
6205
6206 @Override
6207 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6208 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6209 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6210 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006211 PendingIntentRecord originatingPendingIntent,
6212 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006213 synchronized (mGlobalLock) {
6214 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6215 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6216 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006217 validateIncomingUser, originatingPendingIntent,
6218 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006219 }
6220 }
6221
6222 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6224 Intent intent, Bundle options, int userId) {
6225 return ActivityTaskManagerService.this.startActivityAsUser(
6226 caller, callerPacakge, intent,
6227 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6228 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6229 false /*validateIncomingUser*/);
6230 }
6231
6232 @Override
lumark588a3e82018-07-20 18:53:54 +08006233 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 synchronized (mGlobalLock) {
6235
6236 // We might change the visibilities here, so prepare an empty app transition which
6237 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006238 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006239 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006240 if (activityDisplay == null) {
6241 return;
6242 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006243 final DisplayContent dc = activityDisplay.mDisplayContent;
6244 final boolean wasTransitionSet =
6245 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006246 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006247 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006249 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250
6251 // If there was a transition set already we don't want to interfere with it as we
6252 // might be starting it too early.
6253 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006254 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 }
6256 }
6257 if (callback != null) {
6258 callback.run();
6259 }
6260 }
6261
6262 @Override
6263 public void notifyKeyguardTrustedChanged() {
6264 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006265 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006266 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 }
6268 }
6269 }
6270
6271 /**
6272 * Called after virtual display Id is updated by
6273 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6274 * {@param vrVr2dDisplayId}.
6275 */
6276 @Override
6277 public void setVr2dDisplayId(int vr2dDisplayId) {
6278 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6279 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006280 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282 }
6283
6284 @Override
6285 public void setFocusedActivity(IBinder token) {
6286 synchronized (mGlobalLock) {
6287 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6288 if (r == null) {
6289 throw new IllegalArgumentException(
6290 "setFocusedActivity: No activity record matching token=" + token);
6291 }
Louis Chang19443452018-10-09 12:10:21 +08006292 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006293 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 }
6295 }
6296 }
6297
6298 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006300 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
6302
6303 @Override
6304 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006305 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 }
6307
6308 @Override
6309 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006310 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006311 }
6312
6313 @Override
6314 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6315 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6316 }
6317
6318 @Override
6319 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006320 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006321 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006322
6323 @Override
6324 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6325 synchronized (mGlobalLock) {
6326 mActiveVoiceInteractionServiceComponent = component;
6327 }
6328 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006329
6330 @Override
6331 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6332 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6333 return;
6334 }
6335 synchronized (mGlobalLock) {
6336 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6337 if (types == null) {
6338 if (uid < 0) {
6339 return;
6340 }
6341 types = new ArrayMap<>();
6342 mAllowAppSwitchUids.put(userId, types);
6343 }
6344 if (uid < 0) {
6345 types.remove(type);
6346 } else {
6347 types.put(type, uid);
6348 }
6349 }
6350 }
6351
6352 @Override
6353 public void onUserStopped(int userId) {
6354 synchronized (mGlobalLock) {
6355 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6356 mAllowAppSwitchUids.remove(userId);
6357 }
6358 }
6359
6360 @Override
6361 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6362 synchronized (mGlobalLock) {
6363 return ActivityTaskManagerService.this.isGetTasksAllowed(
6364 caller, callingPid, callingUid);
6365 }
6366 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006367
Riddle Hsua0536432019-02-16 00:38:59 +08006368 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006369 @Override
6370 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006371 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006372 mProcessNames.put(proc.mName, proc.mUid, proc);
6373 }
6374 }
6375
Riddle Hsua0536432019-02-16 00:38:59 +08006376 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006377 @Override
6378 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006379 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006380 mProcessNames.remove(name, uid);
6381 }
6382 }
6383
Riddle Hsua0536432019-02-16 00:38:59 +08006384 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006385 @Override
6386 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006387 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006388 if (proc == mHomeProcess) {
6389 mHomeProcess = null;
6390 }
6391 if (proc == mPreviousProcess) {
6392 mPreviousProcess = null;
6393 }
6394 }
6395 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006396
Riddle Hsua0536432019-02-16 00:38:59 +08006397 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006398 @Override
6399 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006400 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006401 return mTopProcessState;
6402 }
6403 }
6404
Riddle Hsua0536432019-02-16 00:38:59 +08006405 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006406 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006407 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006408 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006409 return proc == mHeavyWeightProcess;
6410 }
6411 }
6412
Riddle Hsua0536432019-02-16 00:38:59 +08006413 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006414 @Override
6415 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006416 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006417 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6418 }
6419 }
6420
6421 @Override
6422 public void finishHeavyWeightApp() {
6423 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006424 if (mHeavyWeightProcess != null) {
6425 mHeavyWeightProcess.finishActivities();
6426 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006427 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6428 mHeavyWeightProcess);
6429 }
6430 }
6431
Riddle Hsua0536432019-02-16 00:38:59 +08006432 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006433 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006434 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006435 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006436 return isSleepingLocked();
6437 }
6438 }
6439
6440 @Override
6441 public boolean isShuttingDown() {
6442 synchronized (mGlobalLock) {
6443 return mShuttingDown;
6444 }
6445 }
6446
6447 @Override
6448 public boolean shuttingDown(boolean booted, int timeout) {
6449 synchronized (mGlobalLock) {
6450 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006451 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006452 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006453 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006454 return mStackSupervisor.shutdownLocked(timeout);
6455 }
6456 }
6457
6458 @Override
6459 public void enableScreenAfterBoot(boolean booted) {
6460 synchronized (mGlobalLock) {
6461 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6462 SystemClock.uptimeMillis());
6463 mWindowManager.enableScreenAfterBoot();
6464 updateEventDispatchingLocked(booted);
6465 }
6466 }
6467
6468 @Override
6469 public boolean showStrictModeViolationDialog() {
6470 synchronized (mGlobalLock) {
6471 return mShowDialogs && !mSleeping && !mShuttingDown;
6472 }
6473 }
6474
6475 @Override
6476 public void showSystemReadyErrorDialogsIfNeeded() {
6477 synchronized (mGlobalLock) {
6478 try {
6479 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6480 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6481 + " data partition or your device will be unstable.");
6482 mUiHandler.post(() -> {
6483 if (mShowDialogs) {
6484 AlertDialog d = new BaseErrorDialog(mUiContext);
6485 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6486 d.setCancelable(false);
6487 d.setTitle(mUiContext.getText(R.string.android_system_label));
6488 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6489 d.setButton(DialogInterface.BUTTON_POSITIVE,
6490 mUiContext.getText(R.string.ok),
6491 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6492 d.show();
6493 }
6494 });
6495 }
6496 } catch (RemoteException e) {
6497 }
6498
6499 if (!Build.isBuildConsistent()) {
6500 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6501 mUiHandler.post(() -> {
6502 if (mShowDialogs) {
6503 AlertDialog d = new BaseErrorDialog(mUiContext);
6504 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6505 d.setCancelable(false);
6506 d.setTitle(mUiContext.getText(R.string.android_system_label));
6507 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6508 d.setButton(DialogInterface.BUTTON_POSITIVE,
6509 mUiContext.getText(R.string.ok),
6510 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6511 d.show();
6512 }
6513 });
6514 }
6515 }
6516 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006517
6518 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006519 public void onProcessMapped(int pid, WindowProcessController proc) {
6520 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006522 }
6523 }
6524
6525 @Override
6526 public void onProcessUnMapped(int pid) {
6527 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006528 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006529 }
6530 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006531
6532 @Override
6533 public void onPackageDataCleared(String name) {
6534 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006535 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006536 mAppWarnings.onPackageDataCleared(name);
6537 }
6538 }
6539
6540 @Override
6541 public void onPackageUninstalled(String name) {
6542 synchronized (mGlobalLock) {
6543 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006544 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006545 }
6546 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006547
6548 @Override
6549 public void onPackageAdded(String name, boolean replacing) {
6550 synchronized (mGlobalLock) {
6551 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6552 }
6553 }
6554
6555 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006556 public void onPackageReplaced(ApplicationInfo aInfo) {
6557 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006558 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006559 }
6560 }
6561
6562 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006563 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6564 synchronized (mGlobalLock) {
6565 return compatibilityInfoForPackageLocked(ai);
6566 }
6567 }
6568
Yunfan Chen75157d72018-07-27 14:47:21 +09006569 /**
6570 * Set the corresponding display information for the process global configuration. To be
6571 * called when we need to show IME on a different display.
6572 *
6573 * @param pid The process id associated with the IME window.
6574 * @param displayId The ID of the display showing the IME.
6575 */
6576 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006577 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006578 // Don't update process-level configuration for Multi-Client IME process since other
6579 // IMEs on other displays will also receive this configuration change due to IME
6580 // services use the same application config/context.
6581 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006582
Yunfan Chen75157d72018-07-27 14:47:21 +09006583 if (pid == MY_PID || pid < 0) {
6584 if (DEBUG_CONFIGURATION) {
6585 Slog.w(TAG,
6586 "Trying to update display configuration for system/invalid process.");
6587 }
6588 return;
6589 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006590 synchronized (mGlobalLock) {
6591 final ActivityDisplay activityDisplay =
6592 mRootActivityContainer.getActivityDisplay(displayId);
6593 if (activityDisplay == null) {
6594 // Call might come when display is not yet added or has been removed.
6595 if (DEBUG_CONFIGURATION) {
6596 Slog.w(TAG, "Trying to update display configuration for non-existing "
6597 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006598 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006599 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006600 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006601 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006602 if (process == null) {
6603 if (DEBUG_CONFIGURATION) {
6604 Slog.w(TAG, "Trying to update display configuration for invalid "
6605 + "process, pid=" + pid);
6606 }
6607 return;
6608 }
6609 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6610 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006611 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006612
6613 @Override
6614 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006615 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006616 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006617 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6618 if (r != null && r.getActivityStack() != null) {
6619 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6620 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006621 }
6622 }
6623 }
6624
6625 @Override
6626 public void clearPendingResultForActivity(IBinder activityToken,
6627 WeakReference<PendingIntentRecord> pir) {
6628 synchronized (mGlobalLock) {
6629 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6630 if (r != null && r.pendingResults != null) {
6631 r.pendingResults.remove(pir);
6632 }
6633 }
6634 }
6635
6636 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006637 public ActivityTokens getTopActivityForTask(int taskId) {
6638 synchronized (mGlobalLock) {
6639 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6640 if (taskRecord == null) {
6641 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6642 + " Requested task not found");
6643 return null;
6644 }
6645 final ActivityRecord activity = taskRecord.getTopActivity();
6646 if (activity == null) {
6647 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6648 + " Requested activity not found");
6649 return null;
6650 }
6651 if (!activity.attachedToProcess()) {
6652 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6653 + activity);
6654 return null;
6655 }
6656 return new ActivityTokens(activity.appToken, activity.assistToken,
6657 activity.app.getThread());
6658 }
6659 }
6660
6661 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006662 public IIntentSender getIntentSender(int type, String packageName,
6663 int callingUid, int userId, IBinder token, String resultWho,
6664 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6665 Bundle bOptions) {
6666 synchronized (mGlobalLock) {
6667 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6668 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6669 }
6670 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006671
6672 @Override
6673 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6674 synchronized (mGlobalLock) {
6675 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6676 if (r == null) {
6677 return null;
6678 }
6679 if (r.mServiceConnectionsHolder == null) {
6680 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6681 ActivityTaskManagerService.this, r);
6682 }
6683
6684 return r.mServiceConnectionsHolder;
6685 }
6686 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006687
6688 @Override
6689 public Intent getHomeIntent() {
6690 synchronized (mGlobalLock) {
6691 return ActivityTaskManagerService.this.getHomeIntent();
6692 }
6693 }
6694
6695 @Override
6696 public boolean startHomeActivity(int userId, String reason) {
6697 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006698 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006699 }
6700 }
6701
6702 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006703 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006704 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006705 synchronized (mGlobalLock) {
6706 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006707 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006708 }
Chilun8b1f1be2019-03-13 17:14:36 +08006709 }
6710
6711 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006712 public boolean startHomeOnAllDisplays(int userId, String reason) {
6713 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006714 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715 }
6716 }
6717
Riddle Hsua0536432019-02-16 00:38:59 +08006718 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006719 @Override
6720 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006721 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006722 if (mFactoryTest == FACTORY_TEST_OFF) {
6723 return false;
6724 }
6725 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6726 && wpc.mName.equals(mTopComponent.getPackageName())) {
6727 return true;
6728 }
6729 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6730 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6731 }
6732 }
6733
6734 @Override
6735 public void updateTopComponentForFactoryTest() {
6736 synchronized (mGlobalLock) {
6737 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6738 return;
6739 }
6740 final ResolveInfo ri = mContext.getPackageManager()
6741 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6742 final CharSequence errorMsg;
6743 if (ri != null) {
6744 final ActivityInfo ai = ri.activityInfo;
6745 final ApplicationInfo app = ai.applicationInfo;
6746 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6747 mTopAction = Intent.ACTION_FACTORY_TEST;
6748 mTopData = null;
6749 mTopComponent = new ComponentName(app.packageName, ai.name);
6750 errorMsg = null;
6751 } else {
6752 errorMsg = mContext.getResources().getText(
6753 com.android.internal.R.string.factorytest_not_system);
6754 }
6755 } else {
6756 errorMsg = mContext.getResources().getText(
6757 com.android.internal.R.string.factorytest_no_action);
6758 }
6759 if (errorMsg == null) {
6760 return;
6761 }
6762
6763 mTopAction = null;
6764 mTopData = null;
6765 mTopComponent = null;
6766 mUiHandler.post(() -> {
6767 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6768 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006769 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006770 });
6771 }
6772 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773
Riddle Hsua0536432019-02-16 00:38:59 +08006774 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 @Override
6776 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6777 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006778 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006780 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781
6782 wpc.clearRecentTasks();
6783 wpc.clearActivities();
6784
6785 if (wpc.isInstrumenting()) {
6786 finishInstrumentationCallback.run();
6787 }
6788
Jorim Jaggid0752812018-10-16 16:07:20 +02006789 if (!restarting && hasVisibleActivities) {
6790 mWindowManager.deferSurfaceLayout();
6791 try {
6792 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6793 // If there was nothing to resume, and we are not already restarting
6794 // this process, but there is a visible activity that is hosted by the
6795 // process...then make sure all visible activities are running, taking
6796 // care of restarting this process.
6797 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6798 !PRESERVE_WINDOWS);
6799 }
6800 } finally {
6801 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 }
6804 }
6805 }
6806
6807 @Override
6808 public void closeSystemDialogs(String reason) {
6809 enforceNotIsolatedCaller("closeSystemDialogs");
6810
6811 final int pid = Binder.getCallingPid();
6812 final int uid = Binder.getCallingUid();
6813 final long origId = Binder.clearCallingIdentity();
6814 try {
6815 synchronized (mGlobalLock) {
6816 // Only allow this from foreground processes, so that background
6817 // applications can't abuse it to prevent system UI from being shown.
6818 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006819 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 if (!proc.isPerceptible()) {
6821 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6822 + " from background process " + proc);
6823 return;
6824 }
6825 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 mWindowManager.closeSystemDialogs(reason);
6827
Wale Ogunwaled32da472018-11-16 07:19:28 -08006828 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006830 // Call into AM outside the synchronized block.
6831 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 } finally {
6833 Binder.restoreCallingIdentity(origId);
6834 }
6835 }
6836
6837 @Override
6838 public void cleanupDisabledPackageComponents(
6839 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6840 synchronized (mGlobalLock) {
6841 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006842 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006844 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 mStackSupervisor.scheduleIdleLocked();
6846 }
6847
6848 // Clean-up disabled tasks
6849 getRecentTasks().cleanupDisabledPackageTasksLocked(
6850 packageName, disabledClasses, userId);
6851 }
6852 }
6853
6854 @Override
6855 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6856 int userId) {
6857 synchronized (mGlobalLock) {
6858
6859 boolean didSomething =
6860 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006861 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 null, doit, evenPersistent, userId);
6863 return didSomething;
6864 }
6865 }
6866
6867 @Override
6868 public void resumeTopActivities(boolean scheduleIdle) {
6869 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006870 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 if (scheduleIdle) {
6872 mStackSupervisor.scheduleIdleLocked();
6873 }
6874 }
6875 }
6876
Riddle Hsua0536432019-02-16 00:38:59 +08006877 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 @Override
6879 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006880 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6882 }
6883 }
6884
Riddle Hsua0536432019-02-16 00:38:59 +08006885 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 @Override
6887 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006888 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006889 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891 }
6892
6893 @Override
6894 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6895 try {
6896 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6897 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6898 }
6899 } catch (RemoteException ex) {
6900 throw new SecurityException("Fail to check is caller a privileged app", ex);
6901 }
6902
6903 synchronized (mGlobalLock) {
6904 final long ident = Binder.clearCallingIdentity();
6905 try {
6906 if (mAmInternal.shouldConfirmCredentials(userId)) {
6907 if (mKeyguardController.isKeyguardLocked()) {
6908 // Showing launcher to avoid user entering credential twice.
6909 startHomeActivity(currentUserId, "notifyLockedProfile");
6910 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 }
6913 } finally {
6914 Binder.restoreCallingIdentity(ident);
6915 }
6916 }
6917 }
6918
6919 @Override
6920 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6921 mAmInternal.enforceCallingPermission(
6922 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6923
6924 synchronized (mGlobalLock) {
6925 final long ident = Binder.clearCallingIdentity();
6926 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006927 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6928 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6931 UserHandle.CURRENT);
6932 } finally {
6933 Binder.restoreCallingIdentity(ident);
6934 }
6935 }
6936 }
6937
6938 @Override
6939 public void writeActivitiesToProto(ProtoOutputStream proto) {
6940 synchronized (mGlobalLock) {
6941 // The output proto of "activity --proto activities"
6942 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006943 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006944 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6945 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006946 }
6947 }
6948
6949 @Override
6950 public void saveANRState(String reason) {
6951 synchronized (mGlobalLock) {
6952 final StringWriter sw = new StringWriter();
6953 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6954 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6955 if (reason != null) {
6956 pw.println(" Reason: " + reason);
6957 }
6958 pw.println();
6959 getActivityStartController().dump(pw, " ", null);
6960 pw.println();
6961 pw.println("-------------------------------------------------------------------------------");
6962 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6963 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6964 "" /* header */);
6965 pw.println();
6966 pw.close();
6967
6968 mLastANRState = sw.toString();
6969 }
6970 }
6971
6972 @Override
6973 public void clearSavedANRState() {
6974 synchronized (mGlobalLock) {
6975 mLastANRState = null;
6976 }
6977 }
6978
6979 @Override
6980 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6981 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6982 synchronized (mGlobalLock) {
6983 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6984 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6985 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6986 dumpLastANRLocked(pw);
6987 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6988 dumpLastANRTracesLocked(pw);
6989 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6990 dumpActivityStarterLocked(pw, dumpPackage);
6991 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6992 dumpActivityContainersLocked(pw);
6993 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6994 if (getRecentTasks() != null) {
6995 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6996 }
6997 }
6998 }
6999 }
7000
7001 @Override
7002 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7003 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7004 int wakefulness) {
7005 synchronized (mGlobalLock) {
7006 if (mHomeProcess != null && (dumpPackage == null
7007 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7008 if (needSep) {
7009 pw.println();
7010 needSep = false;
7011 }
7012 pw.println(" mHomeProcess: " + mHomeProcess);
7013 }
7014 if (mPreviousProcess != null && (dumpPackage == null
7015 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7016 if (needSep) {
7017 pw.println();
7018 needSep = false;
7019 }
7020 pw.println(" mPreviousProcess: " + mPreviousProcess);
7021 }
7022 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7024 StringBuilder sb = new StringBuilder(128);
7025 sb.append(" mPreviousProcessVisibleTime: ");
7026 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7027 pw.println(sb);
7028 }
7029 if (mHeavyWeightProcess != null && (dumpPackage == null
7030 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7031 if (needSep) {
7032 pw.println();
7033 needSep = false;
7034 }
7035 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7036 }
7037 if (dumpPackage == null) {
7038 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007039 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 }
7041 if (dumpAll) {
7042 if (dumpPackage == null) {
7043 pw.println(" mConfigWillChange: "
7044 + getTopDisplayFocusedStack().mConfigWillChange);
7045 }
7046 if (mCompatModePackages.getPackages().size() > 0) {
7047 boolean printed = false;
7048 for (Map.Entry<String, Integer> entry
7049 : mCompatModePackages.getPackages().entrySet()) {
7050 String pkg = entry.getKey();
7051 int mode = entry.getValue();
7052 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7053 continue;
7054 }
7055 if (!printed) {
7056 pw.println(" mScreenCompatPackages:");
7057 printed = true;
7058 }
7059 pw.println(" " + pkg + ": " + mode);
7060 }
7061 }
7062 }
7063
7064 if (dumpPackage == null) {
7065 pw.println(" mWakefulness="
7066 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007067 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 if (mRunningVoice != null) {
7069 pw.println(" mRunningVoice=" + mRunningVoice);
7070 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7071 }
7072 pw.println(" mSleeping=" + mSleeping);
7073 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7074 pw.println(" mVrController=" + mVrController);
7075 }
7076 if (mCurAppTimeTracker != null) {
7077 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7078 }
7079 if (mAllowAppSwitchUids.size() > 0) {
7080 boolean printed = false;
7081 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7082 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7083 for (int j = 0; j < types.size(); j++) {
7084 if (dumpPackage == null ||
7085 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7086 if (needSep) {
7087 pw.println();
7088 needSep = false;
7089 }
7090 if (!printed) {
7091 pw.println(" mAllowAppSwitchUids:");
7092 printed = true;
7093 }
7094 pw.print(" User ");
7095 pw.print(mAllowAppSwitchUids.keyAt(i));
7096 pw.print(": Type ");
7097 pw.print(types.keyAt(j));
7098 pw.print(" = ");
7099 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7100 pw.println();
7101 }
7102 }
7103 }
7104 }
7105 if (dumpPackage == null) {
7106 if (mController != null) {
7107 pw.println(" mController=" + mController
7108 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7109 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007110 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7111 pw.println(" mLaunchingActivityWakeLock="
7112 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114
7115 return needSep;
7116 }
7117 }
7118
7119 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007120 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7121 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 synchronized (mGlobalLock) {
7123 if (dumpPackage == null) {
7124 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7125 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007126 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7127 if (mRunningVoice != null) {
7128 final long vrToken = proto.start(
7129 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7130 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7131 mRunningVoice.toString());
7132 mVoiceWakeLock.writeToProto(
7133 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7134 proto.end(vrToken);
7135 }
7136 mVrController.writeToProto(proto,
7137 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007138 if (mController != null) {
7139 final long token = proto.start(CONTROLLER);
7140 proto.write(CONTROLLER, mController.toString());
7141 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7142 proto.end(token);
7143 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007144 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7145 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7146 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007147 }
7148
7149 if (mHomeProcess != null && (dumpPackage == null
7150 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007151 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007152 }
7153
7154 if (mPreviousProcess != null && (dumpPackage == null
7155 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007156 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7158 }
7159
7160 if (mHeavyWeightProcess != null && (dumpPackage == null
7161 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007162 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007163 }
7164
7165 for (Map.Entry<String, Integer> entry
7166 : mCompatModePackages.getPackages().entrySet()) {
7167 String pkg = entry.getKey();
7168 int mode = entry.getValue();
7169 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7170 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7171 proto.write(PACKAGE, pkg);
7172 proto.write(MODE, mode);
7173 proto.end(compatToken);
7174 }
7175 }
7176
7177 if (mCurAppTimeTracker != null) {
7178 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7179 }
7180
7181 }
7182 }
7183
7184 @Override
7185 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7186 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7187 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007188 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7189 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 }
7191
7192 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007193 public void dumpForOom(PrintWriter pw) {
7194 synchronized (mGlobalLock) {
7195 pw.println(" mHomeProcess: " + mHomeProcess);
7196 pw.println(" mPreviousProcess: " + mPreviousProcess);
7197 if (mHeavyWeightProcess != null) {
7198 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7199 }
7200 }
7201 }
7202
7203 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 public boolean canGcNow() {
7205 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007206 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 }
7208 }
7209
Riddle Hsua0536432019-02-16 00:38:59 +08007210 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 @Override
7212 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007213 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007214 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 return top != null ? top.app : null;
7216 }
7217 }
7218
Riddle Hsua0536432019-02-16 00:38:59 +08007219 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 @Override
7221 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007222 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007223 if (mRootActivityContainer != null) {
7224 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007225 }
7226 }
7227 }
7228
7229 @Override
7230 public void scheduleDestroyAllActivities(String reason) {
7231 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007232 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007233 }
7234 }
7235
7236 @Override
7237 public void removeUser(int userId) {
7238 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007239 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007240 }
7241 }
7242
7243 @Override
7244 public boolean switchUser(int userId, UserState userState) {
7245 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007246 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007247 }
7248 }
7249
7250 @Override
7251 public void onHandleAppCrash(WindowProcessController wpc) {
7252 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007253 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 }
7255 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007256
7257 @Override
7258 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7259 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007260 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007261 }
7262 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007263
Riddle Hsua0536432019-02-16 00:38:59 +08007264 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007265 @Override
7266 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007267 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007268 }
7269
Riddle Hsua0536432019-02-16 00:38:59 +08007270 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007271 @Override
7272 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007273 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007274 }
7275
Riddle Hsua0536432019-02-16 00:38:59 +08007276 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007277 @Override
7278 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007279 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007280 }
7281
Riddle Hsua0536432019-02-16 00:38:59 +08007282 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007283 @Override
7284 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007285 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007286 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007287
7288 @Override
7289 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007290 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007291 mPendingTempWhitelist.put(uid, tag);
7292 }
7293 }
7294
7295 @Override
7296 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007298 mPendingTempWhitelist.remove(uid);
7299 }
7300 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007301
7302 @Override
7303 public boolean handleAppCrashInActivityController(String processName, int pid,
7304 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7305 Runnable killCrashingAppCallback) {
7306 synchronized (mGlobalLock) {
7307 if (mController == null) {
7308 return false;
7309 }
7310
7311 try {
7312 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7313 stackTrace)) {
7314 killCrashingAppCallback.run();
7315 return true;
7316 }
7317 } catch (RemoteException e) {
7318 mController = null;
7319 Watchdog.getInstance().setActivityController(null);
7320 }
7321 return false;
7322 }
7323 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007324
7325 @Override
7326 public void removeRecentTasksByPackageName(String packageName, int userId) {
7327 synchronized (mGlobalLock) {
7328 mRecentTasks.removeTasksByPackageName(packageName, userId);
7329 }
7330 }
7331
7332 @Override
7333 public void cleanupRecentTasksForUser(int userId) {
7334 synchronized (mGlobalLock) {
7335 mRecentTasks.cleanupLocked(userId);
7336 }
7337 }
7338
7339 @Override
7340 public void loadRecentTasksForUser(int userId) {
7341 synchronized (mGlobalLock) {
7342 mRecentTasks.loadUserRecentsLocked(userId);
7343 }
7344 }
7345
7346 @Override
7347 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7348 synchronized (mGlobalLock) {
7349 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7350 }
7351 }
7352
7353 @Override
7354 public void flushRecentTasks() {
7355 mRecentTasks.flush();
7356 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007357
7358 @Override
7359 public WindowProcessController getHomeProcess() {
7360 synchronized (mGlobalLock) {
7361 return mHomeProcess;
7362 }
7363 }
7364
7365 @Override
7366 public WindowProcessController getPreviousProcess() {
7367 synchronized (mGlobalLock) {
7368 return mPreviousProcess;
7369 }
7370 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007371
7372 @Override
7373 public void clearLockedTasks(String reason) {
7374 synchronized (mGlobalLock) {
7375 getLockTaskController().clearLockedTasks(reason);
7376 }
7377 }
7378
7379 @Override
7380 public void updateUserConfiguration() {
7381 synchronized (mGlobalLock) {
7382 final Configuration configuration = new Configuration(getGlobalConfiguration());
7383 final int currentUserId = mAmInternal.getCurrentUserId();
7384 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7385 configuration, currentUserId, Settings.System.canWrite(mContext));
7386 updateConfigurationLocked(configuration, null /* starting */,
7387 false /* initLocale */, false /* persistent */, currentUserId,
7388 false /* deferResume */);
7389 }
7390 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007391
7392 @Override
7393 public boolean canShowErrorDialogs() {
7394 synchronized (mGlobalLock) {
7395 return mShowDialogs && !mSleeping && !mShuttingDown
7396 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7397 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7398 mAmInternal.getCurrentUserId())
7399 && !(UserManager.isDeviceInDemoMode(mContext)
7400 && mAmInternal.getCurrentUser().isDemo());
7401 }
7402 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007403
7404 @Override
7405 public void setProfileApp(String profileApp) {
7406 synchronized (mGlobalLock) {
7407 mProfileApp = profileApp;
7408 }
7409 }
7410
7411 @Override
7412 public void setProfileProc(WindowProcessController wpc) {
7413 synchronized (mGlobalLock) {
7414 mProfileProc = wpc;
7415 }
7416 }
7417
7418 @Override
7419 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7420 synchronized (mGlobalLock) {
7421 mProfilerInfo = profilerInfo;
7422 }
7423 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007424
7425 @Override
7426 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7427 synchronized (mGlobalLock) {
7428 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7429 }
7430 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007431
7432 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007433 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7434 boolean reducedResolution) {
7435 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7436 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007437 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007438
7439 @Override
7440 public boolean isUidForeground(int uid) {
7441 synchronized (mGlobalLock) {
7442 return ActivityTaskManagerService.this.isUidForeground(uid);
7443 }
7444 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007445
7446 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007447 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007448 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007449 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007450 }
7451 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007452
7453 @Override
7454 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007455 // Translate package names into UIDs
7456 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007457 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007458 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7459 if (uid >= 0) {
7460 result.add(uid);
7461 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007462 }
7463 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007464 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007465 }
7466 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007467 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007468}