blob: 7283ca57f2aefa4c79120044931ace8fe15852ca [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;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
49import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070055import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070086import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
87import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
89import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
90import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
91import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700109import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800113import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
114import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700115import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
116import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800117import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800119import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
120import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
121import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700122
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700123import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700124import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.annotation.Nullable;
126import android.annotation.UserIdInt;
127import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700129import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700130import android.app.ActivityOptions;
131import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700132import android.app.ActivityThread;
133import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100135import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700136import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700137import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700138import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.IApplicationThread;
140import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700141import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400142import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700263import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800265import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800277import java.lang.annotation.ElementType;
278import java.lang.annotation.Retention;
279import java.lang.annotation.RetentionPolicy;
280import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700284import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400286import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700289import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Map;
291import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292
293/**
294 * System service for managing activities and their containers (task, stacks, displays,... ).
295 *
296 * {@hide}
297 */
298public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700299 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700301 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
302 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
303 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
304 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
305 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700306 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700307
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700309 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100312 // How long we permit background activity starts after an activity in the process
313 // started or finished.
314 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315
Wale Ogunwale98875612018-10-12 07:53:02 -0700316 /** Used to indicate that an app transition should be animated. */
317 static final boolean ANIMATE = true;
318
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700319 /** Hardware-reported OpenGLES version. */
320 final int GL_ES_VERSION;
321
Wale Ogunwale31913b52018-10-13 08:29:31 -0700322 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
323 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
324 public static final String DUMP_LASTANR_CMD = "lastanr" ;
325 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
326 public static final String DUMP_STARTER_CMD = "starter" ;
327 public static final String DUMP_CONTAINERS_CMD = "containers" ;
328 public static final String DUMP_RECENTS_CMD = "recents" ;
329 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
330
Wale Ogunwale64258362018-10-16 15:13:37 -0700331 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
332 public static final int RELAUNCH_REASON_NONE = 0;
333 /** This activity is being relaunched due to windowing mode change. */
334 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
335 /** This activity is being relaunched due to a free-resize operation. */
336 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
337
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700338 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700339
Wale Ogunwalef6733932018-06-27 05:14:34 -0700340 /**
341 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
342 * change at runtime. Use mContext for non-UI purposes.
343 */
344 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700346 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700349 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700350 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800351 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800352 @VisibleForTesting
353 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 PowerManagerInternal mPowerManagerInternal;
355 private UsageStatsManagerInternal mUsageStatsInternal;
356
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700357 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 IntentFirewall mIntentFirewall;
359
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700360 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800361 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800362 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700363 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
365 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
366 *
367 * @see WindowManagerThreadPriorityBooster
368 */
369 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700370 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800371 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700372 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700373 private UserManagerService mUserManager;
374 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700375 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800376 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700377 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700378 /** All processes currently running that might have a window organized by name. */
379 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100380 /** All processes we currently have running mapped by pid and uid */
381 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** This is the process holding what we currently consider to be the "home" activity. */
383 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700384 /** The currently running heavy-weight process, if any. */
385 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700386 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /**
388 * This is the process holding the activity the user last visited that is in a different process
389 * from the one they are currently in.
390 */
391 WindowProcessController mPreviousProcess;
392 /** The time at which the previous process was last visible. */
393 long mPreviousProcessVisibleTime;
394
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700395 /** List of intents that were used to start the most recent tasks. */
396 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700397 /** State of external calls telling us if the device is awake or asleep. */
398 private boolean mKeyguardShown = false;
399
400 // Wrapper around VoiceInteractionServiceManager
401 private AssistUtils mAssistUtils;
402
403 // VoiceInteraction session ID that changes for each new request except when
404 // being called for multi-window assist in a single session.
405 private int mViSessionId = 1000;
406
407 // How long to wait in getAssistContextExtras for the activity and foreground services
408 // to respond with the result.
409 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
410
411 // How long top wait when going through the modern assist (which doesn't need to block
412 // on getting this result before starting to launch its UI).
413 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
414
415 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
416 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
417
Alison Cichowlas3e340502018-08-07 17:15:01 -0400418 // Permission tokens are used to temporarily granted a trusted app the ability to call
419 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
420 // showing any appropriate error messages to the user.
421 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
422 10 * MINUTE_IN_MILLIS;
423
424 // How long before the service actually expires a token. This is slightly longer than
425 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
426 // expiration exception.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
428 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
429
430 // How long the service will remember expired tokens, for the purpose of providing error
431 // messaging when a client uses an expired token.
432 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
433 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
434
435 // Activity tokens of system activities that are delegating their call to
436 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
437 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
438
439 // Permission tokens that have expired, but we remember for error reporting.
440 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700442 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
443
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700444 // Keeps track of the active voice interaction service component, notified from
445 // VoiceInteractionManagerService
446 ComponentName mActiveVoiceInteractionServiceComponent;
447
Michal Karpinskida34cd42019-04-02 19:46:52 +0100448 // A map userId and all its companion app uids
449 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000450
Wale Ogunwalee2172292018-10-25 10:11:10 -0700451 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 KeyguardController mKeyguardController;
453 private final ClientLifecycleManager mLifecycleManager;
454 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700455 /** The controller for all operations related to locktask. */
456 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700457 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700459 boolean mSuppressResizeConfigChanges;
460
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700461 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 new UpdateConfigurationResult();
463
464 static final class UpdateConfigurationResult {
465 // Configuration changes that were updated.
466 int changes;
467 // If the activity was relaunched to match the new configuration.
468 boolean activityRelaunched;
469
470 void reset() {
471 changes = 0;
472 activityRelaunched = false;
473 }
474 }
475
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700476 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700477 private int mConfigurationSeq;
478 // To cache the list of supported system locales
479 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480
481 /**
482 * Temp object used when global and/or display override configuration is updated. It is also
483 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
484 * anyone...
485 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private Configuration mTempConfig = new Configuration();
487
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 /** Temporary to avoid allocations. */
489 final StringBuilder mStringBuilder = new StringBuilder(256);
490
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 // Amount of time after a call to stopAppSwitches() during which we will
492 // prevent further untrusted switches from happening.
493 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
494
495 /**
496 * The time at which we will allow normal application switches again,
497 * after a call to {@link #stopAppSwitches()}.
498 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
501 * This is set to true after the first switch after mAppSwitchesAllowedTime
502 * is set; any switches after that will clear the time.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505
Ricky Wai906af482019-06-03 17:25:28 +0100506 /**
507 * Last stop app switches time, apps finished before this time cannot start background activity
508 * even if they are in grace period.
509 */
510 private long mLastStopAppSwitchesTime;
511
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512 IActivityController mController = null;
513 boolean mControllerIsAMonkey = false;
514
Wale Ogunwale214f3482018-10-04 11:00:47 -0700515 final int mFactoryTest;
516
517 /** Used to control how we initialize the service. */
518 ComponentName mTopComponent;
519 String mTopAction = Intent.ACTION_MAIN;
520 String mTopData;
521
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800522 /** Profiling app information. */
523 String mProfileApp = null;
524 WindowProcessController mProfileProc = null;
525 ProfilerInfo mProfilerInfo = null;
526
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700528 * Dump of the activity state at the time of the last ANR. Cleared after
529 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
530 */
531 String mLastANRState;
532
533 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 * Used to retain an update lock when the foreground activity is in
535 * immersive mode.
536 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700537 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538
539 /**
540 * Packages that are being allowed to perform unrestricted app switches. Mapping is
541 * User -> Type -> uid.
542 */
543 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
544
545 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private int mThumbnailWidth;
547 private int mThumbnailHeight;
548 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Flag that indicates if multi-window is enabled.
552 *
553 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
554 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
555 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
556 * At least one of the forms of multi-window must be enabled in order for this flag to be
557 * initialized to 'true'.
558 *
559 * @see #mSupportsSplitScreenMultiWindow
560 * @see #mSupportsFreeformWindowManagement
561 * @see #mSupportsPictureInPicture
562 * @see #mSupportsMultiDisplay
563 */
564 boolean mSupportsMultiWindow;
565 boolean mSupportsSplitScreenMultiWindow;
566 boolean mSupportsFreeformWindowManagement;
567 boolean mSupportsPictureInPicture;
568 boolean mSupportsMultiDisplay;
569 boolean mForceResizableActivities;
570
571 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
572
573 // VR Vr2d Display Id.
574 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700575
Wale Ogunwalef6733932018-06-27 05:14:34 -0700576 /**
577 * Set while we are wanting to sleep, to prevent any
578 * activities from being started/resumed.
579 *
580 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
581 *
582 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
583 * while in the sleep state until there is a pending transition out of sleep, in which case
584 * mSleeping is set to false, and remains false while awake.
585 *
586 * Whether mSleeping can quickly toggled between true/false without the device actually
587 * display changing states is undefined.
588 */
589 private boolean mSleeping = false;
590
591 /**
592 * The process state used for processes that are running the top activities.
593 * This changes between TOP and TOP_SLEEPING to following mSleeping.
594 */
595 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
596
597 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
598 // automatically. Important for devices without direct input devices.
599 private boolean mShowDialogs = true;
600
601 /** Set if we are shutting down the system, similar to sleeping. */
602 boolean mShuttingDown = false;
603
604 /**
605 * We want to hold a wake lock while running a voice interaction session, since
606 * this may happen with the screen off and we need to keep the CPU running to
607 * be able to continue to interact with the user.
608 */
609 PowerManager.WakeLock mVoiceWakeLock;
610
611 /**
612 * Set while we are running a voice interaction. This overrides sleeping while it is active.
613 */
614 IVoiceInteractionSession mRunningVoice;
615
616 /**
617 * The last resumed activity. This is identical to the current resumed activity most
618 * of the time but could be different when we're pausing one activity before we resume
619 * another activity.
620 */
621 ActivityRecord mLastResumedActivity;
622
623 /**
624 * The activity that is currently being traced as the active resumed activity.
625 *
626 * @see #updateResumedAppTrace
627 */
628 private @Nullable ActivityRecord mTracedResumedActivity;
629
630 /** If non-null, we are tracking the time the user spends in the currently focused app. */
631 AppTimeTracker mCurAppTimeTracker;
632
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700633 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700634
Wale Ogunwale53783742018-09-16 10:21:51 -0700635 /**
636 * Packages that the user has asked to have run in screen size
637 * compatibility mode instead of filling the screen.
638 */
639 CompatModePackages mCompatModePackages;
640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private FontScaleSettingObserver mFontScaleSettingObserver;
642
Ricky Wai96f5c352019-04-10 18:40:17 +0100643 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000644
Wale Ogunwalef6733932018-06-27 05:14:34 -0700645 private final class FontScaleSettingObserver extends ContentObserver {
646 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
647 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
648
649 public FontScaleSettingObserver() {
650 super(mH);
651 final ContentResolver resolver = mContext.getContentResolver();
652 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
653 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
654 UserHandle.USER_ALL);
655 }
656
657 @Override
658 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
659 if (mFontScaleUri.equals(uri)) {
660 updateFontScaleIfNeeded(userId);
661 } else if (mHideErrorDialogsUri.equals(uri)) {
662 synchronized (mGlobalLock) {
663 updateShouldShowDialogsLocked(getGlobalConfiguration());
664 }
665 }
666 }
667 }
668
Riddle Hsua0536432019-02-16 00:38:59 +0800669 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
670 @Target(ElementType.METHOD)
671 @Retention(RetentionPolicy.SOURCE)
672 @interface HotPath {
673 int NONE = 0;
674 int OOM_ADJUSTMENT = 1;
675 int LRU_UPDATE = 2;
676 int PROCESS_CHANGE = 3;
677 int caller() default NONE;
678 }
679
Charles Chen8d98dd22018-12-26 17:36:54 +0800680 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
681 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700682 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700683 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 mSystemThread = ActivityThread.currentActivityThread();
685 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700686 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800687 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700688 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700689 }
690
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 public void onSystemReady() {
692 synchronized (mGlobalLock) {
693 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
694 PackageManager.FEATURE_CANT_SAVE_STATE);
695 mAssistUtils = new AssistUtils(mContext);
696 mVrController.onSystemReady();
697 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700698 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700699 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700700 }
701
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700702 public void onInitPowerManagement() {
703 synchronized (mGlobalLock) {
704 mStackSupervisor.initPowerManagement();
705 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
706 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
707 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
708 mVoiceWakeLock.setReferenceCounted(false);
709 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700710 }
711
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700712 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700713 mFontScaleSettingObserver = new FontScaleSettingObserver();
714 }
715
Wale Ogunwale59507092018-10-29 09:00:30 -0700716 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717 final boolean freeformWindowManagement =
718 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
719 || Settings.Global.getInt(
720 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
721
722 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
723 final boolean supportsPictureInPicture = supportsMultiWindow &&
724 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
725 final boolean supportsSplitScreenMultiWindow =
726 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
727 final boolean supportsMultiDisplay = mContext.getPackageManager()
728 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
730 final boolean forceResizable = Settings.Global.getInt(
731 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
732
733 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900734 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735
736 final Configuration configuration = new Configuration();
737 Settings.System.getConfiguration(resolver, configuration);
738 if (forceRtl) {
739 // This will take care of setting the correct layout direction flags
740 configuration.setLayoutDirection(configuration.locale);
741 }
742
743 synchronized (mGlobalLock) {
744 mForceResizableActivities = forceResizable;
745 final boolean multiWindowFormEnabled = freeformWindowManagement
746 || supportsSplitScreenMultiWindow
747 || supportsPictureInPicture
748 || supportsMultiDisplay;
749 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
750 mSupportsMultiWindow = true;
751 mSupportsFreeformWindowManagement = freeformWindowManagement;
752 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
753 mSupportsPictureInPicture = supportsPictureInPicture;
754 mSupportsMultiDisplay = supportsMultiDisplay;
755 } else {
756 mSupportsMultiWindow = false;
757 mSupportsFreeformWindowManagement = false;
758 mSupportsSplitScreenMultiWindow = false;
759 mSupportsPictureInPicture = false;
760 mSupportsMultiDisplay = false;
761 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700818 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700819 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mKeyguardController = mStackSupervisor.getKeyguardController();
821 }
822
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700823 public void onActivityManagerInternalAdded() {
824 synchronized (mGlobalLock) {
825 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
826 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
827 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700828 }
829
Yunfan Chen75157d72018-07-27 14:47:21 +0900830 int increaseConfigurationSeqLocked() {
831 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
832 return mConfigurationSeq;
833 }
834
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 protected ActivityStackSupervisor createStackSupervisor() {
836 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
837 supervisor.initialize();
838 return supervisor;
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void setWindowManager(WindowManagerService wm) {
842 synchronized (mGlobalLock) {
843 mWindowManager = wm;
844 mLockTaskController.setWindowManager(wm);
845 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800846 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
851 synchronized (mGlobalLock) {
852 mUsageStatsInternal = usageStatsManager;
853 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700854 }
855
Wale Ogunwalef6733932018-06-27 05:14:34 -0700856 UserManagerService getUserManager() {
857 if (mUserManager == null) {
858 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
859 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
860 }
861 return mUserManager;
862 }
863
864 AppOpsService getAppOpsService() {
865 if (mAppOpsService == null) {
866 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
867 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
868 }
869 return mAppOpsService;
870 }
871
872 boolean hasUserRestriction(String restriction, int userId) {
873 return getUserManager().hasUserRestriction(restriction, userId);
874 }
875
Michal Karpinski15486842019-04-25 17:33:42 +0100876 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
877 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
878 callingUid, callingPackage);
879 if (mode == AppOpsManager.MODE_DEFAULT) {
880 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
881 == PERMISSION_GRANTED;
882 }
883 return mode == AppOpsManager.MODE_ALLOWED;
884 }
885
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700886 @VisibleForTesting
887 protected void setRecentTasks(RecentTasks recentTasks) {
888 mRecentTasks = recentTasks;
889 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700890 }
891
892 RecentTasks getRecentTasks() {
893 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700894 }
895
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700896 ClientLifecycleManager getLifecycleManager() {
897 return mLifecycleManager;
898 }
899
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700900 ActivityStartController getActivityStartController() {
901 return mActivityStartController;
902 }
903
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700904 TaskChangeNotificationController getTaskChangeNotificationController() {
905 return mTaskChangeNotificationController;
906 }
907
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700908 LockTaskController getLockTaskController() {
909 return mLockTaskController;
910 }
911
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 /**
913 * Return the global configuration used by the process corresponding to the input pid. This is
914 * usually the global configuration with some overrides specific to that process.
915 */
916 Configuration getGlobalConfigurationForCallingPid() {
917 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800918 return getGlobalConfigurationForPid(pid);
919 }
920
921 /**
922 * Return the global configuration used by the process corresponding to the given pid.
923 */
924 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900925 if (pid == MY_PID || pid < 0) {
926 return getGlobalConfiguration();
927 }
928 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100929 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 return app != null ? app.getConfiguration() : getGlobalConfiguration();
931 }
932 }
933
934 /**
935 * Return the device configuration info used by the process corresponding to the input pid.
936 * The value is consistent with the global configuration for the process.
937 */
938 @Override
939 public ConfigurationInfo getDeviceConfigurationInfo() {
940 ConfigurationInfo config = new ConfigurationInfo();
941 synchronized (mGlobalLock) {
942 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
943 config.reqTouchScreen = globalConfig.touchscreen;
944 config.reqKeyboardType = globalConfig.keyboard;
945 config.reqNavigation = globalConfig.navigation;
946 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
947 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
948 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
949 }
950 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
951 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
953 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700954 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 }
956 return config;
957 }
958
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700959 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700960 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 }
962
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700963 public static final class Lifecycle extends SystemService {
964 private final ActivityTaskManagerService mService;
965
966 public Lifecycle(Context context) {
967 super(context);
968 mService = new ActivityTaskManagerService(context);
969 }
970
971 @Override
972 public void onStart() {
973 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700974 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700975 }
976
Garfield Tan891146c2018-10-09 12:14:00 -0700977 @Override
978 public void onUnlockUser(int userId) {
979 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800980 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700981 }
982 }
983
984 @Override
985 public void onCleanupUser(int userId) {
986 synchronized (mService.getGlobalLock()) {
987 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
988 }
989 }
990
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 public ActivityTaskManagerService getService() {
992 return mService;
993 }
994 }
995
996 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997 public final int startActivity(IApplicationThread caller, String callingPackage,
998 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
999 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1000 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1001 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1002 UserHandle.getCallingUserId());
1003 }
1004
1005 @Override
1006 public final int startActivities(IApplicationThread caller, String callingPackage,
1007 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1008 int userId) {
1009 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001010 enforceNotIsolatedCaller(reason);
1011 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001013 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1014 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1015 reason, null /* originatingPendingIntent */,
1016 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1021 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1022 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1023 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1024 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1025 true /*validateIncomingUser*/);
1026 }
1027
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001028 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1030 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1031 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001034 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1036
1037 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 .setCaller(caller)
1040 .setCallingPackage(callingPackage)
1041 .setResolvedType(resolvedType)
1042 .setResultTo(resultTo)
1043 .setResultWho(resultWho)
1044 .setRequestCode(requestCode)
1045 .setStartFlags(startFlags)
1046 .setProfilerInfo(profilerInfo)
1047 .setActivityOptions(bOptions)
1048 .setMayWait(userId)
1049 .execute();
1050
1051 }
1052
1053 @Override
1054 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1055 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001056 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1057 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058 // Refuse possible leaked file descriptors
1059 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1060 throw new IllegalArgumentException("File descriptors passed in Intent");
1061 }
1062
1063 if (!(target instanceof PendingIntentRecord)) {
1064 throw new IllegalArgumentException("Bad PendingIntent object");
1065 }
1066
1067 PendingIntentRecord pir = (PendingIntentRecord)target;
1068
1069 synchronized (mGlobalLock) {
1070 // If this is coming from the currently resumed activity, it is
1071 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001072 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 if (stack.mResumedActivity != null &&
1074 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001075 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 }
1077 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081
1082 @Override
1083 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1084 Bundle bOptions) {
1085 // Refuse possible leaked file descriptors
1086 if (intent != null && intent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1090
1091 synchronized (mGlobalLock) {
1092 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1093 if (r == null) {
1094 SafeActivityOptions.abort(options);
1095 return false;
1096 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001097 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 // The caller is not running... d'oh!
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
1102 intent = new Intent(intent);
1103 // The caller is not allowed to change the data.
1104 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1105 // And we are resetting to find the next component...
1106 intent.setComponent(null);
1107
1108 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1109
1110 ActivityInfo aInfo = null;
1111 try {
1112 List<ResolveInfo> resolves =
1113 AppGlobals.getPackageManager().queryIntentActivities(
1114 intent, r.resolvedType,
1115 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1116 UserHandle.getCallingUserId()).getList();
1117
1118 // Look for the original activity in the list...
1119 final int N = resolves != null ? resolves.size() : 0;
1120 for (int i=0; i<N; i++) {
1121 ResolveInfo rInfo = resolves.get(i);
1122 if (rInfo.activityInfo.packageName.equals(r.packageName)
1123 && rInfo.activityInfo.name.equals(r.info.name)) {
1124 // We found the current one... the next matching is
1125 // after it.
1126 i++;
1127 if (i<N) {
1128 aInfo = resolves.get(i).activityInfo;
1129 }
1130 if (debug) {
1131 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1132 + "/" + r.info.name);
1133 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1134 ? "null" : aInfo.packageName + "/" + aInfo.name));
1135 }
1136 break;
1137 }
1138 }
1139 } catch (RemoteException e) {
1140 }
1141
1142 if (aInfo == null) {
1143 // Nobody who is next!
1144 SafeActivityOptions.abort(options);
1145 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1146 return false;
1147 }
1148
1149 intent.setComponent(new ComponentName(
1150 aInfo.applicationInfo.packageName, aInfo.name));
1151 intent.setFlags(intent.getFlags()&~(
1152 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1153 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1154 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1155 FLAG_ACTIVITY_NEW_TASK));
1156
1157 // Okay now we need to start the new activity, replacing the currently running activity.
1158 // This is a little tricky because we want to start the new one as if the current one is
1159 // finished, but not finish the current one first so that there is no flicker.
1160 // And thus...
1161 final boolean wasFinishing = r.finishing;
1162 r.finishing = true;
1163
1164 // Propagate reply information over to the new activity.
1165 final ActivityRecord resultTo = r.resultTo;
1166 final String resultWho = r.resultWho;
1167 final int requestCode = r.requestCode;
1168 r.resultTo = null;
1169 if (resultTo != null) {
1170 resultTo.removeResultsLocked(r, resultWho, requestCode);
1171 }
1172
1173 final long origId = Binder.clearCallingIdentity();
1174 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001175 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001177 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001178 .setResolvedType(r.resolvedType)
1179 .setActivityInfo(aInfo)
1180 .setResultTo(resultTo != null ? resultTo.appToken : null)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setCallingPid(-1)
1184 .setCallingUid(r.launchedFromUid)
1185 .setCallingPackage(r.launchedFromPackage)
1186 .setRealCallingPid(-1)
1187 .setRealCallingUid(r.launchedFromUid)
1188 .setActivityOptions(options)
1189 .execute();
1190 Binder.restoreCallingIdentity(origId);
1191
1192 r.finishing = wasFinishing;
1193 if (res != ActivityManager.START_SUCCESS) {
1194 return false;
1195 }
1196 return true;
1197 }
1198 }
1199
1200 @Override
1201 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1202 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1203 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1204 final WaitResult res = new WaitResult();
1205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001206 enforceNotIsolatedCaller("startActivityAndWait");
1207 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1208 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001210 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setCaller(caller)
1212 .setCallingPackage(callingPackage)
1213 .setResolvedType(resolvedType)
1214 .setResultTo(resultTo)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setStartFlags(startFlags)
1218 .setActivityOptions(bOptions)
1219 .setMayWait(userId)
1220 .setProfilerInfo(profilerInfo)
1221 .setWaitResult(res)
1222 .execute();
1223 }
1224 return res;
1225 }
1226
1227 @Override
1228 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, Configuration config, Bundle bOptions, int userId) {
1231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001232 enforceNotIsolatedCaller("startActivityWithConfig");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1234 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001236 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setGlobalConfiguration(config)
1245 .setActivityOptions(bOptions)
1246 .setMayWait(userId)
1247 .execute();
1248 }
1249 }
1250
Alison Cichowlas3e340502018-08-07 17:15:01 -04001251
1252 @Override
1253 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1254 int callingUid = Binder.getCallingUid();
1255 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1256 throw new SecurityException("Only the system process can request a permission token, "
1257 + "received request from uid: " + callingUid);
1258 }
1259 IBinder permissionToken = new Binder();
1260 synchronized (mGlobalLock) {
1261 mStartActivitySources.put(permissionToken, delegatorToken);
1262 }
1263
1264 Message expireMsg = PooledLambda.obtainMessage(
1265 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1266 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1267
1268 Message forgetMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1271
1272 return permissionToken;
1273 }
1274
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 @Override
1276 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1277 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001278 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1279 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 // permission grants) as any app that may launch one of your own activities. So we only
1282 // allow this in two cases:
1283 // 1) The caller is an activity that is part of the core framework, and then only when it
1284 // is running as the system.
1285 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1286 // can only be requested by a system activity, which may then delegate this call to
1287 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 final ActivityRecord sourceRecord;
1289 final int targetUid;
1290 final String targetPackage;
1291 final boolean isResolver;
1292 synchronized (mGlobalLock) {
1293 if (resultTo == null) {
1294 throw new SecurityException("Must be called from an activity");
1295 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 final IBinder sourceToken;
1297 if (permissionToken != null) {
1298 // To even attempt to use a permissionToken, an app must also have this signature
1299 // permission.
1300 mAmInternal.enforceCallingPermission(
1301 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1302 "startActivityAsCaller");
1303 // If called with a permissionToken, we want the sourceRecord from the delegator
1304 // activity that requested this token.
1305 sourceToken = mStartActivitySources.remove(permissionToken);
1306 if (sourceToken == null) {
1307 // Invalid permissionToken, check if it recently expired.
1308 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1309 throw new SecurityException("Called with expired permission token: "
1310 + permissionToken);
1311 } else {
1312 throw new SecurityException("Called with invalid permission token: "
1313 + permissionToken);
1314 }
1315 }
1316 } else {
1317 // This method was called directly by the source.
1318 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001320
Wale Ogunwaled32da472018-11-16 07:19:28 -08001321 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 if (sourceRecord == null) {
1323 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
1325 if (sourceRecord.app == null) {
1326 throw new SecurityException("Called without a process attached to activity");
1327 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001328
1329 // Whether called directly or from a delegate, the source activity must be from the
1330 // android package.
1331 if (!sourceRecord.info.packageName.equals("android")) {
1332 throw new SecurityException("Must be called from an activity that is "
1333 + "declared in the android package");
1334 }
1335
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001336 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 // This is still okay, as long as this activity is running under the
1338 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 + " must be system uid or original calling uid "
1343 + sourceRecord.launchedFromUid);
1344 }
1345 }
1346 if (ignoreTargetSecurity) {
1347 if (intent.getComponent() == null) {
1348 throw new SecurityException(
1349 "Component must be specified with ignoreTargetSecurity");
1350 }
1351 if (intent.getSelector() != null) {
1352 throw new SecurityException(
1353 "Selector not allowed with ignoreTargetSecurity");
1354 }
1355 }
1356 targetUid = sourceRecord.launchedFromUid;
1357 targetPackage = sourceRecord.launchedFromPackage;
1358 isResolver = sourceRecord.isResolverOrChildActivity();
1359 }
1360
1361 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 }
1364
1365 // TODO: Switch to user app stacks here.
1366 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(targetUid)
1369 .setCallingPackage(targetPackage)
1370 .setResolvedType(resolvedType)
1371 .setResultTo(resultTo)
1372 .setResultWho(resultWho)
1373 .setRequestCode(requestCode)
1374 .setStartFlags(startFlags)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1378 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001379 // The target may well be in the background, which would normally prevent it
1380 // from starting an activity. Here we definitely want the start to succeed.
1381 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 .execute();
1383 } catch (SecurityException e) {
1384 // XXX need to figure out how to propagate to original app.
1385 // A SecurityException here is generally actually a fault of the original
1386 // calling activity (such as a fairly granting permissions), so propagate it
1387 // back to them.
1388 /*
1389 StringBuilder msg = new StringBuilder();
1390 msg.append("While launching");
1391 msg.append(intent.toString());
1392 msg.append(": ");
1393 msg.append(e.getMessage());
1394 */
1395 throw e;
1396 }
1397 }
1398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1400 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1401 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1402 }
1403
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 @Override
1405 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1406 Intent intent, String resolvedType, IVoiceInteractionSession session,
1407 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1408 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 if (session == null || interactor == null) {
1411 throw new NullPointerException("null session or interactor");
1412 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001415 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 .setCallingUid(callingUid)
1417 .setCallingPackage(callingPackage)
1418 .setResolvedType(resolvedType)
1419 .setVoiceSession(session)
1420 .setVoiceInteractor(interactor)
1421 .setStartFlags(startFlags)
1422 .setProfilerInfo(profilerInfo)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1431 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1433 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001435 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .setCallingUid(callingUid)
1437 .setCallingPackage(callingPackage)
1438 .setResolvedType(resolvedType)
1439 .setActivityOptions(bOptions)
1440 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001441 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .execute();
1443 }
1444
Riddle Hsu609a8e22019-06-27 16:46:29 -06001445 /**
1446 * Start the recents activity to perform the recents animation.
1447 *
1448 * @param intent The intent to start the recents activity.
1449 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1450 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001452 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1453 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001456 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 final long origId = Binder.clearCallingIdentity();
1458 try {
1459 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001460 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1461 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001462 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463
1464 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001466 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001467 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 if (recentsAnimationRunner == null) {
1469 anim.preloadRecentsActivity();
1470 } else {
1471 anim.startRecentsActivity(recentsAnimationRunner);
1472 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 }
1474 } finally {
1475 Binder.restoreCallingIdentity(origId);
1476 }
1477 }
1478
1479 @Override
1480 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001481 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 "startActivityFromRecents()");
1483
1484 final int callingPid = Binder.getCallingPid();
1485 final int callingUid = Binder.getCallingUid();
1486 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1487 final long origId = Binder.clearCallingIdentity();
1488 try {
1489 synchronized (mGlobalLock) {
1490 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1491 safeOptions);
1492 }
1493 } finally {
1494 Binder.restoreCallingIdentity(origId);
1495 }
1496 }
1497
1498 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001499 * Public API to check if the client is allowed to start an activity on specified display.
1500 *
1501 * If the target display is private or virtual, some restrictions will apply.
1502 *
1503 * @param displayId Target display id.
1504 * @param intent Intent used to launch the activity.
1505 * @param resolvedType The MIME type of the intent.
1506 * @param userId The id of the user for whom the call is made.
1507 * @return {@code true} if a call to start an activity on the target display should succeed and
1508 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1509 */
1510 @Override
1511 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1512 String resolvedType, int userId) {
1513 final int callingUid = Binder.getCallingUid();
1514 final int callingPid = Binder.getCallingPid();
1515 final long origId = Binder.clearCallingIdentity();
1516
1517 try {
1518 // Collect information about the target of the Intent.
1519 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1520 0 /* startFlags */, null /* profilerInfo */, userId,
1521 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1522 UserHandle.USER_NULL));
1523 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1524
1525 synchronized (mGlobalLock) {
1526 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1527 aInfo);
1528 }
1529 } finally {
1530 Binder.restoreCallingIdentity(origId);
1531 }
1532 }
1533
1534 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 * This is the internal entry point for handling Activity.finish().
1536 *
1537 * @param token The Binder token referencing the Activity we want to finish.
1538 * @param resultCode Result code, if any, from this Activity.
1539 * @param resultData Result data (Intent), if any, from this Activity.
1540 * @param finishTask Whether to finish the task associated with this Activity.
1541 *
1542 * @return Returns true if the activity successfully finished, or false if it is still running.
1543 */
1544 @Override
1545 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1546 int finishTask) {
1547 // Refuse possible leaked file descriptors
1548 if (resultData != null && resultData.hasFileDescriptors()) {
1549 throw new IllegalArgumentException("File descriptors passed in Intent");
1550 }
1551
1552 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 if (r == null) {
1555 return true;
1556 }
1557 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001558 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001559 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 if (rootR == null) {
1561 Slog.w(TAG, "Finishing task with all activities already finished");
1562 }
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1564 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001565 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 return false;
1567 }
1568
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1570 // We should consolidate.
1571 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001573 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 if (next != null) {
1575 // ask watcher if this is allowed
1576 boolean resumeOK = true;
1577 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001578 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 Watchdog.getInstance().setActivityController(null);
1582 }
1583
1584 if (!resumeOK) {
1585 Slog.i(TAG, "Not finishing activity because controller resumed");
1586 return false;
1587 }
1588 }
1589 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001590
1591 // note down that the process has finished an activity and is in background activity
1592 // starts grace period
1593 if (r.app != null) {
1594 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1595 }
1596
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 final long origId = Binder.clearCallingIdentity();
1598 try {
1599 boolean res;
1600 final boolean finishWithRootActivity =
1601 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1602 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1603 || (finishWithRootActivity && r == rootR)) {
1604 // If requested, remove the task that is associated to this activity only if it
1605 // was the root activity in the task. The result code and data is ignored
1606 // because we don't support returning them across task boundaries. Also, to
1607 // keep backwards compatibility we remove the task from recents when finishing
1608 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001609 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 finishWithRootActivity, "finish-activity");
1611 if (!res) {
1612 Slog.i(TAG, "Removing task failed to finish activity");
1613 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001614 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001615 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 } else {
Andrii Kulian40eda672019-07-30 15:05:57 -07001617 r.finishActivityLocked(resultCode, resultData, "app-request",
1618 true /* oomAdj */);
1619 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 if (!res) {
1621 Slog.i(TAG, "Failed to finish by app-request");
1622 }
1623 }
1624 return res;
1625 } finally {
1626 Binder.restoreCallingIdentity(origId);
1627 }
1628 }
1629 }
1630
1631 @Override
1632 public boolean finishActivityAffinity(IBinder token) {
1633 synchronized (mGlobalLock) {
1634 final long origId = Binder.clearCallingIdentity();
1635 try {
1636 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1637 if (r == null) {
1638 return false;
1639 }
1640
1641 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1642 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001643 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 return false;
1645 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001646 r.finishActivityAffinity();
1647 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1656 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001657 try {
1658 WindowProcessController proc = null;
1659 synchronized (mGlobalLock) {
1660 ActivityStack stack = ActivityRecord.getStackLocked(token);
1661 if (stack == null) {
1662 return;
1663 }
1664 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1665 false /* fromTimeout */, false /* processPausingActivities */, config);
1666 if (r != null) {
1667 proc = r.app;
1668 }
1669 if (stopProfiling && proc != null) {
1670 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 }
1672 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001673 } finally {
1674 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677
1678 @Override
1679 public final void activityResumed(IBinder token) {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001683 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 Binder.restoreCallingIdentity(origId);
1686 }
1687
1688 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001689 public final void activityTopResumedStateLost() {
1690 final long origId = Binder.clearCallingIdentity();
1691 synchronized (mGlobalLock) {
1692 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1693 }
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696
1697 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 public final void activityPaused(IBinder token) {
1699 final long origId = Binder.clearCallingIdentity();
1700 synchronized (mGlobalLock) {
1701 ActivityStack stack = ActivityRecord.getStackLocked(token);
1702 if (stack != null) {
1703 stack.activityPausedLocked(token, false);
1704 }
1705 }
1706 Binder.restoreCallingIdentity(origId);
1707 }
1708
1709 @Override
1710 public final void activityStopped(IBinder token, Bundle icicle,
1711 PersistableBundle persistentState, CharSequence description) {
1712 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1713
1714 // Refuse possible leaked file descriptors
1715 if (icicle != null && icicle.hasFileDescriptors()) {
1716 throw new IllegalArgumentException("File descriptors passed in Bundle");
1717 }
1718
1719 final long origId = Binder.clearCallingIdentity();
1720
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001721 String restartingName = null;
1722 int restartingUid = 0;
1723 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001725 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001727 if (r.attachedToProcess()
1728 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1729 // The activity was requested to restart from
1730 // {@link #restartActivityProcessIfVisible}.
1731 restartingName = r.app.mName;
1732 restartingUid = r.app.mUid;
1733 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 r.activityStoppedLocked(icicle, persistentState, description);
1735 }
1736 }
1737
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001738 if (restartingName != null) {
1739 // In order to let the foreground activity can be restarted with its saved state from
1740 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1741 // until the activity reports stopped with the state. And the activity record will be
1742 // kept because the record state is restarting, then the activity will be restarted
1743 // immediately if it is still the top one.
1744 mStackSupervisor.removeRestartTimeouts(r);
1745 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1746 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001747 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 @Override
1753 public final void activityDestroyed(IBinder token) {
1754 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1755 synchronized (mGlobalLock) {
1756 ActivityStack stack = ActivityRecord.getStackLocked(token);
1757 if (stack != null) {
1758 stack.activityDestroyedLocked(token, "activityDestroyed");
1759 }
1760 }
1761 }
1762
1763 @Override
1764 public final void activityRelaunched(IBinder token) {
1765 final long origId = Binder.clearCallingIdentity();
1766 synchronized (mGlobalLock) {
1767 mStackSupervisor.activityRelaunchedLocked(token);
1768 }
1769 Binder.restoreCallingIdentity(origId);
1770 }
1771
1772 public final void activitySlept(IBinder token) {
1773 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1774
1775 final long origId = Binder.clearCallingIdentity();
1776
1777 synchronized (mGlobalLock) {
1778 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1779 if (r != null) {
1780 mStackSupervisor.activitySleptLocked(r);
1781 }
1782 }
1783
1784 Binder.restoreCallingIdentity(origId);
1785 }
1786
1787 @Override
1788 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1789 synchronized (mGlobalLock) {
1790 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1791 if (r == null) {
1792 return;
1793 }
1794 final long origId = Binder.clearCallingIdentity();
1795 try {
1796 r.setRequestedOrientation(requestedOrientation);
1797 } finally {
1798 Binder.restoreCallingIdentity(origId);
1799 }
1800 }
1801 }
1802
1803 @Override
1804 public int getRequestedOrientation(IBinder token) {
1805 synchronized (mGlobalLock) {
1806 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1807 if (r == null) {
1808 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1809 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001810 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
1812 }
1813
1814 @Override
1815 public void setImmersive(IBinder token, boolean immersive) {
1816 synchronized (mGlobalLock) {
1817 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 throw new IllegalArgumentException();
1820 }
1821 r.immersive = immersive;
1822
1823 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001824 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001826 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827 }
1828 }
1829 }
1830
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 void applyUpdateLockStateLocked(ActivityRecord r) {
1832 // Modifications to the UpdateLock state are done on our handler, outside
1833 // the activity manager's locks. The new state is determined based on the
1834 // state *now* of the relevant activity record. The object is passed to
1835 // the handler solely for logging detail, not to be consulted/modified.
1836 final boolean nextState = r != null && r.immersive;
1837 mH.post(() -> {
1838 if (mUpdateLock.isHeld() != nextState) {
1839 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1840 "Applying new update lock state '" + nextState + "' for " + r);
1841 if (nextState) {
1842 mUpdateLock.acquire();
1843 } else {
1844 mUpdateLock.release();
1845 }
1846 }
1847 });
1848 }
1849
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850 @Override
1851 public boolean isImmersive(IBinder token) {
1852 synchronized (mGlobalLock) {
1853 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1854 if (r == null) {
1855 throw new IllegalArgumentException();
1856 }
1857 return r.immersive;
1858 }
1859 }
1860
1861 @Override
1862 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001863 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001865 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 return (r != null) ? r.immersive : false;
1867 }
1868 }
1869
1870 @Override
1871 public void overridePendingTransition(IBinder token, String packageName,
1872 int enterAnim, int exitAnim) {
1873 synchronized (mGlobalLock) {
1874 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1875 if (self == null) {
1876 return;
1877 }
1878
1879 final long origId = Binder.clearCallingIdentity();
1880
1881 if (self.isState(
1882 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001883 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001884 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 }
1886
1887 Binder.restoreCallingIdentity(origId);
1888 }
1889 }
1890
1891 @Override
1892 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001893 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001895 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001896 if (r == null) {
1897 return ActivityManager.COMPAT_MODE_UNKNOWN;
1898 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001899 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 }
1901 }
1902
1903 @Override
1904 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001905 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001907 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001908 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001909 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 if (r == null) {
1911 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1912 return;
1913 }
1914 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001915 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 }
1917 }
1918
1919 @Override
1920 public int getLaunchedFromUid(IBinder activityToken) {
1921 ActivityRecord srec;
1922 synchronized (mGlobalLock) {
1923 srec = ActivityRecord.forTokenLocked(activityToken);
1924 }
1925 if (srec == null) {
1926 return -1;
1927 }
1928 return srec.launchedFromUid;
1929 }
1930
1931 @Override
1932 public String getLaunchedFromPackage(IBinder activityToken) {
1933 ActivityRecord srec;
1934 synchronized (mGlobalLock) {
1935 srec = ActivityRecord.forTokenLocked(activityToken);
1936 }
1937 if (srec == null) {
1938 return null;
1939 }
1940 return srec.launchedFromPackage;
1941 }
1942
1943 @Override
1944 public boolean convertFromTranslucent(IBinder token) {
1945 final long origId = Binder.clearCallingIdentity();
1946 try {
1947 synchronized (mGlobalLock) {
1948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1949 if (r == null) {
1950 return false;
1951 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001952 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 }
1954 } finally {
1955 Binder.restoreCallingIdentity(origId);
1956 }
1957 }
1958
1959 @Override
1960 public boolean convertToTranslucent(IBinder token, Bundle options) {
1961 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1962 final long origId = Binder.clearCallingIdentity();
1963 try {
1964 synchronized (mGlobalLock) {
1965 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1966 if (r == null) {
1967 return false;
1968 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001969 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 int index = task.mActivities.lastIndexOf(r);
1971 if (index > 0) {
1972 ActivityRecord under = task.mActivities.get(index - 1);
1973 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1974 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001975 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 } finally {
1978 Binder.restoreCallingIdentity(origId);
1979 }
1980 }
1981
1982 @Override
1983 public void notifyActivityDrawn(IBinder token) {
1984 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1985 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001986 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001987 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001988 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990 }
1991 }
1992
1993 @Override
1994 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1995 synchronized (mGlobalLock) {
1996 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1997 if (r == null) {
1998 return;
1999 }
2000 r.reportFullyDrawnLocked(restoredFromBundle);
2001 }
2002 }
2003
2004 @Override
2005 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2006 synchronized (mGlobalLock) {
2007 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2008 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2009 return stack.mDisplayId;
2010 }
2011 return DEFAULT_DISPLAY;
2012 }
2013 }
2014
2015 @Override
2016 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002017 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 long ident = Binder.clearCallingIdentity();
2019 try {
2020 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002021 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002023 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 }
2025 return null;
2026 }
2027 } finally {
2028 Binder.restoreCallingIdentity(ident);
2029 }
2030 }
2031
2032 @Override
2033 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002034 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2036 final long callingId = Binder.clearCallingIdentity();
2037 try {
2038 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 if (stack == null) {
2041 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2042 return;
2043 }
2044 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002045 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 }
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(callingId);
2051 }
2052 }
2053
2054 @Override
2055 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002056 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2058 final long callingId = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002062 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (task == null) {
2064 return;
2065 }
2066 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002067 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 }
2070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(callingId);
2073 }
2074 }
2075
2076 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002077 public void restartActivityProcessIfVisible(IBinder activityToken) {
2078 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2079 final long callingId = Binder.clearCallingIdentity();
2080 try {
2081 synchronized (mGlobalLock) {
2082 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2083 if (r == null) {
2084 return;
2085 }
2086 r.restartProcessIfVisible();
2087 }
2088 } finally {
2089 Binder.restoreCallingIdentity(callingId);
2090 }
2091 }
2092
2093 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002095 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 synchronized (mGlobalLock) {
2097 final long ident = Binder.clearCallingIdentity();
2098 try {
2099 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2100 "remove-task");
2101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
2104 }
2105 }
2106
2107 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002108 public void removeAllVisibleRecentTasks() {
2109 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2110 synchronized (mGlobalLock) {
2111 final long ident = Binder.clearCallingIdentity();
2112 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002113 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
2117 }
2118 }
2119
2120 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2122 synchronized (mGlobalLock) {
2123 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2124 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002125 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 }
2127 }
2128 return false;
2129 }
2130
2131 @Override
2132 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2133 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002134
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002135 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002136 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2137 if (r != null) {
2138 return r.getActivityStack().navigateUpToLocked(
2139 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002140 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 }
2143 }
2144
2145 /**
2146 * Attempts to move a task backwards in z-order (the order of activities within the task is
2147 * unchanged).
2148 *
2149 * There are several possible results of this call:
2150 * - if the task is locked, then we will show the lock toast
2151 * - if there is a task behind the provided task, then that task is made visible and resumed as
2152 * this task is moved to the back
2153 * - otherwise, if there are no other tasks in the stack:
2154 * - if this task is in the pinned stack, then we remove the stack completely, which will
2155 * have the effect of moving the task to the top or bottom of the fullscreen stack
2156 * (depending on whether it is visible)
2157 * - otherwise, we simply return home and hide this task
2158 *
2159 * @param token A reference to the activity we wish to move
2160 * @param nonRoot If false then this only works if the activity is the root
2161 * of a task; if true it will work for any activity in a task.
2162 * @return Returns true if the move completed, false if not.
2163 */
2164 @Override
2165 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002166 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 synchronized (mGlobalLock) {
2168 final long origId = Binder.clearCallingIdentity();
2169 try {
2170 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002171 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 if (task != null) {
2173 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2174 }
2175 } finally {
2176 Binder.restoreCallingIdentity(origId);
2177 }
2178 }
2179 return false;
2180 }
2181
2182 @Override
2183 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002184 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 long ident = Binder.clearCallingIdentity();
2186 Rect rect = new Rect();
2187 try {
2188 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002189 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2191 if (task == null) {
2192 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2193 return rect;
2194 }
2195 if (task.getStack() != null) {
2196 // Return the bounds from window manager since it will be adjusted for various
2197 // things like the presense of a docked stack for tasks that aren't resizeable.
2198 task.getWindowContainerBounds(rect);
2199 } else {
2200 // Task isn't in window manager yet since it isn't associated with a stack.
2201 // Return the persist value from activity manager
2202 if (!task.matchParentBounds()) {
2203 rect.set(task.getBounds());
2204 } else if (task.mLastNonFullscreenBounds != null) {
2205 rect.set(task.mLastNonFullscreenBounds);
2206 }
2207 }
2208 }
2209 } finally {
2210 Binder.restoreCallingIdentity(ident);
2211 }
2212 return rect;
2213 }
2214
2215 @Override
2216 public ActivityManager.TaskDescription getTaskDescription(int id) {
2217 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002218 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002220 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2222 if (tr != null) {
2223 return tr.lastTaskDescription;
2224 }
2225 }
2226 return null;
2227 }
2228
2229 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002230 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2231 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2232 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2233 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2234 return;
2235 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 synchronized (mGlobalLock) {
2238 final long ident = Binder.clearCallingIdentity();
2239 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002240 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002241 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002242 if (task == null) {
2243 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2244 return;
2245 }
2246
2247 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2248 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2249
2250 if (!task.isActivityTypeStandardOrUndefined()) {
2251 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2252 + " non-standard task " + taskId + " to windowing mode="
2253 + windowingMode);
2254 }
2255
2256 final ActivityStack stack = task.getStack();
2257 if (toTop) {
2258 stack.moveToFront("setTaskWindowingMode", task);
2259 }
2260 stack.setWindowingMode(windowingMode);
2261 } finally {
2262 Binder.restoreCallingIdentity(ident);
2263 }
2264 }
2265 }
2266
2267 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002268 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002269 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270 ActivityRecord r = getCallingRecordLocked(token);
2271 return r != null ? r.info.packageName : null;
2272 }
2273 }
2274
2275 @Override
2276 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002277 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 ActivityRecord r = getCallingRecordLocked(token);
2279 return r != null ? r.intent.getComponent() : null;
2280 }
2281 }
2282
2283 private ActivityRecord getCallingRecordLocked(IBinder token) {
2284 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2285 if (r == null) {
2286 return null;
2287 }
2288 return r.resultTo;
2289 }
2290
2291 @Override
2292 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002293 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294
2295 synchronized (mGlobalLock) {
2296 final long origId = Binder.clearCallingIdentity();
2297 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002298 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 } finally {
2300 Binder.restoreCallingIdentity(origId);
2301 }
2302 }
2303 }
2304
Mark Renouf446251d2019-04-26 10:22:41 -04002305 @Override
2306 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2307 synchronized (mGlobalLock) {
2308 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2309 if (r == null) {
2310 return;
2311 }
2312 ActivityStack stack = r.getActivityStack();
2313 if (stack != null && stack.isSingleTaskInstance()) {
2314 // Single-task stacks are used for activities which are presented in floating
2315 // windows above full screen activities. Instead of directly finishing the
2316 // task, a task change listener is used to notify SystemUI so the action can be
2317 // handled specially.
2318 final TaskRecord task = r.getTaskRecord();
2319 mTaskChangeNotificationController
2320 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2321 } else {
2322 try {
2323 callback.requestFinish();
2324 } catch (RemoteException e) {
2325 Slog.e(TAG, "Failed to invoke request finish callback", e);
2326 }
2327 }
2328 }
2329 }
2330
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002331 /**
2332 * TODO: Add mController hook
2333 */
2334 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002335 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2336 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002337 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338
2339 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2340 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002341 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2342 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 }
2344 }
2345
Ricky Waiaca8a772019-04-04 16:01:06 +01002346 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2347 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002349
Ricky Waiaca8a772019-04-04 16:01:06 +01002350 final int callingPid = Binder.getCallingPid();
2351 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002352 if (!isSameApp(callingUid, callingPackage)) {
2353 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2354 + Binder.getCallingPid() + " as package " + callingPackage;
2355 Slog.w(TAG, msg);
2356 throw new SecurityException(msg);
2357 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002358 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 SafeActivityOptions.abort(options);
2360 return;
2361 }
2362 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 WindowProcessController callerApp = null;
2364 if (appThread != null) {
2365 callerApp = getProcessController(appThread);
2366 }
2367 final ActivityStarter starter = getActivityStartController().obtainStarter(
2368 null /* intent */, "moveTaskToFront");
2369 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2370 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002371 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002372 return;
2373 }
2374 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002376 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 if (task == null) {
2378 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002379 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 return;
2381 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002382 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002384 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 return;
2386 }
2387 ActivityOptions realOptions = options != null
2388 ? options.getOptions(mStackSupervisor)
2389 : null;
2390 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2391 false /* forceNonResizable */);
2392
2393 final ActivityRecord topActivity = task.getTopActivity();
2394 if (topActivity != null) {
2395
2396 // We are reshowing a task, use a starting window to hide the initial draw delay
2397 // so the transition can start earlier.
2398 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2399 true /* taskSwitch */, fromRecents);
2400 }
2401 } finally {
2402 Binder.restoreCallingIdentity(origId);
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 }
2405
Ricky Waiaca8a772019-04-04 16:01:06 +01002406 /**
2407 * Return true if callingUid is system, or packageName belongs to that callingUid.
2408 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002409 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002410 try {
2411 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2412 if (packageName == null) {
2413 return false;
2414 }
2415 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2416 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2417 UserHandle.getUserId(callingUid));
2418 return UserHandle.isSameApp(callingUid, uid);
2419 }
2420 } catch (RemoteException e) {
2421 // Should not happen
2422 }
2423 return true;
2424 }
2425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002426 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2427 int callingPid, int callingUid, String name) {
2428 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2429 return true;
2430 }
2431
2432 if (getRecentTasks().isCallerRecents(sourceUid)) {
2433 return true;
2434 }
2435
2436 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2437 if (perm == PackageManager.PERMISSION_GRANTED) {
2438 return true;
2439 }
2440 if (checkAllowAppSwitchUid(sourceUid)) {
2441 return true;
2442 }
2443
2444 // If the actual IPC caller is different from the logical source, then
2445 // also see if they are allowed to control app switches.
2446 if (callingUid != -1 && callingUid != sourceUid) {
2447 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2448 if (perm == PackageManager.PERMISSION_GRANTED) {
2449 return true;
2450 }
2451 if (checkAllowAppSwitchUid(callingUid)) {
2452 return true;
2453 }
2454 }
2455
2456 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2457 return false;
2458 }
2459
2460 private boolean checkAllowAppSwitchUid(int uid) {
2461 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2462 if (types != null) {
2463 for (int i = types.size() - 1; i >= 0; i--) {
2464 if (types.valueAt(i).intValue() == uid) {
2465 return true;
2466 }
2467 }
2468 }
2469 return false;
2470 }
2471
2472 @Override
2473 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2474 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2475 "setActivityController()");
2476 synchronized (mGlobalLock) {
2477 mController = controller;
2478 mControllerIsAMonkey = imAMonkey;
2479 Watchdog.getInstance().setActivityController(controller);
2480 }
2481 }
2482
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002483 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 synchronized (mGlobalLock) {
2485 return mController != null && mControllerIsAMonkey;
2486 }
2487 }
2488
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 @Override
2490 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2491 synchronized (mGlobalLock) {
2492 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2493 }
2494 }
2495
2496 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2498 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2499 }
2500
2501 @Override
2502 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2503 @WindowConfiguration.ActivityType int ignoreActivityType,
2504 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2505 final int callingUid = Binder.getCallingUid();
2506 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2507
2508 synchronized (mGlobalLock) {
2509 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002513 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002514 ignoreWindowingMode, callingUid, allowed);
2515 }
2516
2517 return list;
2518 }
2519
2520 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2522 synchronized (mGlobalLock) {
2523 final long origId = Binder.clearCallingIdentity();
2524 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2525 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002526 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002527 }
2528 Binder.restoreCallingIdentity(origId);
2529 }
2530 }
2531
2532 @Override
2533 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 ActivityStack stack = ActivityRecord.getStackLocked(token);
2536 if (stack != null) {
2537 return stack.willActivityBeVisibleLocked(token);
2538 }
2539 return false;
2540 }
2541 }
2542
2543 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002545 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002546 synchronized (mGlobalLock) {
2547 final long ident = Binder.clearCallingIdentity();
2548 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002549 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002550 if (task == null) {
2551 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2552 return;
2553 }
2554
2555 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2556 + " to stackId=" + stackId + " toTop=" + toTop);
2557
Wale Ogunwaled32da472018-11-16 07:19:28 -08002558 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 if (stack == null) {
2560 throw new IllegalStateException(
2561 "moveTaskToStack: No stack for stackId=" + stackId);
2562 }
2563 if (!stack.isActivityTypeStandardOrUndefined()) {
2564 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2565 + taskId + " to stack " + stackId);
2566 }
2567 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002568 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002569 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2570 }
2571 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2572 "moveTaskToStack");
2573 } finally {
2574 Binder.restoreCallingIdentity(ident);
2575 }
2576 }
2577 }
2578
2579 @Override
2580 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2581 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583
2584 final long ident = Binder.clearCallingIdentity();
2585 try {
2586 synchronized (mGlobalLock) {
2587 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002588 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002589 if (stack == null) {
2590 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2591 return;
2592 }
2593 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2594 throw new IllegalArgumentException("Stack: " + stackId
2595 + " doesn't support animated resize.");
2596 }
2597 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2598 animationDuration, false /* fromFullscreen */);
2599 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002600 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002601 if (stack == null) {
2602 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2603 return;
2604 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002605 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2607 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2608 }
2609 }
2610 } finally {
2611 Binder.restoreCallingIdentity(ident);
2612 }
2613 }
2614
wilsonshih5c4cf522019-01-25 09:03:47 +08002615 @Override
2616 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2617 int animationDuration) {
2618 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2619
2620 final long ident = Binder.clearCallingIdentity();
2621 try {
2622 synchronized (mGlobalLock) {
2623 if (xOffset == 0 && yOffset == 0) {
2624 return;
2625 }
2626 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2627 if (stack == null) {
2628 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2629 return;
2630 }
2631 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2632 throw new IllegalArgumentException("Stack: " + stackId
2633 + " doesn't support animated resize.");
2634 }
2635 final Rect destBounds = new Rect();
2636 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002637 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002638 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2639 return;
2640 }
2641 destBounds.offset(xOffset, yOffset);
2642 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2643 animationDuration, false /* fromFullscreen */);
2644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(ident);
2647 }
2648 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002649 /**
2650 * Moves the specified task to the primary-split-screen stack.
2651 *
2652 * @param taskId Id of task to move.
2653 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2654 * exist already. See
2655 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2656 * and
2657 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2658 * @param toTop If the task and stack should be moved to the top.
2659 * @param animate Whether we should play an animation for the moving the task.
2660 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2661 * stack. Pass {@code null} to use default bounds.
2662 * @param showRecents If the recents activity should be shown on the other side of the task
2663 * going into split-screen mode.
2664 */
2665 @Override
2666 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2667 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002668 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002669 "setTaskWindowingModeSplitScreenPrimary()");
2670 synchronized (mGlobalLock) {
2671 final long ident = Binder.clearCallingIdentity();
2672 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002673 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002674 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 if (task == null) {
2676 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2677 return false;
2678 }
2679 if (DEBUG_STACK) Slog.d(TAG_STACK,
2680 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2681 + " to createMode=" + createMode + " toTop=" + toTop);
2682 if (!task.isActivityTypeStandardOrUndefined()) {
2683 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2684 + " non-standard task " + taskId + " to split-screen windowing mode");
2685 }
2686
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002687 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 final int windowingMode = task.getWindowingMode();
2689 final ActivityStack stack = task.getStack();
2690 if (toTop) {
2691 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2692 }
2693 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002694 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2695 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 return windowingMode != task.getWindowingMode();
2697 } finally {
2698 Binder.restoreCallingIdentity(ident);
2699 }
2700 }
2701 }
2702
2703 /**
2704 * Removes stacks in the input windowing modes from the system if they are of activity type
2705 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2706 */
2707 @Override
2708 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002709 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 "removeStacksInWindowingModes()");
2711
2712 synchronized (mGlobalLock) {
2713 final long ident = Binder.clearCallingIdentity();
2714 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002715 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002716 } finally {
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720 }
2721
2722 @Override
2723 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 "removeStacksWithActivityTypes()");
2726
2727 synchronized (mGlobalLock) {
2728 final long ident = Binder.clearCallingIdentity();
2729 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002730 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736
2737 @Override
2738 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2739 int userId) {
2740 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2742 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 final boolean detailed = checkGetTasksPermission(
2745 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2746 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 == PackageManager.PERMISSION_GRANTED;
2748
2749 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002750 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 callingUid);
2752 }
2753 }
2754
2755 @Override
2756 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002757 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 long ident = Binder.clearCallingIdentity();
2759 try {
2760 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002761 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 }
2763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
2766 }
2767
2768 @Override
2769 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002770 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 long ident = Binder.clearCallingIdentity();
2772 try {
2773 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002774 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 }
2776 } finally {
2777 Binder.restoreCallingIdentity(ident);
2778 }
2779 }
2780
2781 @Override
2782 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002783 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 final long callingUid = Binder.getCallingUid();
2785 final long origId = Binder.clearCallingIdentity();
2786 try {
2787 synchronized (mGlobalLock) {
2788 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002789 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2791 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2792 }
2793 } finally {
2794 Binder.restoreCallingIdentity(origId);
2795 }
2796 }
2797
2798 @Override
2799 public void startLockTaskModeByToken(IBinder token) {
2800 synchronized (mGlobalLock) {
2801 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2802 if (r == null) {
2803 return;
2804 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002805 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 }
2807 }
2808
2809 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002810 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002811 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 // This makes inner call to look as if it was initiated by system.
2813 long ident = Binder.clearCallingIdentity();
2814 try {
2815 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002816 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002817 MATCH_TASK_IN_STACKS_ONLY);
2818 if (task == null) {
2819 return;
2820 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821
2822 // When starting lock task mode the stack must be in front and focused
2823 task.getStack().moveToFront("startSystemLockTaskMode");
2824 startLockTaskModeLocked(task, true /* isSystemCaller */);
2825 }
2826 } finally {
2827 Binder.restoreCallingIdentity(ident);
2828 }
2829 }
2830
2831 @Override
2832 public void stopLockTaskModeByToken(IBinder token) {
2833 synchronized (mGlobalLock) {
2834 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2835 if (r == null) {
2836 return;
2837 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002838 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 }
2840 }
2841
2842 /**
2843 * This API should be called by SystemUI only when user perform certain action to dismiss
2844 * lock task mode. We should only dismiss pinned lock task mode in this case.
2845 */
2846 @Override
2847 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002848 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2850 }
2851
2852 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2853 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2854 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2855 return;
2856 }
2857
Wale Ogunwaled32da472018-11-16 07:19:28 -08002858 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002859 if (stack == null || task != stack.topTask()) {
2860 throw new IllegalArgumentException("Invalid task, not in foreground");
2861 }
2862
2863 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2864 // system or a specific app.
2865 // * System-initiated requests will only start the pinned mode (screen pinning)
2866 // * App-initiated requests
2867 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2868 // - will start the pinned mode, otherwise
2869 final int callingUid = Binder.getCallingUid();
2870 long ident = Binder.clearCallingIdentity();
2871 try {
2872 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002873 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002875 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 } finally {
2877 Binder.restoreCallingIdentity(ident);
2878 }
2879 }
2880
2881 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2882 final int callingUid = Binder.getCallingUid();
2883 long ident = Binder.clearCallingIdentity();
2884 try {
2885 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002886 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 }
2888 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2889 // task and jumping straight into a call in the case of emergency call back.
2890 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2891 if (tm != null) {
2892 tm.showInCallScreen(false);
2893 }
2894 } finally {
2895 Binder.restoreCallingIdentity(ident);
2896 }
2897 }
2898
2899 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002900 public void updateLockTaskPackages(int userId, String[] packages) {
2901 final int callingUid = Binder.getCallingUid();
2902 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2903 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2904 "updateLockTaskPackages()");
2905 }
2906 synchronized (this) {
2907 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2908 + Arrays.toString(packages));
2909 getLockTaskController().updateLockTaskPackages(userId, packages);
2910 }
2911 }
2912
2913 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 public boolean isInLockTaskMode() {
2915 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2916 }
2917
2918 @Override
2919 public int getLockTaskModeState() {
2920 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002921 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 }
2923 }
2924
2925 @Override
2926 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2927 synchronized (mGlobalLock) {
2928 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2929 if (r != null) {
2930 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002931 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002933 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 }
2935 }
2936 }
2937
2938 @Override
2939 public Bundle getActivityOptions(IBinder token) {
2940 final long origId = Binder.clearCallingIdentity();
2941 try {
2942 synchronized (mGlobalLock) {
2943 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2944 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002945 final ActivityOptions activityOptions = r.takeOptionsLocked(
2946 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 return activityOptions == null ? null : activityOptions.toBundle();
2948 }
2949 return null;
2950 }
2951 } finally {
2952 Binder.restoreCallingIdentity(origId);
2953 }
2954 }
2955
2956 @Override
2957 public List<IBinder> getAppTasks(String callingPackage) {
2958 int callingUid = Binder.getCallingUid();
2959 long ident = Binder.clearCallingIdentity();
2960 try {
2961 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002962 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 }
2964 } finally {
2965 Binder.restoreCallingIdentity(ident);
2966 }
2967 }
2968
2969 @Override
2970 public void finishVoiceTask(IVoiceInteractionSession session) {
2971 synchronized (mGlobalLock) {
2972 final long origId = Binder.clearCallingIdentity();
2973 try {
2974 // TODO: VI Consider treating local voice interactions and voice tasks
2975 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002976 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 } finally {
2978 Binder.restoreCallingIdentity(origId);
2979 }
2980 }
2981
2982 }
2983
2984 @Override
2985 public boolean isTopOfTask(IBinder token) {
2986 synchronized (mGlobalLock) {
2987 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002988 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989 }
2990 }
2991
2992 @Override
2993 public void notifyLaunchTaskBehindComplete(IBinder token) {
2994 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2995 }
2996
2997 @Override
2998 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002999 mH.post(() -> {
3000 synchronized (mGlobalLock) {
3001 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003002 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003003 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003004 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003005 } catch (RemoteException e) {
3006 }
3007 }
3008 }
3009
3010 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 }
3012
3013 /** Called from an app when assist data is ready. */
3014 @Override
3015 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3016 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003017 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 synchronized (pae) {
3019 pae.result = extras;
3020 pae.structure = structure;
3021 pae.content = content;
3022 if (referrer != null) {
3023 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3024 }
3025 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003026 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003027 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3028 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 structure.setHomeActivity(pae.isHome);
3030 }
3031 pae.haveResult = true;
3032 pae.notifyAll();
3033 if (pae.intent == null && pae.receiver == null) {
3034 // Caller is just waiting for the result.
3035 return;
3036 }
3037 }
3038 // We are now ready to launch the assist activity.
3039 IAssistDataReceiver sendReceiver = null;
3040 Bundle sendBundle = null;
3041 synchronized (mGlobalLock) {
3042 buildAssistBundleLocked(pae, extras);
3043 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 if (!exists) {
3046 // Timed out.
3047 return;
3048 }
3049
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003050 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 // Caller wants result sent back to them.
3052 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003053 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3054 pae.activity.getTaskRecord().taskId);
3055 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3056 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003057 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3058 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3059 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3060 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3061 }
3062 }
3063 if (sendReceiver != null) {
3064 try {
3065 sendReceiver.onHandleAssistData(sendBundle);
3066 } catch (RemoteException e) {
3067 }
3068 return;
3069 }
3070
3071 final long ident = Binder.clearCallingIdentity();
3072 try {
3073 if (TextUtils.equals(pae.intent.getAction(),
3074 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003075 // Start voice interaction through VoiceInteractionManagerService.
3076 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3077 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 } else {
3079 pae.intent.replaceExtras(pae.extras);
3080 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3081 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3082 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003083 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084
3085 try {
3086 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3087 } catch (ActivityNotFoundException e) {
3088 Slog.w(TAG, "No activity to handle assist action.", e);
3089 }
3090 }
3091 } finally {
3092 Binder.restoreCallingIdentity(ident);
3093 }
3094 }
3095
3096 @Override
3097 public int addAppTask(IBinder activityToken, Intent intent,
3098 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3099 final int callingUid = Binder.getCallingUid();
3100 final long callingIdent = Binder.clearCallingIdentity();
3101
3102 try {
3103 synchronized (mGlobalLock) {
3104 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3105 if (r == null) {
3106 throw new IllegalArgumentException("Activity does not exist; token="
3107 + activityToken);
3108 }
3109 ComponentName comp = intent.getComponent();
3110 if (comp == null) {
3111 throw new IllegalArgumentException("Intent " + intent
3112 + " must specify explicit component");
3113 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003114 if (thumbnail.getWidth() != mThumbnailWidth
3115 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 throw new IllegalArgumentException("Bad thumbnail size: got "
3117 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003118 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 }
3120 if (intent.getSelector() != null) {
3121 intent.setSelector(null);
3122 }
3123 if (intent.getSourceBounds() != null) {
3124 intent.setSourceBounds(null);
3125 }
3126 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3127 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3128 // The caller has added this as an auto-remove task... that makes no
3129 // sense, so turn off auto-remove.
3130 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3131 }
3132 }
3133 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3134 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3135 if (ainfo.applicationInfo.uid != callingUid) {
3136 throw new SecurityException(
3137 "Can't add task for another application: target uid="
3138 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3139 }
3140
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003141 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003143 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003145 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 // The app has too many tasks already and we can't add any more
3147 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3148 return INVALID_TASK_ID;
3149 }
3150 task.lastTaskDescription.copyFrom(description);
3151
3152 // TODO: Send the thumbnail to WM to store it.
3153
3154 return task.taskId;
3155 }
3156 } finally {
3157 Binder.restoreCallingIdentity(callingIdent);
3158 }
3159 }
3160
3161 @Override
3162 public Point getAppTaskThumbnailSize() {
3163 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003164 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 }
3166 }
3167
3168 @Override
3169 public void setTaskResizeable(int taskId, int resizeableMode) {
3170 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003171 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3173 if (task == null) {
3174 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3175 return;
3176 }
3177 task.setResizeMode(resizeableMode);
3178 }
3179 }
3180
3181 @Override
3182 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003183 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 long ident = Binder.clearCallingIdentity();
3185 try {
3186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003187 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003188 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 if (task == null) {
3190 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3191 return;
3192 }
3193 // Place the task in the right stack if it isn't there already based on
3194 // the requested bounds.
3195 // The stack transition logic is:
3196 // - a null bounds on a freeform task moves that task to fullscreen
3197 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3198 // that task to freeform
3199 // - otherwise the task is not moved
3200 ActivityStack stack = task.getStack();
3201 if (!task.getWindowConfiguration().canResizeTask()) {
3202 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3203 }
3204 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3205 stack = stack.getDisplay().getOrCreateStack(
3206 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3207 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3208 stack = stack.getDisplay().getOrCreateStack(
3209 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3210 }
3211
3212 // Reparent the task to the right stack if necessary
3213 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3214 if (stack != task.getStack()) {
3215 // Defer resume until the task is resized below
3216 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3217 DEFER_RESUME, "resizeTask");
3218 preserveWindow = false;
3219 }
3220
3221 // After reparenting (which only resizes the task to the stack bounds), resize the
3222 // task to the actual bounds provided
3223 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3224 }
3225 } finally {
3226 Binder.restoreCallingIdentity(ident);
3227 }
3228 }
3229
3230 @Override
3231 public boolean releaseActivityInstance(IBinder token) {
3232 synchronized (mGlobalLock) {
3233 final long origId = Binder.clearCallingIdentity();
3234 try {
3235 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3236 if (r == null) {
3237 return false;
3238 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003239 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 } finally {
3241 Binder.restoreCallingIdentity(origId);
3242 }
3243 }
3244 }
3245
3246 @Override
3247 public void releaseSomeActivities(IApplicationThread appInt) {
3248 synchronized (mGlobalLock) {
3249 final long origId = Binder.clearCallingIdentity();
3250 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003251 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003252 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 } finally {
3254 Binder.restoreCallingIdentity(origId);
3255 }
3256 }
3257 }
3258
3259 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003260 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003261 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 != PackageManager.PERMISSION_GRANTED) {
3263 throw new SecurityException("Requires permission "
3264 + android.Manifest.permission.DEVICE_POWER);
3265 }
3266
3267 synchronized (mGlobalLock) {
3268 long ident = Binder.clearCallingIdentity();
3269 if (mKeyguardShown != keyguardShowing) {
3270 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003271 final Message msg = PooledLambda.obtainMessage(
3272 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3273 keyguardShowing);
3274 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 }
3276 try {
wilsonshih177261f2019-02-22 12:02:18 +08003277 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 } finally {
3279 Binder.restoreCallingIdentity(ident);
3280 }
3281 }
3282
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003283 mH.post(() -> {
3284 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3285 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3286 }
3287 });
3288 }
3289
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003290 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003291 mH.post(() -> {
3292 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3293 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3294 }
3295 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 }
3297
3298 @Override
3299 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003300 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3301 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302
3303 final File passedIconFile = new File(filePath);
3304 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3305 passedIconFile.getName());
3306 if (!legitIconFile.getPath().equals(filePath)
3307 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3308 throw new IllegalArgumentException("Bad file path: " + filePath
3309 + " passed for userId " + userId);
3310 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003311 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 }
3313
3314 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003315 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3317 final ActivityOptions activityOptions = safeOptions != null
3318 ? safeOptions.getOptions(mStackSupervisor)
3319 : null;
3320 if (activityOptions == null
3321 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3322 || activityOptions.getCustomInPlaceResId() == 0) {
3323 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3324 "with valid animation");
3325 }
lumark588a3e82018-07-20 18:53:54 +08003326 // Get top display of front most application.
3327 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3328 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003329 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3330 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3331 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003332 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003333 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003334 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 }
3336
3337 @Override
3338 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003339 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 synchronized (mGlobalLock) {
3341 final long ident = Binder.clearCallingIdentity();
3342 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003343 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 if (stack == null) {
3345 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3346 return;
3347 }
3348 if (!stack.isActivityTypeStandardOrUndefined()) {
3349 throw new IllegalArgumentException(
3350 "Removing non-standard stack is not allowed.");
3351 }
3352 mStackSupervisor.removeStack(stack);
3353 } finally {
3354 Binder.restoreCallingIdentity(ident);
3355 }
3356 }
3357 }
3358
3359 @Override
3360 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362
3363 synchronized (mGlobalLock) {
3364 final long ident = Binder.clearCallingIdentity();
3365 try {
3366 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3367 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003368 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 } finally {
3370 Binder.restoreCallingIdentity(ident);
3371 }
3372 }
3373 }
3374
3375 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003376 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 synchronized (mGlobalLock) {
3378 long ident = Binder.clearCallingIdentity();
3379 try {
3380 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3381 if (r == null) {
3382 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003383 "toggleFreeformWindowingMode: No activity record matching token="
3384 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 }
3386
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003387 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003388 if (stack == null) {
3389 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3390 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392
Yunfan Chend967af82019-01-17 18:30:18 +09003393 if (!stack.inFreeformWindowingMode()
3394 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3395 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3396 + "toggle between fullscreen and freeform.");
3397 }
3398
3399 if (stack.inFreeformWindowingMode()) {
3400 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003401 } else if (stack.getParent().inFreeformWindowingMode()) {
3402 // If the window is on a freeform display, set it to undefined. It will be
3403 // resolved to freeform and it can adjust windowing mode when the display mode
3404 // changes in runtime.
3405 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003406 } else {
3407 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3408 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 } finally {
3410 Binder.restoreCallingIdentity(ident);
3411 }
3412 }
3413 }
3414
3415 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3416 @Override
3417 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003418 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003420 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 }
3422
3423 /** Unregister a task stack listener so that it stops receiving callbacks. */
3424 @Override
3425 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003426 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003428 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 }
3430
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 @Override
3432 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3433 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3434 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3435 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3436 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3437 }
3438
3439 @Override
3440 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3441 IBinder activityToken, int flags) {
3442 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3443 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3444 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3445 }
3446
3447 @Override
3448 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3449 Bundle args) {
3450 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3451 true /* focused */, true /* newSessionId */, userHandle, args,
3452 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3453 }
3454
3455 @Override
3456 public Bundle getAssistContextExtras(int requestType) {
3457 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3458 null, null, true /* focused */, true /* newSessionId */,
3459 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3460 if (pae == null) {
3461 return null;
3462 }
3463 synchronized (pae) {
3464 while (!pae.haveResult) {
3465 try {
3466 pae.wait();
3467 } catch (InterruptedException e) {
3468 }
3469 }
3470 }
3471 synchronized (mGlobalLock) {
3472 buildAssistBundleLocked(pae, pae.result);
3473 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003474 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 }
3476 return pae.extras;
3477 }
3478
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003479 /**
3480 * Binder IPC calls go through the public entry point.
3481 * This can be called with or without the global lock held.
3482 */
3483 private static int checkCallingPermission(String permission) {
3484 return checkPermission(
3485 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3486 }
3487
3488 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003489 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003490 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3491 mAmInternal.enforceCallingPermission(permission, func);
3492 }
3493 }
3494
3495 @VisibleForTesting
3496 int checkGetTasksPermission(String permission, int pid, int uid) {
3497 return checkPermission(permission, pid, uid);
3498 }
3499
3500 static int checkPermission(String permission, int pid, int uid) {
3501 if (permission == null) {
3502 return PackageManager.PERMISSION_DENIED;
3503 }
3504 return checkComponentPermission(permission, pid, uid, -1, true);
3505 }
3506
Wale Ogunwale214f3482018-10-04 11:00:47 -07003507 public static int checkComponentPermission(String permission, int pid, int uid,
3508 int owningUid, boolean exported) {
3509 return ActivityManagerService.checkComponentPermission(
3510 permission, pid, uid, owningUid, exported);
3511 }
3512
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003513 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3514 if (getRecentTasks().isCallerRecents(callingUid)) {
3515 // Always allow the recents component to get tasks
3516 return true;
3517 }
3518
3519 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3520 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3521 if (!allowed) {
3522 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3523 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3524 // Temporary compatibility: some existing apps on the system image may
3525 // still be requesting the old permission and not switched to the new
3526 // one; if so, we'll still allow them full access. This means we need
3527 // to see if they are holding the old permission and are a system app.
3528 try {
3529 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3530 allowed = true;
3531 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3532 + " is using old GET_TASKS but privileged; allowing");
3533 }
3534 } catch (RemoteException e) {
3535 }
3536 }
3537 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3538 + " does not hold REAL_GET_TASKS; limiting output");
3539 }
3540 return allowed;
3541 }
3542
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003543 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3544 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3545 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3546 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003547 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 "enqueueAssistContext()");
3549
3550 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003551 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 if (activity == null) {
3553 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3554 return null;
3555 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003556 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3558 return null;
3559 }
3560 if (focused) {
3561 if (activityToken != null) {
3562 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3563 if (activity != caller) {
3564 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3565 + " is not current top " + activity);
3566 return null;
3567 }
3568 }
3569 } else {
3570 activity = ActivityRecord.forTokenLocked(activityToken);
3571 if (activity == null) {
3572 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3573 + " couldn't be found");
3574 return null;
3575 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003576 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3578 return null;
3579 }
3580 }
3581
3582 PendingAssistExtras pae;
3583 Bundle extras = new Bundle();
3584 if (args != null) {
3585 extras.putAll(args);
3586 }
3587 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003588 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589
3590 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3591 userHandle);
3592 pae.isHome = activity.isActivityTypeHome();
3593
3594 // Increment the sessionId if necessary
3595 if (newSessionId) {
3596 mViSessionId++;
3597 }
3598 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3600 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 } catch (RemoteException e) {
3604 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3605 return null;
3606 }
3607 return pae;
3608 }
3609 }
3610
3611 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3612 if (result != null) {
3613 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3614 }
3615 if (pae.hint != null) {
3616 pae.extras.putBoolean(pae.hint, true);
3617 }
3618 }
3619
3620 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3621 IAssistDataReceiver receiver;
3622 synchronized (mGlobalLock) {
3623 mPendingAssistExtras.remove(pae);
3624 receiver = pae.receiver;
3625 }
3626 if (receiver != null) {
3627 // Caller wants result sent back to them.
3628 Bundle sendBundle = new Bundle();
3629 // At least return the receiver extras
3630 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3631 try {
3632 pae.receiver.onHandleAssistData(sendBundle);
3633 } catch (RemoteException e) {
3634 }
3635 }
3636 }
3637
3638 public class PendingAssistExtras extends Binder implements Runnable {
3639 public final ActivityRecord activity;
3640 public boolean isHome;
3641 public final Bundle extras;
3642 public final Intent intent;
3643 public final String hint;
3644 public final IAssistDataReceiver receiver;
3645 public final int userHandle;
3646 public boolean haveResult = false;
3647 public Bundle result = null;
3648 public AssistStructure structure = null;
3649 public AssistContent content = null;
3650 public Bundle receiverExtras;
3651
3652 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3653 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3654 int _userHandle) {
3655 activity = _activity;
3656 extras = _extras;
3657 intent = _intent;
3658 hint = _hint;
3659 receiver = _receiver;
3660 receiverExtras = _receiverExtras;
3661 userHandle = _userHandle;
3662 }
3663
3664 @Override
3665 public void run() {
3666 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3667 synchronized (this) {
3668 haveResult = true;
3669 notifyAll();
3670 }
3671 pendingAssistExtrasTimedOut(this);
3672 }
3673 }
3674
3675 @Override
3676 public boolean isAssistDataAllowedOnCurrentActivity() {
3677 int userId;
3678 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003679 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3681 return false;
3682 }
3683
3684 final ActivityRecord activity = focusedStack.getTopActivity();
3685 if (activity == null) {
3686 return false;
3687 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003688 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 }
3690 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3691 }
3692
3693 @Override
3694 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3695 long ident = Binder.clearCallingIdentity();
3696 try {
3697 synchronized (mGlobalLock) {
3698 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003699 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003700 if (top != caller) {
3701 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3702 + " is not current top " + top);
3703 return false;
3704 }
3705 if (!top.nowVisible) {
3706 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3707 + " is not visible");
3708 return false;
3709 }
3710 }
3711 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3712 token);
3713 } finally {
3714 Binder.restoreCallingIdentity(ident);
3715 }
3716 }
3717
3718 @Override
3719 public boolean isRootVoiceInteraction(IBinder token) {
3720 synchronized (mGlobalLock) {
3721 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3722 if (r == null) {
3723 return false;
3724 }
3725 return r.rootVoiceInteraction;
3726 }
3727 }
3728
Wale Ogunwalef6733932018-06-27 05:14:34 -07003729 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3730 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3731 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3732 if (activityToCallback == null) return;
3733 activityToCallback.setVoiceSessionLocked(voiceSession);
3734
3735 // Inform the activity
3736 try {
3737 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3738 voiceInteractor);
3739 long token = Binder.clearCallingIdentity();
3740 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003741 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003742 } finally {
3743 Binder.restoreCallingIdentity(token);
3744 }
3745 // TODO: VI Should we cache the activity so that it's easier to find later
3746 // rather than scan through all the stacks and activities?
3747 } catch (RemoteException re) {
3748 activityToCallback.clearVoiceSessionLocked();
3749 // TODO: VI Should this terminate the voice session?
3750 }
3751 }
3752
3753 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3754 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3755 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3756 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3757 boolean wasRunningVoice = mRunningVoice != null;
3758 mRunningVoice = session;
3759 if (!wasRunningVoice) {
3760 mVoiceWakeLock.acquire();
3761 updateSleepIfNeededLocked();
3762 }
3763 }
3764 }
3765
3766 void finishRunningVoiceLocked() {
3767 if (mRunningVoice != null) {
3768 mRunningVoice = null;
3769 mVoiceWakeLock.release();
3770 updateSleepIfNeededLocked();
3771 }
3772 }
3773
3774 @Override
3775 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3776 synchronized (mGlobalLock) {
3777 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3778 if (keepAwake) {
3779 mVoiceWakeLock.acquire();
3780 } else {
3781 mVoiceWakeLock.release();
3782 }
3783 }
3784 }
3785 }
3786
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 @Override
3788 public ComponentName getActivityClassForToken(IBinder token) {
3789 synchronized (mGlobalLock) {
3790 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3791 if (r == null) {
3792 return null;
3793 }
3794 return r.intent.getComponent();
3795 }
3796 }
3797
3798 @Override
3799 public String getPackageForToken(IBinder token) {
3800 synchronized (mGlobalLock) {
3801 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3802 if (r == null) {
3803 return null;
3804 }
3805 return r.packageName;
3806 }
3807 }
3808
3809 @Override
3810 public void showLockTaskEscapeMessage(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3813 if (r == null) {
3814 return;
3815 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003816 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 }
3818 }
3819
3820 @Override
3821 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003822 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 final long token = Binder.clearCallingIdentity();
3824 try {
3825 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003826 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 }
3828 } finally {
3829 Binder.restoreCallingIdentity(token);
3830 }
3831 }
3832
3833 /**
3834 * Try to place task to provided position. The final position might be different depending on
3835 * current user and stacks state. The task will be moved to target stack if it's currently in
3836 * different stack.
3837 */
3838 @Override
3839 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003840 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 synchronized (mGlobalLock) {
3842 long ident = Binder.clearCallingIdentity();
3843 try {
3844 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3845 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003846 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 if (task == null) {
3848 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3849 + taskId);
3850 }
3851
Wale Ogunwaled32da472018-11-16 07:19:28 -08003852 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853
3854 if (stack == null) {
3855 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3856 + stackId);
3857 }
3858 if (!stack.isActivityTypeStandardOrUndefined()) {
3859 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3860 + " the position of task " + taskId + " in/to non-standard stack");
3861 }
3862
3863 // TODO: Have the callers of this API call a separate reparent method if that is
3864 // what they intended to do vs. having this method also do reparenting.
3865 if (task.getStack() == stack) {
3866 // Change position in current stack.
3867 stack.positionChildAt(task, position);
3868 } else {
3869 // Reparent to new stack.
3870 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3871 !DEFER_RESUME, "positionTaskInStack");
3872 }
3873 } finally {
3874 Binder.restoreCallingIdentity(ident);
3875 }
3876 }
3877 }
3878
3879 @Override
3880 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3881 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3882 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003883 + Arrays.toString(horizontalSizeConfiguration) + " "
3884 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 synchronized (mGlobalLock) {
3886 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3887 if (record == null) {
3888 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3889 + "found for: " + token);
3890 }
3891 record.setSizeConfigurations(horizontalSizeConfiguration,
3892 verticalSizeConfigurations, smallestSizeConfigurations);
3893 }
3894 }
3895
3896 /**
3897 * Dismisses split-screen multi-window mode.
3898 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3899 */
3900 @Override
3901 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003902 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3904 final long ident = Binder.clearCallingIdentity();
3905 try {
3906 synchronized (mGlobalLock) {
3907 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003908 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 if (stack == null) {
3910 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3911 return;
3912 }
3913
3914 if (toTop) {
3915 // Caller wants the current split-screen primary stack to be the top stack after
3916 // it goes fullscreen, so move it to the front.
3917 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003918 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003920 // stack after it goes fullscreen, so we move the focus to the top-most
3921 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3923 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3924 if (otherStack != null) {
3925 otherStack.moveToFront("dismissSplitScreenMode_other");
3926 }
3927 }
3928
Evan Rosky10475742018-09-05 19:02:48 -07003929 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 }
3931 } finally {
3932 Binder.restoreCallingIdentity(ident);
3933 }
3934 }
3935
3936 /**
3937 * Dismisses Pip
3938 * @param animate True if the dismissal should be animated.
3939 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3940 * default animation duration should be used.
3941 */
3942 @Override
3943 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003944 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 final long ident = Binder.clearCallingIdentity();
3946 try {
3947 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003948 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003949 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 if (stack == null) {
3951 Slog.w(TAG, "dismissPip: pinned stack not found.");
3952 return;
3953 }
3954 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3955 throw new IllegalArgumentException("Stack: " + stack
3956 + " doesn't support animated resize.");
3957 }
3958 if (animate) {
3959 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3960 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3961 } else {
3962 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3963 }
3964 }
3965 } finally {
3966 Binder.restoreCallingIdentity(ident);
3967 }
3968 }
3969
3970 @Override
3971 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003972 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 synchronized (mGlobalLock) {
3974 mSuppressResizeConfigChanges = suppress;
3975 }
3976 }
3977
3978 /**
3979 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3980 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3981 * activity and clearing the task at the same time.
3982 */
3983 @Override
3984 // TODO: API should just be about changing windowing modes...
3985 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 "moveTasksToFullscreenStack()");
3988 synchronized (mGlobalLock) {
3989 final long origId = Binder.clearCallingIdentity();
3990 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003991 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 if (stack != null){
3993 if (!stack.isActivityTypeStandardOrUndefined()) {
3994 throw new IllegalArgumentException(
3995 "You can't move tasks from non-standard stacks.");
3996 }
3997 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3998 }
3999 } finally {
4000 Binder.restoreCallingIdentity(origId);
4001 }
4002 }
4003 }
4004
4005 /**
4006 * Moves the top activity in the input stackId to the pinned stack.
4007 *
4008 * @param stackId Id of stack to move the top activity to pinned stack.
4009 * @param bounds Bounds to use for pinned stack.
4010 *
4011 * @return True if the top activity of the input stack was successfully moved to the pinned
4012 * stack.
4013 */
4014 @Override
4015 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004016 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 "moveTopActivityToPinnedStack()");
4018 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4021 + "Device doesn't support picture-in-picture mode");
4022 }
4023
4024 long ident = Binder.clearCallingIdentity();
4025 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004026 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 } finally {
4028 Binder.restoreCallingIdentity(ident);
4029 }
4030 }
4031 }
4032
4033 @Override
4034 public boolean isInMultiWindowMode(IBinder token) {
4035 final long origId = Binder.clearCallingIdentity();
4036 try {
4037 synchronized (mGlobalLock) {
4038 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4039 if (r == null) {
4040 return false;
4041 }
4042 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4043 return r.inMultiWindowMode();
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(origId);
4047 }
4048 }
4049
4050 @Override
4051 public boolean isInPictureInPictureMode(IBinder token) {
4052 final long origId = Binder.clearCallingIdentity();
4053 try {
4054 synchronized (mGlobalLock) {
4055 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4056 }
4057 } finally {
4058 Binder.restoreCallingIdentity(origId);
4059 }
4060 }
4061
4062 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004063 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4064 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 return false;
4066 }
4067
4068 // If we are animating to fullscreen then we have already dispatched the PIP mode
4069 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004070 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4071 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 }
4073
4074 @Override
4075 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4076 final long origId = Binder.clearCallingIdentity();
4077 try {
4078 synchronized (mGlobalLock) {
4079 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4080 "enterPictureInPictureMode", token, params);
4081
4082 // If the activity is already in picture in picture mode, then just return early
4083 if (isInPictureInPictureMode(r)) {
4084 return true;
4085 }
4086
4087 // Activity supports picture-in-picture, now check that we can enter PiP at this
4088 // point, if it is
4089 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4090 false /* beforeStopping */)) {
4091 return false;
4092 }
4093
4094 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004095 synchronized (mGlobalLock) {
4096 // Only update the saved args from the args that are set
4097 r.pictureInPictureArgs.copyOnlySet(params);
4098 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4099 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4100 // Adjust the source bounds by the insets for the transition down
4101 final Rect sourceBounds = new Rect(
4102 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004103 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004104 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004105 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 stack.setPictureInPictureAspectRatio(aspectRatio);
4107 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004108 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4109 r.info.applicationInfo.uid, r.shortComponentName,
4110 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004111 logPictureInPictureArgs(params);
4112 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 };
4114
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004115 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 // If the keyguard is showing or occluded, then try and dismiss it before
4117 // entering picture-in-picture (this will prompt the user to authenticate if the
4118 // device is currently locked).
4119 dismissKeyguard(token, new KeyguardDismissCallback() {
4120 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 public void onDismissSucceeded() {
4122 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 }
4124 }, null /* message */);
4125 } else {
4126 // Enter picture in picture immediately otherwise
4127 enterPipRunnable.run();
4128 }
4129 return true;
4130 }
4131 } finally {
4132 Binder.restoreCallingIdentity(origId);
4133 }
4134 }
4135
4136 @Override
4137 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4138 final long origId = Binder.clearCallingIdentity();
4139 try {
4140 synchronized (mGlobalLock) {
4141 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4142 "setPictureInPictureParams", token, params);
4143
4144 // Only update the saved args from the args that are set
4145 r.pictureInPictureArgs.copyOnlySet(params);
4146 if (r.inPinnedWindowingMode()) {
4147 // If the activity is already in picture-in-picture, update the pinned stack now
4148 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4149 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004150 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 if (!stack.isAnimatingBoundsToFullscreen()) {
4152 stack.setPictureInPictureAspectRatio(
4153 r.pictureInPictureArgs.getAspectRatio());
4154 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4155 }
4156 }
4157 logPictureInPictureArgs(params);
4158 }
4159 } finally {
4160 Binder.restoreCallingIdentity(origId);
4161 }
4162 }
4163
4164 @Override
4165 public int getMaxNumPictureInPictureActions(IBinder token) {
4166 // Currently, this is a static constant, but later, we may change this to be dependent on
4167 // the context of the activity
4168 return 3;
4169 }
4170
4171 private void logPictureInPictureArgs(PictureInPictureParams params) {
4172 if (params.hasSetActions()) {
4173 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4174 params.getActions().size());
4175 }
4176 if (params.hasSetAspectRatio()) {
4177 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4178 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4179 MetricsLogger.action(lm);
4180 }
4181 }
4182
4183 /**
4184 * Checks the state of the system and the activity associated with the given {@param token} to
4185 * verify that picture-in-picture is supported for that activity.
4186 *
4187 * @return the activity record for the given {@param token} if all the checks pass.
4188 */
4189 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4190 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 throw new IllegalStateException(caller
4193 + ": Device doesn't support picture-in-picture mode.");
4194 }
4195
4196 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4197 if (r == null) {
4198 throw new IllegalStateException(caller
4199 + ": Can't find activity for token=" + token);
4200 }
4201
4202 if (!r.supportsPictureInPicture()) {
4203 throw new IllegalStateException(caller
4204 + ": Current activity does not support picture-in-picture.");
4205 }
4206
4207 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004208 && !mWindowManager.isValidPictureInPictureAspectRatio(
4209 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 final float minAspectRatio = mContext.getResources().getFloat(
4211 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4212 final float maxAspectRatio = mContext.getResources().getFloat(
4213 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4214 throw new IllegalArgumentException(String.format(caller
4215 + ": Aspect ratio is too extreme (must be between %f and %f).",
4216 minAspectRatio, maxAspectRatio));
4217 }
4218
4219 // Truncate the number of actions if necessary
4220 params.truncateActions(getMaxNumPictureInPictureActions(token));
4221
4222 return r;
4223 }
4224
4225 @Override
4226 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004227 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 synchronized (mGlobalLock) {
4229 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4230 if (r == null) {
4231 throw new IllegalArgumentException("Activity does not exist; token="
4232 + activityToken);
4233 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004234 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 }
4236 }
4237
4238 @Override
4239 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4240 Rect tempDockedTaskInsetBounds,
4241 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 long ident = Binder.clearCallingIdentity();
4244 try {
4245 synchronized (mGlobalLock) {
4246 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4247 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4248 PRESERVE_WINDOWS);
4249 }
4250 } finally {
4251 Binder.restoreCallingIdentity(ident);
4252 }
4253 }
4254
4255 @Override
4256 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 final long ident = Binder.clearCallingIdentity();
4259 try {
4260 synchronized (mGlobalLock) {
4261 mStackSupervisor.setSplitScreenResizing(resizing);
4262 }
4263 } finally {
4264 Binder.restoreCallingIdentity(ident);
4265 }
4266 }
4267
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 /**
4269 * Check that we have the features required for VR-related API calls, and throw an exception if
4270 * not.
4271 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004272 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 if (!mContext.getPackageManager().hasSystemFeature(
4274 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4275 throw new UnsupportedOperationException("VR mode not supported on this device!");
4276 }
4277 }
4278
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 @Override
4280 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004281 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282
4283 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4284
4285 ActivityRecord r;
4286 synchronized (mGlobalLock) {
4287 r = ActivityRecord.isInStackLocked(token);
4288 }
4289
4290 if (r == null) {
4291 throw new IllegalArgumentException();
4292 }
4293
4294 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004295 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 VrManagerInternal.NO_ERROR) {
4297 return err;
4298 }
4299
4300 // Clear the binder calling uid since this path may call moveToTask().
4301 final long callingId = Binder.clearCallingIdentity();
4302 try {
4303 synchronized (mGlobalLock) {
4304 r.requestedVrComponent = (enabled) ? packageName : null;
4305
4306 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004307 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004308 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 }
4310 return 0;
4311 }
4312 } finally {
4313 Binder.restoreCallingIdentity(callingId);
4314 }
4315 }
4316
4317 @Override
4318 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4319 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4320 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004321 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4323 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4324 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004325 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 || activity.voiceSession != null) {
4327 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4328 return;
4329 }
4330 if (activity.pendingVoiceInteractionStart) {
4331 Slog.w(TAG, "Pending start of voice interaction already.");
4332 return;
4333 }
4334 activity.pendingVoiceInteractionStart = true;
4335 }
4336 LocalServices.getService(VoiceInteractionManagerInternal.class)
4337 .startLocalVoiceInteraction(callingActivity, options);
4338 }
4339
4340 @Override
4341 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4342 LocalServices.getService(VoiceInteractionManagerInternal.class)
4343 .stopLocalVoiceInteraction(callingActivity);
4344 }
4345
4346 @Override
4347 public boolean supportsLocalVoiceInteraction() {
4348 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4349 .supportsLocalVoiceInteraction();
4350 }
4351
4352 /** Notifies all listeners when the pinned stack animation starts. */
4353 @Override
4354 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004355 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
4357
4358 /** Notifies all listeners when the pinned stack animation ends. */
4359 @Override
4360 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
4364 @Override
4365 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 final long ident = Binder.clearCallingIdentity();
4368 try {
4369 synchronized (mGlobalLock) {
4370 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4371 }
4372 } finally {
4373 Binder.restoreCallingIdentity(ident);
4374 }
4375 }
4376
4377 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380
4381 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004382 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004384 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 }
4386
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004388 final Message msg = PooledLambda.obtainMessage(
4389 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4390 DEFAULT_DISPLAY);
4391 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 }
4393
4394 final long origId = Binder.clearCallingIdentity();
4395 try {
4396 if (values != null) {
4397 Settings.System.clearConfiguration(values);
4398 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004399 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400 UserHandle.USER_NULL, false /* deferResume */,
4401 mTmpUpdateConfigurationResult);
4402 return mTmpUpdateConfigurationResult.changes != 0;
4403 } finally {
4404 Binder.restoreCallingIdentity(origId);
4405 }
4406 }
4407 }
4408
4409 @Override
4410 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4411 CharSequence message) {
4412 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4415 }
4416 final long callingId = Binder.clearCallingIdentity();
4417 try {
4418 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004419 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421 } finally {
4422 Binder.restoreCallingIdentity(callingId);
4423 }
4424 }
4425
4426 @Override
4427 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 "cancelTaskWindowTransition()");
4430 final long ident = Binder.clearCallingIdentity();
4431 try {
4432 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004433 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 MATCH_TASK_IN_STACKS_ONLY);
4435 if (task == null) {
4436 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4437 return;
4438 }
4439 task.cancelWindowTransition();
4440 }
4441 } finally {
4442 Binder.restoreCallingIdentity(ident);
4443 }
4444 }
4445
4446 @Override
4447 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 final long ident = Binder.clearCallingIdentity();
4450 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004451 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 } finally {
4453 Binder.restoreCallingIdentity(ident);
4454 }
4455 }
4456
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004457 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4458 boolean restoreFromDisk) {
4459 final TaskRecord task;
4460 synchronized (mGlobalLock) {
4461 task = mRootActivityContainer.anyTaskForId(taskId,
4462 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4463 if (task == null) {
4464 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4465 return null;
4466 }
4467 }
4468 // Don't call this while holding the lock as this operation might hit the disk.
4469 return task.getSnapshot(reducedResolution, restoreFromDisk);
4470 }
4471
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 @Override
4473 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4474 synchronized (mGlobalLock) {
4475 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4476 if (r == null) {
4477 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4478 + token);
4479 return;
4480 }
4481 final long origId = Binder.clearCallingIdentity();
4482 try {
4483 r.setDisablePreviewScreenshots(disable);
4484 } finally {
4485 Binder.restoreCallingIdentity(origId);
4486 }
4487 }
4488 }
4489
4490 /** Return the user id of the last resumed activity. */
4491 @Override
4492 public @UserIdInt
4493 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4496 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004497 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004500 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
4502 }
4503
4504 @Override
4505 public void updateLockTaskFeatures(int userId, int flags) {
4506 final int callingUid = Binder.getCallingUid();
4507 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 "updateLockTaskFeatures()");
4510 }
4511 synchronized (mGlobalLock) {
4512 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4513 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004514 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
4516 }
4517
4518 @Override
4519 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4520 synchronized (mGlobalLock) {
4521 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4522 if (r == null) {
4523 return;
4524 }
4525 final long origId = Binder.clearCallingIdentity();
4526 try {
4527 r.setShowWhenLocked(showWhenLocked);
4528 } finally {
4529 Binder.restoreCallingIdentity(origId);
4530 }
4531 }
4532 }
4533
4534 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004535 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4536 synchronized (mGlobalLock) {
4537 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4538 if (r == null) {
4539 return;
4540 }
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
4543 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
4549
4550 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4552 synchronized (mGlobalLock) {
4553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4554 if (r == null) {
4555 return;
4556 }
4557 final long origId = Binder.clearCallingIdentity();
4558 try {
4559 r.setTurnScreenOn(turnScreenOn);
4560 } finally {
4561 Binder.restoreCallingIdentity(origId);
4562 }
4563 }
4564 }
4565
4566 @Override
4567 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004568 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004570 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 synchronized (mGlobalLock) {
4572 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4573 if (r == null) {
4574 return;
4575 }
4576 final long origId = Binder.clearCallingIdentity();
4577 try {
4578 r.registerRemoteAnimations(definition);
4579 } finally {
4580 Binder.restoreCallingIdentity(origId);
4581 }
4582 }
4583 }
4584
4585 @Override
4586 public void registerRemoteAnimationForNextActivityStart(String packageName,
4587 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004588 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004589 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004590 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 synchronized (mGlobalLock) {
4592 final long origId = Binder.clearCallingIdentity();
4593 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004594 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 packageName, adapter);
4596 } finally {
4597 Binder.restoreCallingIdentity(origId);
4598 }
4599 }
4600 }
4601
Evan Rosky966759f2019-01-15 10:33:58 -08004602 @Override
4603 public void registerRemoteAnimationsForDisplay(int displayId,
4604 RemoteAnimationDefinition definition) {
4605 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4606 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004607 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004608 synchronized (mGlobalLock) {
4609 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4610 if (display == null) {
4611 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4612 return;
4613 }
4614 final long origId = Binder.clearCallingIdentity();
4615 try {
4616 display.mDisplayContent.registerRemoteAnimations(definition);
4617 } finally {
4618 Binder.restoreCallingIdentity(origId);
4619 }
4620 }
4621 }
4622
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4624 @Override
4625 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4626 synchronized (mGlobalLock) {
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004629 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004635
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004636 @Override
4637 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004638 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004639 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004640 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004641 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004642 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004643 }
4644 }
4645
4646 @Override
4647 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004648 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 != PERMISSION_GRANTED) {
4650 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4651 + Binder.getCallingPid()
4652 + ", uid=" + Binder.getCallingUid()
4653 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4654 Slog.w(TAG, msg);
4655 throw new SecurityException(msg);
4656 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004657 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004658 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004659 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004660 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004661 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004662 }
4663 }
4664
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004665 @Override
4666 public void stopAppSwitches() {
4667 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4668 synchronized (mGlobalLock) {
4669 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004670 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004671 mDidAppSwitch = false;
4672 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4673 }
4674 }
4675
4676 @Override
4677 public void resumeAppSwitches() {
4678 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4679 synchronized (mGlobalLock) {
4680 // Note that we don't execute any pending app switches... we will
4681 // let those wait until either the timeout, or the next start
4682 // activity request.
4683 mAppSwitchesAllowedTime = 0;
4684 }
4685 }
4686
Ricky Wai906af482019-06-03 17:25:28 +01004687 long getLastStopAppSwitchesTime() {
4688 return mLastStopAppSwitchesTime;
4689 }
4690
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004691 void onStartActivitySetDidAppSwitch() {
4692 if (mDidAppSwitch) {
4693 // This is the second allowed switch since we stopped switches, so now just generally
4694 // allow switches. Use case:
4695 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4696 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4697 // anyone to switch again).
4698 mAppSwitchesAllowedTime = 0;
4699 } else {
4700 mDidAppSwitch = true;
4701 }
4702 }
4703
4704 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 boolean shouldDisableNonVrUiLocked() {
4706 return mVrController.shouldDisableNonVrUiLocked();
4707 }
4708
Wale Ogunwale53783742018-09-16 10:21:51 -07004709 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 // 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 +00004711 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004713 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4714 + " to main display for VR");
4715 mRootActivityContainer.moveStackToDisplay(
4716 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 }
4718 mH.post(() -> {
4719 if (!mVrController.onVrModeChanged(r)) {
4720 return;
4721 }
4722 synchronized (mGlobalLock) {
4723 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4724 mWindowManager.disableNonVrUi(disableNonVrUi);
4725 if (disableNonVrUi) {
4726 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4727 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004728 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004729 }
4730 }
4731 });
4732 }
4733
Wale Ogunwale53783742018-09-16 10:21:51 -07004734 @Override
4735 public int getPackageScreenCompatMode(String packageName) {
4736 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4737 synchronized (mGlobalLock) {
4738 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4739 }
4740 }
4741
4742 @Override
4743 public void setPackageScreenCompatMode(String packageName, int mode) {
4744 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4745 "setPackageScreenCompatMode");
4746 synchronized (mGlobalLock) {
4747 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4748 }
4749 }
4750
4751 @Override
4752 public boolean getPackageAskScreenCompat(String packageName) {
4753 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4754 synchronized (mGlobalLock) {
4755 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4756 }
4757 }
4758
4759 @Override
4760 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4761 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4762 "setPackageAskScreenCompat");
4763 synchronized (mGlobalLock) {
4764 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4765 }
4766 }
4767
Wale Ogunwale64258362018-10-16 15:13:37 -07004768 public static String relaunchReasonToString(int relaunchReason) {
4769 switch (relaunchReason) {
4770 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4771 return "window_resize";
4772 case RELAUNCH_REASON_FREE_RESIZE:
4773 return "free_resize";
4774 default:
4775 return null;
4776 }
4777 }
4778
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004779 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004780 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004781 }
4782
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004783 /** Pokes the task persister. */
4784 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4785 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4786 }
4787
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004788 boolean isKeyguardLocked() {
4789 return mKeyguardController.isKeyguardLocked();
4790 }
4791
Garfield Tan01548632018-11-27 10:15:48 -08004792 /**
4793 * Clears launch params for the given package.
4794 * @param packageNames the names of the packages of which the launch params are to be cleared
4795 */
4796 @Override
4797 public void clearLaunchParamsForPackages(List<String> packageNames) {
4798 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4799 "clearLaunchParamsForPackages");
4800 synchronized (mGlobalLock) {
4801 for (int i = 0; i < packageNames.size(); ++i) {
4802 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4803 }
4804 }
4805 }
4806
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004807 /**
4808 * Makes the display with the given id a single task instance display. I.e the display can only
4809 * contain one task.
4810 */
4811 @Override
4812 public void setDisplayToSingleTaskInstance(int displayId) {
4813 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4814 "setDisplayToSingleTaskInstance");
4815 final long origId = Binder.clearCallingIdentity();
4816 try {
4817 final ActivityDisplay display =
4818 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4819 if (display != null) {
4820 display.setDisplayToSingleTaskInstance();
4821 }
4822 } finally {
4823 Binder.restoreCallingIdentity(origId);
4824 }
4825 }
4826
Wale Ogunwale31913b52018-10-13 08:29:31 -07004827 void dumpLastANRLocked(PrintWriter pw) {
4828 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4829 if (mLastANRState == null) {
4830 pw.println(" <no ANR has occurred since boot>");
4831 } else {
4832 pw.println(mLastANRState);
4833 }
4834 }
4835
4836 void dumpLastANRTracesLocked(PrintWriter pw) {
4837 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4838
4839 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4840 if (ArrayUtils.isEmpty(files)) {
4841 pw.println(" <no ANR has occurred since boot>");
4842 return;
4843 }
4844 // Find the latest file.
4845 File latest = null;
4846 for (File f : files) {
4847 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4848 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004849 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004850 }
4851 pw.print("File: ");
4852 pw.print(latest.getName());
4853 pw.println();
4854 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4855 String line;
4856 while ((line = in.readLine()) != null) {
4857 pw.println(line);
4858 }
4859 } catch (IOException e) {
4860 pw.print("Unable to read: ");
4861 pw.print(e);
4862 pw.println();
4863 }
4864 }
4865
4866 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4867 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4868 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4869 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4870 }
4871
4872 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4873 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4874 pw.println(header);
4875
Wale Ogunwaled32da472018-11-16 07:19:28 -08004876 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004877 dumpPackage);
4878 boolean needSep = printedAnything;
4879
4880 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004881 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004882 " ResumedActivity: ");
4883 if (printed) {
4884 printedAnything = true;
4885 needSep = false;
4886 }
4887
4888 if (dumpPackage == null) {
4889 if (needSep) {
4890 pw.println();
4891 }
4892 printedAnything = true;
4893 mStackSupervisor.dump(pw, " ");
4894 }
4895
4896 if (!printedAnything) {
4897 pw.println(" (nothing)");
4898 }
4899 }
4900
4901 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004902 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004903 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004904 pw.println(" ");
4905 }
4906
4907 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4908 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4909 getActivityStartController().dump(pw, "", dumpPackage);
4910 }
4911
4912 /**
4913 * There are three things that cmd can be:
4914 * - a flattened component name that matches an existing activity
4915 * - the cmd arg isn't the flattened component name of an existing activity:
4916 * dump all activity whose component contains the cmd as a substring
4917 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004918 * <p>
4919 * The caller should not hold lock when calling this method because it will wait for the
4920 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004921 *
4922 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4923 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4924 */
4925 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4926 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4927 ArrayList<ActivityRecord> activities;
4928
4929 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004930 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 dumpFocusedStackOnly);
4932 }
4933
4934 if (activities.size() <= 0) {
4935 return false;
4936 }
4937
4938 String[] newArgs = new String[args.length - opti];
4939 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4940
4941 TaskRecord lastTask = null;
4942 boolean needSep = false;
4943 for (int i = activities.size() - 1; i >= 0; i--) {
4944 ActivityRecord r = activities.get(i);
4945 if (needSep) {
4946 pw.println();
4947 }
4948 needSep = true;
4949 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004951 if (lastTask != task) {
4952 lastTask = task;
4953 pw.print("TASK "); pw.print(lastTask.affinity);
4954 pw.print(" id="); pw.print(lastTask.taskId);
4955 pw.print(" userId="); pw.println(lastTask.userId);
4956 if (dumpAll) {
4957 lastTask.dump(pw, " ");
4958 }
4959 }
4960 }
4961 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4962 }
4963 return true;
4964 }
4965
4966 /**
4967 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4968 * there is a thread associated with the activity.
4969 */
4970 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4971 final ActivityRecord r, String[] args, boolean dumpAll) {
4972 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004973 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004974 synchronized (mGlobalLock) {
4975 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4976 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4977 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004978 if (r.hasProcess()) {
4979 pw.println(r.app.getPid());
4980 appThread = r.app.getThread();
4981 } else {
4982 pw.println("(not running)");
4983 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 if (dumpAll) {
4985 r.dump(pw, innerPrefix);
4986 }
4987 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004988 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004989 // flush anything that is already in the PrintWriter since the thread is going
4990 // to write to the file descriptor directly
4991 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004992 try (TransferPipe tp = new TransferPipe()) {
4993 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4994 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 } catch (IOException e) {
4996 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4997 } catch (RemoteException e) {
4998 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4999 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005000 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005001 }
5002
sanryhuang498e77e2018-12-06 14:57:01 +08005003 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5004 boolean testPssMode) {
5005 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5006 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5007 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005008 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005009 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5010 st.toString());
5011 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005012 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5013 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5014 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5016 testPssMode);
5017 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005018 }
5019
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005020 int getCurrentUserId() {
5021 return mAmInternal.getCurrentUserId();
5022 }
5023
5024 private void enforceNotIsolatedCaller(String caller) {
5025 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5026 throw new SecurityException("Isolated process not allowed to call " + caller);
5027 }
5028 }
5029
Wale Ogunwalef6733932018-06-27 05:14:34 -07005030 public Configuration getConfiguration() {
5031 Configuration ci;
5032 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005033 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005034 ci.userSetLocale = false;
5035 }
5036 return ci;
5037 }
5038
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005039 /**
5040 * Current global configuration information. Contains general settings for the entire system,
5041 * also corresponds to the merged configuration of the default display.
5042 */
5043 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005044 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045 }
5046
5047 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5048 boolean initLocale) {
5049 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5050 }
5051
5052 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5053 boolean initLocale, boolean deferResume) {
5054 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5055 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5056 UserHandle.USER_NULL, deferResume);
5057 }
5058
Wale Ogunwale59507092018-10-29 09:00:30 -07005059 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060 final long origId = Binder.clearCallingIdentity();
5061 try {
5062 synchronized (mGlobalLock) {
5063 updateConfigurationLocked(values, null, false, true, userId,
5064 false /* deferResume */);
5065 }
5066 } finally {
5067 Binder.restoreCallingIdentity(origId);
5068 }
5069 }
5070
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5072 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5073 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5074 deferResume, null /* result */);
5075 }
5076
5077 /**
5078 * Do either or both things: (1) change the current configuration, and (2)
5079 * make sure the given activity is running with the (now) current
5080 * configuration. Returns true if the activity has been left running, or
5081 * false if <var>starting</var> is being destroyed to match the new
5082 * configuration.
5083 *
5084 * @param userId is only used when persistent parameter is set to true to persist configuration
5085 * for that particular user
5086 */
5087 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5088 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5089 ActivityTaskManagerService.UpdateConfigurationResult result) {
5090 int changes = 0;
5091 boolean kept = true;
5092
5093 if (mWindowManager != null) {
5094 mWindowManager.deferSurfaceLayout();
5095 }
5096 try {
5097 if (values != null) {
5098 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5099 deferResume);
5100 }
5101
5102 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5103 } finally {
5104 if (mWindowManager != null) {
5105 mWindowManager.continueSurfaceLayout();
5106 }
5107 }
5108
5109 if (result != null) {
5110 result.changes = changes;
5111 result.activityRelaunched = !kept;
5112 }
5113 return kept;
5114 }
5115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005117 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005118 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005119
5120 final ActivityDisplay defaultDisplay =
5121 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5122
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005123 mTempConfig.setTo(getGlobalConfiguration());
5124 final int changes = mTempConfig.updateFrom(values);
5125 if (changes == 0) {
5126 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5127 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5128 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5129 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005130 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 return 0;
5132 }
5133
5134 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5135 "Updating global configuration to: " + values);
5136
5137 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5138 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5139 values.colorMode,
5140 values.densityDpi,
5141 values.fontScale,
5142 values.hardKeyboardHidden,
5143 values.keyboard,
5144 values.keyboardHidden,
5145 values.mcc,
5146 values.mnc,
5147 values.navigation,
5148 values.navigationHidden,
5149 values.orientation,
5150 values.screenHeightDp,
5151 values.screenLayout,
5152 values.screenWidthDp,
5153 values.smallestScreenWidthDp,
5154 values.touchscreen,
5155 values.uiMode);
5156
5157
5158 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5159 final LocaleList locales = values.getLocales();
5160 int bestLocaleIndex = 0;
5161 if (locales.size() > 1) {
5162 if (mSupportedSystemLocales == null) {
5163 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5164 }
5165 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5166 }
5167 SystemProperties.set("persist.sys.locale",
5168 locales.get(bestLocaleIndex).toLanguageTag());
5169 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005170
5171 final Message m = PooledLambda.obtainMessage(
5172 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5173 locales.get(bestLocaleIndex));
5174 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175 }
5176
Yunfan Chen75157d72018-07-27 14:47:21 +09005177 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178
5179 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005180 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181
5182 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5183 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005184 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185
5186 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005187 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005188
5189 AttributeCache ac = AttributeCache.instance();
5190 if (ac != null) {
5191 ac.updateConfiguration(mTempConfig);
5192 }
5193
5194 // Make sure all resources in our process are updated right now, so that anyone who is going
5195 // to retrieve resource values after we return will be sure to get the new ones. This is
5196 // especially important during boot, where the first config change needs to guarantee all
5197 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005198 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199
5200 // We need another copy of global config because we're scheduling some calls instead of
5201 // running them in place. We need to be sure that object we send will be handled unchanged.
5202 final Configuration configCopy = new Configuration(mTempConfig);
5203 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005204 final Message msg = PooledLambda.obtainMessage(
5205 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5206 this, userId, configCopy);
5207 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005208 }
5209
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005210 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5211 for (int i = pidMap.size() - 1; i >= 0; i--) {
5212 final int pid = pidMap.keyAt(i);
5213 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005214 if (DEBUG_CONFIGURATION) {
5215 Slog.v(TAG_CONFIGURATION, "Update process config of "
5216 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005217 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005218 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
5220
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005221 final Message msg = PooledLambda.obtainMessage(
5222 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5223 mAmInternal, changes, initLocale);
5224 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 // Override configuration of the default display duplicates global config, so we need to
5227 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005228 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5229 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 return changes;
5232 }
5233
Wale Ogunwalef6733932018-06-27 05:14:34 -07005234 private void updateEventDispatchingLocked(boolean booted) {
5235 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5236 }
5237
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005238 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5239 final ContentResolver resolver = mContext.getContentResolver();
5240 Settings.System.putConfigurationForUser(resolver, config, userId);
5241 }
5242
5243 private void sendLocaleToMountDaemonMsg(Locale l) {
5244 try {
5245 IBinder service = ServiceManager.getService("mount");
5246 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5247 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5248 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5249 } catch (RemoteException e) {
5250 Log.e(TAG, "Error storing locale for decryption UI", e);
5251 }
5252 }
5253
Alison Cichowlas3e340502018-08-07 17:15:01 -04005254 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5255 mStartActivitySources.remove(permissionToken);
5256 mExpiredStartAsCallerTokens.add(permissionToken);
5257 }
5258
5259 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5260 mExpiredStartAsCallerTokens.remove(permissionToken);
5261 }
5262
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005263 boolean isActivityStartsLoggingEnabled() {
5264 return mAmInternal.isActivityStartsLoggingEnabled();
5265 }
5266
Michal Karpinski8596ded2018-11-14 14:43:48 +00005267 boolean isBackgroundActivityStartsEnabled() {
5268 return mAmInternal.isBackgroundActivityStartsEnabled();
5269 }
5270
Wale Ogunwalef6733932018-06-27 05:14:34 -07005271 void enableScreenAfterBoot(boolean booted) {
5272 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5273 SystemClock.uptimeMillis());
5274 mWindowManager.enableScreenAfterBoot();
5275
5276 synchronized (mGlobalLock) {
5277 updateEventDispatchingLocked(booted);
5278 }
5279 }
5280
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005281 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5282 if (r == null || !r.hasProcess()) {
5283 return KEY_DISPATCHING_TIMEOUT_MS;
5284 }
5285 return getInputDispatchingTimeoutLocked(r.app);
5286 }
5287
5288 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005289 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005290 }
5291
Wale Ogunwalef6733932018-06-27 05:14:34 -07005292 /**
5293 * Decide based on the configuration whether we should show the ANR,
5294 * crash, etc dialogs. The idea is that if there is no affordance to
5295 * press the on-screen buttons, or the user experience would be more
5296 * greatly impacted than the crash itself, we shouldn't show the dialog.
5297 *
5298 * A thought: SystemUI might also want to get told about this, the Power
5299 * dialog / global actions also might want different behaviors.
5300 */
5301 private void updateShouldShowDialogsLocked(Configuration config) {
5302 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5303 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5304 && config.navigation == Configuration.NAVIGATION_NONAV);
5305 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5306 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5307 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5308 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5309 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5310 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5311 HIDE_ERROR_DIALOGS, 0) != 0;
5312 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5313 }
5314
5315 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5316 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5317 FONT_SCALE, 1.0f, userId);
5318
5319 synchronized (this) {
5320 if (getGlobalConfiguration().fontScale == scaleFactor) {
5321 return;
5322 }
5323
5324 final Configuration configuration
5325 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5326 configuration.fontScale = scaleFactor;
5327 updatePersistentConfiguration(configuration, userId);
5328 }
5329 }
5330
5331 // Actually is sleeping or shutting down or whatever else in the future
5332 // is an inactive state.
5333 boolean isSleepingOrShuttingDownLocked() {
5334 return isSleepingLocked() || mShuttingDown;
5335 }
5336
5337 boolean isSleepingLocked() {
5338 return mSleeping;
5339 }
5340
Riddle Hsu16567132018-08-16 21:37:47 +08005341 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005342 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005343 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005344 if (task.isActivityTypeStandard()) {
5345 if (mCurAppTimeTracker != r.appTimeTracker) {
5346 // We are switching app tracking. Complete the current one.
5347 if (mCurAppTimeTracker != null) {
5348 mCurAppTimeTracker.stop();
5349 mH.obtainMessage(
5350 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005351 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005352 mCurAppTimeTracker = null;
5353 }
5354 if (r.appTimeTracker != null) {
5355 mCurAppTimeTracker = r.appTimeTracker;
5356 startTimeTrackingFocusedActivityLocked();
5357 }
5358 } else {
5359 startTimeTrackingFocusedActivityLocked();
5360 }
5361 } else {
5362 r.appTimeTracker = null;
5363 }
5364 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5365 // TODO: Probably not, because we don't want to resume voice on switching
5366 // back to this activity
5367 if (task.voiceInteractor != null) {
5368 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5369 } else {
5370 finishRunningVoiceLocked();
5371
5372 if (mLastResumedActivity != null) {
5373 final IVoiceInteractionSession session;
5374
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005375 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005376 if (lastResumedActivityTask != null
5377 && lastResumedActivityTask.voiceSession != null) {
5378 session = lastResumedActivityTask.voiceSession;
5379 } else {
5380 session = mLastResumedActivity.voiceSession;
5381 }
5382
5383 if (session != null) {
5384 // We had been in a voice interaction session, but now focused has
5385 // move to something different. Just finish the session, we can't
5386 // return to it and retain the proper state and synchronization with
5387 // the voice interaction service.
5388 finishVoiceTask(session);
5389 }
5390 }
5391 }
5392
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005393 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5394 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005395 }
5396 updateResumedAppTrace(r);
5397 mLastResumedActivity = r;
5398
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005399 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400
5401 applyUpdateLockStateLocked(r);
5402 applyUpdateVrModeLocked(r);
5403
5404 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005405 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005406 r == null ? "NULL" : r.shortComponentName,
5407 reason);
5408 }
5409
5410 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5411 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005412 final ActivityTaskManagerInternal.SleepToken token =
5413 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 updateSleepIfNeededLocked();
5415 return token;
5416 }
5417 }
5418
5419 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005420 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005421 final boolean wasSleeping = mSleeping;
5422 boolean updateOomAdj = false;
5423
5424 if (!shouldSleep) {
5425 // If wasSleeping is true, we need to wake up activity manager state from when
5426 // we started sleeping. In either case, we need to apply the sleep tokens, which
5427 // will wake up stacks or put them to sleep as appropriate.
5428 if (wasSleeping) {
5429 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005430 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5431 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 startTimeTrackingFocusedActivityLocked();
5433 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005434 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5436 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005437 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005438 if (wasSleeping) {
5439 updateOomAdj = true;
5440 }
5441 } else if (!mSleeping && shouldSleep) {
5442 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005443 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5444 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005445 if (mCurAppTimeTracker != null) {
5446 mCurAppTimeTracker.stop();
5447 }
5448 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005449 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 mStackSupervisor.goingToSleepLocked();
5451 updateResumedAppTrace(null /* resumed */);
5452 updateOomAdj = true;
5453 }
5454 if (updateOomAdj) {
5455 mH.post(mAmInternal::updateOomAdj);
5456 }
5457 }
5458
5459 void updateOomAdj() {
5460 mH.post(mAmInternal::updateOomAdj);
5461 }
5462
Wale Ogunwale53783742018-09-16 10:21:51 -07005463 void updateCpuStats() {
5464 mH.post(mAmInternal::updateCpuStats);
5465 }
5466
Hui Yu03d12402018-12-06 18:00:37 -08005467 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5468 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005469 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5470 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005471 mH.sendMessage(m);
5472 }
5473
Hui Yu03d12402018-12-06 18:00:37 -08005474 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005475 ComponentName taskRoot = null;
5476 final TaskRecord task = activity.getTaskRecord();
5477 if (task != null) {
5478 final ActivityRecord rootActivity = task.getRootActivity();
5479 if (rootActivity != null) {
5480 taskRoot = rootActivity.mActivityComponent;
5481 }
5482 }
5483
Hui Yu03d12402018-12-06 18:00:37 -08005484 final Message m = PooledLambda.obtainMessage(
5485 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005486 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005487 mH.sendMessage(m);
5488 }
5489
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005490 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5491 String hostingType) {
5492 try {
5493 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5494 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5495 + activity.processName);
5496 }
5497 // Post message to start process to avoid possible deadlock of calling into AMS with the
5498 // ATMS lock held.
5499 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5500 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5501 isTop, hostingType, activity.intent.getComponent());
5502 mH.sendMessage(m);
5503 } finally {
5504 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5505 }
5506 }
5507
Wale Ogunwale53783742018-09-16 10:21:51 -07005508 void setBooting(boolean booting) {
5509 mAmInternal.setBooting(booting);
5510 }
5511
5512 boolean isBooting() {
5513 return mAmInternal.isBooting();
5514 }
5515
5516 void setBooted(boolean booted) {
5517 mAmInternal.setBooted(booted);
5518 }
5519
5520 boolean isBooted() {
5521 return mAmInternal.isBooted();
5522 }
5523
5524 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5525 mH.post(() -> {
5526 if (finishBooting) {
5527 mAmInternal.finishBooting();
5528 }
5529 if (enableScreen) {
5530 mInternal.enableScreenAfterBoot(isBooted());
5531 }
5532 });
5533 }
5534
5535 void setHeavyWeightProcess(ActivityRecord root) {
5536 mHeavyWeightProcess = root.app;
5537 final Message m = PooledLambda.obtainMessage(
5538 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005539 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005540 mH.sendMessage(m);
5541 }
5542
5543 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5544 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5545 return;
5546 }
5547
5548 mHeavyWeightProcess = null;
5549 final Message m = PooledLambda.obtainMessage(
5550 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5551 proc.mUserId);
5552 mH.sendMessage(m);
5553 }
5554
5555 private void cancelHeavyWeightProcessNotification(int userId) {
5556 final INotificationManager inm = NotificationManager.getService();
5557 if (inm == null) {
5558 return;
5559 }
5560 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005561 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005562 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5563 } catch (RuntimeException e) {
5564 Slog.w(TAG, "Error canceling notification for service", e);
5565 } catch (RemoteException e) {
5566 }
5567
5568 }
5569
5570 private void postHeavyWeightProcessNotification(
5571 WindowProcessController proc, Intent intent, int userId) {
5572 if (proc == null) {
5573 return;
5574 }
5575
5576 final INotificationManager inm = NotificationManager.getService();
5577 if (inm == null) {
5578 return;
5579 }
5580
5581 try {
5582 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5583 String text = mContext.getString(R.string.heavy_weight_notification,
5584 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5585 Notification notification =
5586 new Notification.Builder(context,
5587 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5588 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5589 .setWhen(0)
5590 .setOngoing(true)
5591 .setTicker(text)
5592 .setColor(mContext.getColor(
5593 com.android.internal.R.color.system_notification_accent_color))
5594 .setContentTitle(text)
5595 .setContentText(
5596 mContext.getText(R.string.heavy_weight_notification_detail))
5597 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5598 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5599 new UserHandle(userId)))
5600 .build();
5601 try {
5602 inm.enqueueNotificationWithTag("android", "android", null,
5603 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5604 } catch (RuntimeException e) {
5605 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5606 } catch (RemoteException e) {
5607 }
5608 } catch (PackageManager.NameNotFoundException e) {
5609 Slog.w(TAG, "Unable to create context for heavy notification", e);
5610 }
5611
5612 }
5613
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005614 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5615 IBinder token, String resultWho, int requestCode, Intent[] intents,
5616 String[] resolvedTypes, int flags, Bundle bOptions) {
5617
5618 ActivityRecord activity = null;
5619 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5620 activity = ActivityRecord.isInStackLocked(token);
5621 if (activity == null) {
5622 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5623 return null;
5624 }
5625 if (activity.finishing) {
5626 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5627 return null;
5628 }
5629 }
5630
5631 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5632 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5633 bOptions);
5634 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5635 if (noCreate) {
5636 return rec;
5637 }
5638 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5639 if (activity.pendingResults == null) {
5640 activity.pendingResults = new HashSet<>();
5641 }
5642 activity.pendingResults.add(rec.ref);
5643 }
5644 return rec;
5645 }
5646
Andrii Kulian52d255c2018-07-13 11:32:19 -07005647 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005648 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005649 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5651 mCurAppTimeTracker.start(resumedActivity.packageName);
5652 }
5653 }
5654
5655 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5656 if (mTracedResumedActivity != null) {
5657 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5658 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5659 }
5660 if (resumed != null) {
5661 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5662 constructResumedTraceName(resumed.packageName), 0);
5663 }
5664 mTracedResumedActivity = resumed;
5665 }
5666
5667 private String constructResumedTraceName(String packageName) {
5668 return "focused app: " + packageName;
5669 }
5670
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005671 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005672 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005673 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005674 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005675 // mainStack is null during startup.
5676 if (mainStack != null) {
5677 if (changes != 0 && starting == null) {
5678 // If the configuration changed, and the caller is not already
5679 // in the process of starting an activity, then find the top
5680 // activity to check if its configuration needs to change.
5681 starting = mainStack.topRunningActivityLocked();
5682 }
5683
5684 if (starting != null) {
5685 kept = starting.ensureActivityConfiguration(changes,
5686 false /* preserveWindow */);
5687 // And we need to make sure at this point that all other activities
5688 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005689 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005690 !PRESERVE_WINDOWS);
5691 }
5692 }
5693
5694 return kept;
5695 }
5696
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005697 void scheduleAppGcsLocked() {
5698 mH.post(() -> mAmInternal.scheduleAppGcs());
5699 }
5700
Wale Ogunwale53783742018-09-16 10:21:51 -07005701 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5702 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5703 }
5704
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005705 /**
5706 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5707 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5708 * on demand.
5709 */
5710 IPackageManager getPackageManager() {
5711 return AppGlobals.getPackageManager();
5712 }
5713
5714 PackageManagerInternal getPackageManagerInternalLocked() {
5715 if (mPmInternal == null) {
5716 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5717 }
5718 return mPmInternal;
5719 }
5720
Hai Zhangf4da9be2019-05-01 13:46:06 +08005721 PermissionPolicyInternal getPermissionPolicyInternal() {
5722 if (mPermissionPolicyInternal == null) {
5723 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5724 }
5725 return mPermissionPolicyInternal;
5726 }
5727
Wale Ogunwale008163e2018-07-23 23:11:08 -07005728 AppWarnings getAppWarningsLocked() {
5729 return mAppWarnings;
5730 }
5731
Wale Ogunwale214f3482018-10-04 11:00:47 -07005732 Intent getHomeIntent() {
5733 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5734 intent.setComponent(mTopComponent);
5735 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5736 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5737 intent.addCategory(Intent.CATEGORY_HOME);
5738 }
5739 return intent;
5740 }
5741
Chilun2ef71f72018-11-16 17:57:15 +08005742 /**
5743 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5744 * activities.
5745 *
5746 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5747 * component defined in config_secondaryHomeComponent.
5748 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5749 */
5750 Intent getSecondaryHomeIntent(String preferredPackage) {
5751 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005752 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5753 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5754 if (preferredPackage == null || useSystemProvidedLauncher) {
5755 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005756 final String secondaryHomeComponent = mContext.getResources().getString(
5757 com.android.internal.R.string.config_secondaryHomeComponent);
5758 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5759 } else {
5760 intent.setPackage(preferredPackage);
5761 }
5762 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5763 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5764 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5765 }
5766 return intent;
5767 }
5768
Wale Ogunwale214f3482018-10-04 11:00:47 -07005769 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5770 if (info == null) return null;
5771 ApplicationInfo newInfo = new ApplicationInfo(info);
5772 newInfo.initForUser(userId);
5773 return newInfo;
5774 }
5775
Wale Ogunwale9c103022018-10-18 07:44:54 -07005776 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005777 if (uid == SYSTEM_UID) {
5778 // The system gets to run in any process. If there are multiple processes with the same
5779 // uid, just pick the first (this should never happen).
5780 final SparseArray<WindowProcessController> procs =
5781 mProcessNames.getMap().get(processName);
5782 if (procs == null) return null;
5783 final int procCount = procs.size();
5784 for (int i = 0; i < procCount; i++) {
5785 final int procUid = procs.keyAt(i);
5786 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5787 // Don't use an app process or different user process for system component.
5788 continue;
5789 }
5790 return procs.valueAt(i);
5791 }
5792 }
5793
5794 return mProcessNames.get(processName, uid);
5795 }
5796
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005797 WindowProcessController getProcessController(IApplicationThread thread) {
5798 if (thread == null) {
5799 return null;
5800 }
5801
5802 final IBinder threadBinder = thread.asBinder();
5803 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5804 for (int i = pmap.size()-1; i >= 0; i--) {
5805 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5806 for (int j = procs.size() - 1; j >= 0; j--) {
5807 final WindowProcessController proc = procs.valueAt(j);
5808 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5809 return proc;
5810 }
5811 }
5812 }
5813
5814 return null;
5815 }
5816
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005817 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005818 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005819 if (proc == null) return null;
5820 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5821 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005822 }
5823 return null;
5824 }
5825
Riddle Hsua0536432019-02-16 00:38:59 +08005826 int getUidState(int uid) {
5827 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005828 }
5829
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005830 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005831 // A uid is considered to be foreground if it has a visible non-toast window.
5832 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005833 }
5834
Ricky Wai96f5c352019-04-10 18:40:17 +01005835 boolean isDeviceOwner(int uid) {
5836 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005837 }
5838
Ricky Wai96f5c352019-04-10 18:40:17 +01005839 void setDeviceOwnerUid(int uid) {
5840 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005841 }
5842
Wale Ogunwale9de19442018-10-18 19:05:03 -07005843 /**
5844 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5845 * the whitelist
5846 */
5847 String getPendingTempWhitelistTagForUidLocked(int uid) {
5848 return mPendingTempWhitelist.get(uid);
5849 }
5850
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005851 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5852 if (true || Build.IS_USER) {
5853 return;
5854 }
5855
5856 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5857 StrictMode.allowThreadDiskWrites();
5858 try {
5859 File tracesDir = new File("/data/anr");
5860 File tracesFile = null;
5861 try {
5862 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5863
5864 StringBuilder sb = new StringBuilder();
5865 Time tobj = new Time();
5866 tobj.set(System.currentTimeMillis());
5867 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5868 sb.append(": ");
5869 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5870 sb.append(" since ");
5871 sb.append(msg);
5872 FileOutputStream fos = new FileOutputStream(tracesFile);
5873 fos.write(sb.toString().getBytes());
5874 if (app == null) {
5875 fos.write("\n*** No application process!".getBytes());
5876 }
5877 fos.close();
5878 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5879 } catch (IOException e) {
5880 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5881 return;
5882 }
5883
5884 if (app != null && app.getPid() > 0) {
5885 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5886 firstPids.add(app.getPid());
5887 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5888 }
5889
5890 File lastTracesFile = null;
5891 File curTracesFile = null;
5892 for (int i=9; i>=0; i--) {
5893 String name = String.format(Locale.US, "slow%02d.txt", i);
5894 curTracesFile = new File(tracesDir, name);
5895 if (curTracesFile.exists()) {
5896 if (lastTracesFile != null) {
5897 curTracesFile.renameTo(lastTracesFile);
5898 } else {
5899 curTracesFile.delete();
5900 }
5901 }
5902 lastTracesFile = curTracesFile;
5903 }
5904 tracesFile.renameTo(curTracesFile);
5905 } finally {
5906 StrictMode.setThreadPolicy(oldPolicy);
5907 }
5908 }
5909
Michal Karpinskida34cd42019-04-02 19:46:52 +01005910 boolean isAssociatedCompanionApp(int userId, int uid) {
5911 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5912 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005913 return false;
5914 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005915 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005916 }
5917
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005918 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005919 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005920
5921
Wale Ogunwale98875612018-10-12 07:53:02 -07005922 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5923 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005924
Riddle Hsud93a6c42018-11-29 21:50:06 +08005925 H(Looper looper) {
5926 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005927 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005928
5929 @Override
5930 public void handleMessage(Message msg) {
5931 switch (msg.what) {
5932 case REPORT_TIME_TRACKER_MSG: {
5933 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5934 tracker.deliverResult(mContext);
5935 } break;
5936 }
5937 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005938 }
5939
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005940 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005941 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005942
5943 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005944 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005945 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005946
5947 @Override
5948 public void handleMessage(Message msg) {
5949 switch (msg.what) {
5950 case DISMISS_DIALOG_UI_MSG: {
5951 final Dialog d = (Dialog) msg.obj;
5952 d.dismiss();
5953 break;
5954 }
5955 }
5956 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005957 }
5958
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005959 final class LocalService extends ActivityTaskManagerInternal {
5960 @Override
5961 public SleepToken acquireSleepToken(String tag, int displayId) {
5962 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005963 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005964 }
5965
5966 @Override
5967 public ComponentName getHomeActivityForUser(int userId) {
5968 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005969 final ActivityRecord homeActivity =
5970 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005971 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005972 }
5973 }
5974
5975 @Override
5976 public void onLocalVoiceInteractionStarted(IBinder activity,
5977 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5978 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005979 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005980 }
5981 }
5982
5983 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005984 public void notifyAppTransitionStarting(SparseIntArray reasons,
5985 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005986 synchronized (mGlobalLock) {
5987 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5988 reasons, timestamp);
5989 }
5990 }
5991
5992 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005993 public void notifySingleTaskDisplayDrawn(int displayId) {
5994 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
5995 }
5996
5997 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005998 public void notifyAppTransitionFinished() {
5999 synchronized (mGlobalLock) {
6000 mStackSupervisor.notifyAppTransitionDone();
6001 }
6002 }
6003
6004 @Override
6005 public void notifyAppTransitionCancelled() {
6006 synchronized (mGlobalLock) {
6007 mStackSupervisor.notifyAppTransitionDone();
6008 }
6009 }
6010
6011 @Override
6012 public List<IBinder> getTopVisibleActivities() {
6013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006014 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006015 }
6016 }
6017
6018 @Override
6019 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6020 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006021 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006022 }
6023 }
6024
6025 @Override
6026 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6027 Bundle bOptions) {
6028 Preconditions.checkNotNull(intents, "intents");
6029 final String[] resolvedTypes = new String[intents.length];
6030
6031 // UID of the package on user userId.
6032 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6033 // packageUid may not be initialized.
6034 int packageUid = 0;
6035 final long ident = Binder.clearCallingIdentity();
6036
6037 try {
6038 for (int i = 0; i < intents.length; i++) {
6039 resolvedTypes[i] =
6040 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6041 }
6042
6043 packageUid = AppGlobals.getPackageManager().getPackageUid(
6044 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6045 } catch (RemoteException e) {
6046 // Shouldn't happen.
6047 } finally {
6048 Binder.restoreCallingIdentity(ident);
6049 }
6050
Riddle Hsu591bf612019-02-14 17:55:31 +08006051 return getActivityStartController().startActivitiesInPackage(
6052 packageUid, packageName,
6053 intents, resolvedTypes, null /* resultTo */,
6054 SafeActivityOptions.fromBundle(bOptions), userId,
6055 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6056 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006057 }
6058
6059 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006060 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6061 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6062 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6063 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006064 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006065 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006066 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6067 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6068 userId, validateIncomingUser, originatingPendingIntent,
6069 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006070 }
6071 }
6072
6073 @Override
6074 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6075 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6076 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6077 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006078 PendingIntentRecord originatingPendingIntent,
6079 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006080 synchronized (mGlobalLock) {
6081 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6082 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6083 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006084 validateIncomingUser, originatingPendingIntent,
6085 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006086 }
6087 }
6088
6089 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006090 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6091 Intent intent, Bundle options, int userId) {
6092 return ActivityTaskManagerService.this.startActivityAsUser(
6093 caller, callerPacakge, intent,
6094 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6095 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6096 false /*validateIncomingUser*/);
6097 }
6098
6099 @Override
lumark588a3e82018-07-20 18:53:54 +08006100 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 synchronized (mGlobalLock) {
6102
6103 // We might change the visibilities here, so prepare an empty app transition which
6104 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006105 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006106 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006107 if (activityDisplay == null) {
6108 return;
6109 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006110 final DisplayContent dc = activityDisplay.mDisplayContent;
6111 final boolean wasTransitionSet =
6112 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006113 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006114 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006116 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006117
6118 // If there was a transition set already we don't want to interfere with it as we
6119 // might be starting it too early.
6120 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006121 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122 }
6123 }
6124 if (callback != null) {
6125 callback.run();
6126 }
6127 }
6128
6129 @Override
6130 public void notifyKeyguardTrustedChanged() {
6131 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006132 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006133 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 }
6135 }
6136 }
6137
6138 /**
6139 * Called after virtual display Id is updated by
6140 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6141 * {@param vrVr2dDisplayId}.
6142 */
6143 @Override
6144 public void setVr2dDisplayId(int vr2dDisplayId) {
6145 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6146 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006147 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150
6151 @Override
6152 public void setFocusedActivity(IBinder token) {
6153 synchronized (mGlobalLock) {
6154 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6155 if (r == null) {
6156 throw new IllegalArgumentException(
6157 "setFocusedActivity: No activity record matching token=" + token);
6158 }
Louis Chang19443452018-10-09 12:10:21 +08006159 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006160 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162 }
6163 }
6164
6165 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006167 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 }
6169
6170 @Override
6171 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006172 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 }
6174
6175 @Override
6176 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006177 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179
6180 @Override
6181 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6182 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6183 }
6184
6185 @Override
6186 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006187 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006189
6190 @Override
6191 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6192 synchronized (mGlobalLock) {
6193 mActiveVoiceInteractionServiceComponent = component;
6194 }
6195 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006196
6197 @Override
6198 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6199 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6200 return;
6201 }
6202 synchronized (mGlobalLock) {
6203 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6204 if (types == null) {
6205 if (uid < 0) {
6206 return;
6207 }
6208 types = new ArrayMap<>();
6209 mAllowAppSwitchUids.put(userId, types);
6210 }
6211 if (uid < 0) {
6212 types.remove(type);
6213 } else {
6214 types.put(type, uid);
6215 }
6216 }
6217 }
6218
6219 @Override
6220 public void onUserStopped(int userId) {
6221 synchronized (mGlobalLock) {
6222 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6223 mAllowAppSwitchUids.remove(userId);
6224 }
6225 }
6226
6227 @Override
6228 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6229 synchronized (mGlobalLock) {
6230 return ActivityTaskManagerService.this.isGetTasksAllowed(
6231 caller, callingPid, callingUid);
6232 }
6233 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006234
Riddle Hsua0536432019-02-16 00:38:59 +08006235 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006236 @Override
6237 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006238 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006239 mProcessNames.put(proc.mName, proc.mUid, proc);
6240 }
6241 }
6242
Riddle Hsua0536432019-02-16 00:38:59 +08006243 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006244 @Override
6245 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006246 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006247 mProcessNames.remove(name, uid);
6248 }
6249 }
6250
Riddle Hsua0536432019-02-16 00:38:59 +08006251 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 @Override
6253 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006254 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006255 if (proc == mHomeProcess) {
6256 mHomeProcess = null;
6257 }
6258 if (proc == mPreviousProcess) {
6259 mPreviousProcess = null;
6260 }
6261 }
6262 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006263
Riddle Hsua0536432019-02-16 00:38:59 +08006264 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006265 @Override
6266 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006267 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006268 return mTopProcessState;
6269 }
6270 }
6271
Riddle Hsua0536432019-02-16 00:38:59 +08006272 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006273 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006274 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006275 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006276 return proc == mHeavyWeightProcess;
6277 }
6278 }
6279
Riddle Hsua0536432019-02-16 00:38:59 +08006280 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 @Override
6282 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006283 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006284 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6285 }
6286 }
6287
6288 @Override
6289 public void finishHeavyWeightApp() {
6290 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006291 if (mHeavyWeightProcess != null) {
6292 mHeavyWeightProcess.finishActivities();
6293 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006294 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6295 mHeavyWeightProcess);
6296 }
6297 }
6298
Riddle Hsua0536432019-02-16 00:38:59 +08006299 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006300 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006301 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006302 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006303 return isSleepingLocked();
6304 }
6305 }
6306
6307 @Override
6308 public boolean isShuttingDown() {
6309 synchronized (mGlobalLock) {
6310 return mShuttingDown;
6311 }
6312 }
6313
6314 @Override
6315 public boolean shuttingDown(boolean booted, int timeout) {
6316 synchronized (mGlobalLock) {
6317 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006318 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006319 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006320 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006321 return mStackSupervisor.shutdownLocked(timeout);
6322 }
6323 }
6324
6325 @Override
6326 public void enableScreenAfterBoot(boolean booted) {
6327 synchronized (mGlobalLock) {
6328 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6329 SystemClock.uptimeMillis());
6330 mWindowManager.enableScreenAfterBoot();
6331 updateEventDispatchingLocked(booted);
6332 }
6333 }
6334
6335 @Override
6336 public boolean showStrictModeViolationDialog() {
6337 synchronized (mGlobalLock) {
6338 return mShowDialogs && !mSleeping && !mShuttingDown;
6339 }
6340 }
6341
6342 @Override
6343 public void showSystemReadyErrorDialogsIfNeeded() {
6344 synchronized (mGlobalLock) {
6345 try {
6346 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6347 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6348 + " data partition or your device will be unstable.");
6349 mUiHandler.post(() -> {
6350 if (mShowDialogs) {
6351 AlertDialog d = new BaseErrorDialog(mUiContext);
6352 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6353 d.setCancelable(false);
6354 d.setTitle(mUiContext.getText(R.string.android_system_label));
6355 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6356 d.setButton(DialogInterface.BUTTON_POSITIVE,
6357 mUiContext.getText(R.string.ok),
6358 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6359 d.show();
6360 }
6361 });
6362 }
6363 } catch (RemoteException e) {
6364 }
6365
6366 if (!Build.isBuildConsistent()) {
6367 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6368 mUiHandler.post(() -> {
6369 if (mShowDialogs) {
6370 AlertDialog d = new BaseErrorDialog(mUiContext);
6371 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6372 d.setCancelable(false);
6373 d.setTitle(mUiContext.getText(R.string.android_system_label));
6374 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6375 d.setButton(DialogInterface.BUTTON_POSITIVE,
6376 mUiContext.getText(R.string.ok),
6377 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6378 d.show();
6379 }
6380 });
6381 }
6382 }
6383 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006384
6385 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006386 public void onProcessMapped(int pid, WindowProcessController proc) {
6387 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006388 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006389 }
6390 }
6391
6392 @Override
6393 public void onProcessUnMapped(int pid) {
6394 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006395 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006396 }
6397 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006398
6399 @Override
6400 public void onPackageDataCleared(String name) {
6401 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006403 mAppWarnings.onPackageDataCleared(name);
6404 }
6405 }
6406
6407 @Override
6408 public void onPackageUninstalled(String name) {
6409 synchronized (mGlobalLock) {
6410 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006411 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006412 }
6413 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006414
6415 @Override
6416 public void onPackageAdded(String name, boolean replacing) {
6417 synchronized (mGlobalLock) {
6418 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6419 }
6420 }
6421
6422 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006423 public void onPackageReplaced(ApplicationInfo aInfo) {
6424 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006425 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006426 }
6427 }
6428
6429 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006430 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6431 synchronized (mGlobalLock) {
6432 return compatibilityInfoForPackageLocked(ai);
6433 }
6434 }
6435
Yunfan Chen75157d72018-07-27 14:47:21 +09006436 /**
6437 * Set the corresponding display information for the process global configuration. To be
6438 * called when we need to show IME on a different display.
6439 *
6440 * @param pid The process id associated with the IME window.
6441 * @param displayId The ID of the display showing the IME.
6442 */
6443 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006444 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006445 // Don't update process-level configuration for Multi-Client IME process since other
6446 // IMEs on other displays will also receive this configuration change due to IME
6447 // services use the same application config/context.
6448 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006449
Yunfan Chen75157d72018-07-27 14:47:21 +09006450 if (pid == MY_PID || pid < 0) {
6451 if (DEBUG_CONFIGURATION) {
6452 Slog.w(TAG,
6453 "Trying to update display configuration for system/invalid process.");
6454 }
6455 return;
6456 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006457 synchronized (mGlobalLock) {
6458 final ActivityDisplay activityDisplay =
6459 mRootActivityContainer.getActivityDisplay(displayId);
6460 if (activityDisplay == null) {
6461 // Call might come when display is not yet added or has been removed.
6462 if (DEBUG_CONFIGURATION) {
6463 Slog.w(TAG, "Trying to update display configuration for non-existing "
6464 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006465 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006466 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006467 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006468 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006469 if (process == null) {
6470 if (DEBUG_CONFIGURATION) {
6471 Slog.w(TAG, "Trying to update display configuration for invalid "
6472 + "process, pid=" + pid);
6473 }
6474 return;
6475 }
lumarkddc77fb2019-06-27 22:22:23 +08006476 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006477 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6478 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006479 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006480
6481 @Override
6482 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006483 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006484 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006485 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6486 if (r != null && r.getActivityStack() != null) {
6487 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6488 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006489 }
6490 }
6491 }
6492
6493 @Override
6494 public void clearPendingResultForActivity(IBinder activityToken,
6495 WeakReference<PendingIntentRecord> pir) {
6496 synchronized (mGlobalLock) {
6497 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6498 if (r != null && r.pendingResults != null) {
6499 r.pendingResults.remove(pir);
6500 }
6501 }
6502 }
6503
6504 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006505 public ActivityTokens getTopActivityForTask(int taskId) {
6506 synchronized (mGlobalLock) {
6507 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6508 if (taskRecord == null) {
6509 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6510 + " Requested task not found");
6511 return null;
6512 }
6513 final ActivityRecord activity = taskRecord.getTopActivity();
6514 if (activity == null) {
6515 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6516 + " Requested activity not found");
6517 return null;
6518 }
6519 if (!activity.attachedToProcess()) {
6520 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6521 + activity);
6522 return null;
6523 }
6524 return new ActivityTokens(activity.appToken, activity.assistToken,
6525 activity.app.getThread());
6526 }
6527 }
6528
6529 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006530 public IIntentSender getIntentSender(int type, String packageName,
6531 int callingUid, int userId, IBinder token, String resultWho,
6532 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6533 Bundle bOptions) {
6534 synchronized (mGlobalLock) {
6535 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6536 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6537 }
6538 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006539
6540 @Override
6541 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6542 synchronized (mGlobalLock) {
6543 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6544 if (r == null) {
6545 return null;
6546 }
6547 if (r.mServiceConnectionsHolder == null) {
6548 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6549 ActivityTaskManagerService.this, r);
6550 }
6551
6552 return r.mServiceConnectionsHolder;
6553 }
6554 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006555
6556 @Override
6557 public Intent getHomeIntent() {
6558 synchronized (mGlobalLock) {
6559 return ActivityTaskManagerService.this.getHomeIntent();
6560 }
6561 }
6562
6563 @Override
6564 public boolean startHomeActivity(int userId, String reason) {
6565 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006566 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006567 }
6568 }
6569
6570 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006571 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006572 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006573 synchronized (mGlobalLock) {
6574 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006575 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006576 }
Chilun8b1f1be2019-03-13 17:14:36 +08006577 }
6578
6579 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006580 public boolean startHomeOnAllDisplays(int userId, String reason) {
6581 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006582 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006583 }
6584 }
6585
Riddle Hsua0536432019-02-16 00:38:59 +08006586 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006587 @Override
6588 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006589 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006590 if (mFactoryTest == FACTORY_TEST_OFF) {
6591 return false;
6592 }
6593 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6594 && wpc.mName.equals(mTopComponent.getPackageName())) {
6595 return true;
6596 }
6597 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6598 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6599 }
6600 }
6601
6602 @Override
6603 public void updateTopComponentForFactoryTest() {
6604 synchronized (mGlobalLock) {
6605 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6606 return;
6607 }
6608 final ResolveInfo ri = mContext.getPackageManager()
6609 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6610 final CharSequence errorMsg;
6611 if (ri != null) {
6612 final ActivityInfo ai = ri.activityInfo;
6613 final ApplicationInfo app = ai.applicationInfo;
6614 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6615 mTopAction = Intent.ACTION_FACTORY_TEST;
6616 mTopData = null;
6617 mTopComponent = new ComponentName(app.packageName, ai.name);
6618 errorMsg = null;
6619 } else {
6620 errorMsg = mContext.getResources().getText(
6621 com.android.internal.R.string.factorytest_not_system);
6622 }
6623 } else {
6624 errorMsg = mContext.getResources().getText(
6625 com.android.internal.R.string.factorytest_no_action);
6626 }
6627 if (errorMsg == null) {
6628 return;
6629 }
6630
6631 mTopAction = null;
6632 mTopData = null;
6633 mTopComponent = null;
6634 mUiHandler.post(() -> {
6635 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6636 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006637 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006638 });
6639 }
6640 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006641
Riddle Hsua0536432019-02-16 00:38:59 +08006642 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006643 @Override
6644 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6645 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006646 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006647 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006648 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006649
6650 wpc.clearRecentTasks();
6651 wpc.clearActivities();
6652
6653 if (wpc.isInstrumenting()) {
6654 finishInstrumentationCallback.run();
6655 }
6656
Jorim Jaggid0752812018-10-16 16:07:20 +02006657 if (!restarting && hasVisibleActivities) {
6658 mWindowManager.deferSurfaceLayout();
6659 try {
6660 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6661 // If there was nothing to resume, and we are not already restarting
6662 // this process, but there is a visible activity that is hosted by the
6663 // process...then make sure all visible activities are running, taking
6664 // care of restarting this process.
6665 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6666 !PRESERVE_WINDOWS);
6667 }
6668 } finally {
6669 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006670 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006671 }
6672 }
6673 }
6674
6675 @Override
6676 public void closeSystemDialogs(String reason) {
6677 enforceNotIsolatedCaller("closeSystemDialogs");
6678
6679 final int pid = Binder.getCallingPid();
6680 final int uid = Binder.getCallingUid();
6681 final long origId = Binder.clearCallingIdentity();
6682 try {
6683 synchronized (mGlobalLock) {
6684 // Only allow this from foreground processes, so that background
6685 // applications can't abuse it to prevent system UI from being shown.
6686 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006687 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006688 if (!proc.isPerceptible()) {
6689 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6690 + " from background process " + proc);
6691 return;
6692 }
6693 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006694 mWindowManager.closeSystemDialogs(reason);
6695
Wale Ogunwaled32da472018-11-16 07:19:28 -08006696 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006697 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006698 // Call into AM outside the synchronized block.
6699 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006700 } finally {
6701 Binder.restoreCallingIdentity(origId);
6702 }
6703 }
6704
6705 @Override
6706 public void cleanupDisabledPackageComponents(
6707 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6708 synchronized (mGlobalLock) {
6709 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006710 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006711 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006712 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 mStackSupervisor.scheduleIdleLocked();
6714 }
6715
6716 // Clean-up disabled tasks
6717 getRecentTasks().cleanupDisabledPackageTasksLocked(
6718 packageName, disabledClasses, userId);
6719 }
6720 }
6721
6722 @Override
6723 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6724 int userId) {
6725 synchronized (mGlobalLock) {
6726
6727 boolean didSomething =
6728 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006729 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 null, doit, evenPersistent, userId);
6731 return didSomething;
6732 }
6733 }
6734
6735 @Override
6736 public void resumeTopActivities(boolean scheduleIdle) {
6737 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006738 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006739 if (scheduleIdle) {
6740 mStackSupervisor.scheduleIdleLocked();
6741 }
6742 }
6743 }
6744
Riddle Hsua0536432019-02-16 00:38:59 +08006745 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 @Override
6747 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006748 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6750 }
6751 }
6752
Riddle Hsua0536432019-02-16 00:38:59 +08006753 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 @Override
6755 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006756 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006757 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 }
6759 }
6760
6761 @Override
6762 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6763 try {
6764 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6765 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6766 }
6767 } catch (RemoteException ex) {
6768 throw new SecurityException("Fail to check is caller a privileged app", ex);
6769 }
6770
6771 synchronized (mGlobalLock) {
6772 final long ident = Binder.clearCallingIdentity();
6773 try {
6774 if (mAmInternal.shouldConfirmCredentials(userId)) {
6775 if (mKeyguardController.isKeyguardLocked()) {
6776 // Showing launcher to avoid user entering credential twice.
6777 startHomeActivity(currentUserId, "notifyLockedProfile");
6778 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006779 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 }
6781 } finally {
6782 Binder.restoreCallingIdentity(ident);
6783 }
6784 }
6785 }
6786
6787 @Override
6788 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6789 mAmInternal.enforceCallingPermission(
6790 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6791
6792 synchronized (mGlobalLock) {
6793 final long ident = Binder.clearCallingIdentity();
6794 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006795 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6796 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6799 UserHandle.CURRENT);
6800 } finally {
6801 Binder.restoreCallingIdentity(ident);
6802 }
6803 }
6804 }
6805
6806 @Override
6807 public void writeActivitiesToProto(ProtoOutputStream proto) {
6808 synchronized (mGlobalLock) {
6809 // The output proto of "activity --proto activities"
6810 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006811 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006812 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6813 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 }
6815 }
6816
6817 @Override
6818 public void saveANRState(String reason) {
6819 synchronized (mGlobalLock) {
6820 final StringWriter sw = new StringWriter();
6821 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6822 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6823 if (reason != null) {
6824 pw.println(" Reason: " + reason);
6825 }
6826 pw.println();
6827 getActivityStartController().dump(pw, " ", null);
6828 pw.println();
6829 pw.println("-------------------------------------------------------------------------------");
6830 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6831 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6832 "" /* header */);
6833 pw.println();
6834 pw.close();
6835
6836 mLastANRState = sw.toString();
6837 }
6838 }
6839
6840 @Override
6841 public void clearSavedANRState() {
6842 synchronized (mGlobalLock) {
6843 mLastANRState = null;
6844 }
6845 }
6846
6847 @Override
6848 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6849 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6850 synchronized (mGlobalLock) {
6851 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6852 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6853 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6854 dumpLastANRLocked(pw);
6855 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6856 dumpLastANRTracesLocked(pw);
6857 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6858 dumpActivityStarterLocked(pw, dumpPackage);
6859 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6860 dumpActivityContainersLocked(pw);
6861 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6862 if (getRecentTasks() != null) {
6863 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6864 }
6865 }
6866 }
6867 }
6868
6869 @Override
6870 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6871 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6872 int wakefulness) {
6873 synchronized (mGlobalLock) {
6874 if (mHomeProcess != null && (dumpPackage == null
6875 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6876 if (needSep) {
6877 pw.println();
6878 needSep = false;
6879 }
6880 pw.println(" mHomeProcess: " + mHomeProcess);
6881 }
6882 if (mPreviousProcess != null && (dumpPackage == null
6883 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6884 if (needSep) {
6885 pw.println();
6886 needSep = false;
6887 }
6888 pw.println(" mPreviousProcess: " + mPreviousProcess);
6889 }
6890 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6891 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6892 StringBuilder sb = new StringBuilder(128);
6893 sb.append(" mPreviousProcessVisibleTime: ");
6894 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6895 pw.println(sb);
6896 }
6897 if (mHeavyWeightProcess != null && (dumpPackage == null
6898 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6899 if (needSep) {
6900 pw.println();
6901 needSep = false;
6902 }
6903 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6904 }
6905 if (dumpPackage == null) {
6906 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006907 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 }
6909 if (dumpAll) {
6910 if (dumpPackage == null) {
6911 pw.println(" mConfigWillChange: "
6912 + getTopDisplayFocusedStack().mConfigWillChange);
6913 }
6914 if (mCompatModePackages.getPackages().size() > 0) {
6915 boolean printed = false;
6916 for (Map.Entry<String, Integer> entry
6917 : mCompatModePackages.getPackages().entrySet()) {
6918 String pkg = entry.getKey();
6919 int mode = entry.getValue();
6920 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6921 continue;
6922 }
6923 if (!printed) {
6924 pw.println(" mScreenCompatPackages:");
6925 printed = true;
6926 }
6927 pw.println(" " + pkg + ": " + mode);
6928 }
6929 }
6930 }
6931
6932 if (dumpPackage == null) {
6933 pw.println(" mWakefulness="
6934 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006935 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 if (mRunningVoice != null) {
6937 pw.println(" mRunningVoice=" + mRunningVoice);
6938 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6939 }
6940 pw.println(" mSleeping=" + mSleeping);
6941 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6942 pw.println(" mVrController=" + mVrController);
6943 }
6944 if (mCurAppTimeTracker != null) {
6945 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6946 }
6947 if (mAllowAppSwitchUids.size() > 0) {
6948 boolean printed = false;
6949 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6950 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6951 for (int j = 0; j < types.size(); j++) {
6952 if (dumpPackage == null ||
6953 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6954 if (needSep) {
6955 pw.println();
6956 needSep = false;
6957 }
6958 if (!printed) {
6959 pw.println(" mAllowAppSwitchUids:");
6960 printed = true;
6961 }
6962 pw.print(" User ");
6963 pw.print(mAllowAppSwitchUids.keyAt(i));
6964 pw.print(": Type ");
6965 pw.print(types.keyAt(j));
6966 pw.print(" = ");
6967 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6968 pw.println();
6969 }
6970 }
6971 }
6972 }
6973 if (dumpPackage == null) {
6974 if (mController != null) {
6975 pw.println(" mController=" + mController
6976 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6977 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006978 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6979 pw.println(" mLaunchingActivityWakeLock="
6980 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 }
6982
6983 return needSep;
6984 }
6985 }
6986
6987 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006988 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6989 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006990 synchronized (mGlobalLock) {
6991 if (dumpPackage == null) {
6992 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6993 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006994 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6995 if (mRunningVoice != null) {
6996 final long vrToken = proto.start(
6997 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6998 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6999 mRunningVoice.toString());
7000 mVoiceWakeLock.writeToProto(
7001 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7002 proto.end(vrToken);
7003 }
7004 mVrController.writeToProto(proto,
7005 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007006 if (mController != null) {
7007 final long token = proto.start(CONTROLLER);
7008 proto.write(CONTROLLER, mController.toString());
7009 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7010 proto.end(token);
7011 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007012 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7013 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7014 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007015 }
7016
7017 if (mHomeProcess != null && (dumpPackage == null
7018 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007019 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007020 }
7021
7022 if (mPreviousProcess != null && (dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007024 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7026 }
7027
7028 if (mHeavyWeightProcess != null && (dumpPackage == null
7029 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007030 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007031 }
7032
7033 for (Map.Entry<String, Integer> entry
7034 : mCompatModePackages.getPackages().entrySet()) {
7035 String pkg = entry.getKey();
7036 int mode = entry.getValue();
7037 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7038 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7039 proto.write(PACKAGE, pkg);
7040 proto.write(MODE, mode);
7041 proto.end(compatToken);
7042 }
7043 }
7044
7045 if (mCurAppTimeTracker != null) {
7046 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7047 }
7048
7049 }
7050 }
7051
7052 @Override
7053 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7054 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7055 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007056 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7057 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007058 }
7059
7060 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007061 public void dumpForOom(PrintWriter pw) {
7062 synchronized (mGlobalLock) {
7063 pw.println(" mHomeProcess: " + mHomeProcess);
7064 pw.println(" mPreviousProcess: " + mPreviousProcess);
7065 if (mHeavyWeightProcess != null) {
7066 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7067 }
7068 }
7069 }
7070
7071 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 public boolean canGcNow() {
7073 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007074 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007075 }
7076 }
7077
Riddle Hsua0536432019-02-16 00:38:59 +08007078 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 @Override
7080 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007081 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007082 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 return top != null ? top.app : null;
7084 }
7085 }
7086
Riddle Hsua0536432019-02-16 00:38:59 +08007087 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 @Override
7089 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007090 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007091 if (mRootActivityContainer != null) {
7092 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094 }
7095 }
7096
7097 @Override
7098 public void scheduleDestroyAllActivities(String reason) {
7099 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007100 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 }
7102 }
7103
7104 @Override
7105 public void removeUser(int userId) {
7106 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007107 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007108 }
7109 }
7110
7111 @Override
7112 public boolean switchUser(int userId, UserState userState) {
7113 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007114 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 }
7116 }
7117
7118 @Override
7119 public void onHandleAppCrash(WindowProcessController wpc) {
7120 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007121 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 }
7123 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007124
7125 @Override
7126 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7127 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007128 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007129 }
7130 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007131
Riddle Hsua0536432019-02-16 00:38:59 +08007132 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007133 @Override
7134 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007135 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007136 }
7137
Riddle Hsua0536432019-02-16 00:38:59 +08007138 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007139 @Override
7140 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007141 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007142 }
7143
Riddle Hsua0536432019-02-16 00:38:59 +08007144 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007145 @Override
7146 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007147 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007148 }
7149
Riddle Hsua0536432019-02-16 00:38:59 +08007150 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007151 @Override
7152 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007153 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007154 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007155
7156 @Override
7157 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007158 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007159 mPendingTempWhitelist.put(uid, tag);
7160 }
7161 }
7162
7163 @Override
7164 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007165 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007166 mPendingTempWhitelist.remove(uid);
7167 }
7168 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007169
7170 @Override
7171 public boolean handleAppCrashInActivityController(String processName, int pid,
7172 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7173 Runnable killCrashingAppCallback) {
7174 synchronized (mGlobalLock) {
7175 if (mController == null) {
7176 return false;
7177 }
7178
7179 try {
7180 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7181 stackTrace)) {
7182 killCrashingAppCallback.run();
7183 return true;
7184 }
7185 } catch (RemoteException e) {
7186 mController = null;
7187 Watchdog.getInstance().setActivityController(null);
7188 }
7189 return false;
7190 }
7191 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007192
7193 @Override
7194 public void removeRecentTasksByPackageName(String packageName, int userId) {
7195 synchronized (mGlobalLock) {
7196 mRecentTasks.removeTasksByPackageName(packageName, userId);
7197 }
7198 }
7199
7200 @Override
7201 public void cleanupRecentTasksForUser(int userId) {
7202 synchronized (mGlobalLock) {
7203 mRecentTasks.cleanupLocked(userId);
7204 }
7205 }
7206
7207 @Override
7208 public void loadRecentTasksForUser(int userId) {
7209 synchronized (mGlobalLock) {
7210 mRecentTasks.loadUserRecentsLocked(userId);
7211 }
7212 }
7213
7214 @Override
7215 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7216 synchronized (mGlobalLock) {
7217 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7218 }
7219 }
7220
7221 @Override
7222 public void flushRecentTasks() {
7223 mRecentTasks.flush();
7224 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007225
7226 @Override
7227 public WindowProcessController getHomeProcess() {
7228 synchronized (mGlobalLock) {
7229 return mHomeProcess;
7230 }
7231 }
7232
7233 @Override
7234 public WindowProcessController getPreviousProcess() {
7235 synchronized (mGlobalLock) {
7236 return mPreviousProcess;
7237 }
7238 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007239
7240 @Override
7241 public void clearLockedTasks(String reason) {
7242 synchronized (mGlobalLock) {
7243 getLockTaskController().clearLockedTasks(reason);
7244 }
7245 }
7246
7247 @Override
7248 public void updateUserConfiguration() {
7249 synchronized (mGlobalLock) {
7250 final Configuration configuration = new Configuration(getGlobalConfiguration());
7251 final int currentUserId = mAmInternal.getCurrentUserId();
7252 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7253 configuration, currentUserId, Settings.System.canWrite(mContext));
7254 updateConfigurationLocked(configuration, null /* starting */,
7255 false /* initLocale */, false /* persistent */, currentUserId,
7256 false /* deferResume */);
7257 }
7258 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007259
7260 @Override
7261 public boolean canShowErrorDialogs() {
7262 synchronized (mGlobalLock) {
7263 return mShowDialogs && !mSleeping && !mShuttingDown
7264 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7265 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7266 mAmInternal.getCurrentUserId())
7267 && !(UserManager.isDeviceInDemoMode(mContext)
7268 && mAmInternal.getCurrentUser().isDemo());
7269 }
7270 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007271
7272 @Override
7273 public void setProfileApp(String profileApp) {
7274 synchronized (mGlobalLock) {
7275 mProfileApp = profileApp;
7276 }
7277 }
7278
7279 @Override
7280 public void setProfileProc(WindowProcessController wpc) {
7281 synchronized (mGlobalLock) {
7282 mProfileProc = wpc;
7283 }
7284 }
7285
7286 @Override
7287 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7288 synchronized (mGlobalLock) {
7289 mProfilerInfo = profilerInfo;
7290 }
7291 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007292
7293 @Override
7294 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7295 synchronized (mGlobalLock) {
7296 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7297 }
7298 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007299
7300 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007301 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7302 boolean reducedResolution) {
7303 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7304 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007305 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007306
7307 @Override
7308 public boolean isUidForeground(int uid) {
7309 synchronized (mGlobalLock) {
7310 return ActivityTaskManagerService.this.isUidForeground(uid);
7311 }
7312 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007313
7314 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007315 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007316 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007317 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007318 }
7319 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007320
7321 @Override
7322 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007323 // Translate package names into UIDs
7324 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007325 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007326 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7327 if (uid >= 0) {
7328 result.add(uid);
7329 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007330 }
7331 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007332 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007333 }
7334 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007335 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007336}