blob: 18532092f81726389ef83c07ec4814e2ac45b7cf [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 }
1952 final boolean translucentChanged = r.changeWindowTranslucency(true);
1953 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001954 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 return translucentChanged;
1958 }
1959 } finally {
1960 Binder.restoreCallingIdentity(origId);
1961 }
1962 }
1963
1964 @Override
1965 public boolean convertToTranslucent(IBinder token, Bundle options) {
1966 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1967 final long origId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return false;
1973 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001974 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 int index = task.mActivities.lastIndexOf(r);
1976 if (index > 0) {
1977 ActivityRecord under = task.mActivities.get(index - 1);
1978 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1979 }
1980 final boolean translucentChanged = r.changeWindowTranslucency(false);
1981 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001982 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001984 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001985 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 return translucentChanged;
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(origId);
1990 }
1991 }
1992
1993 @Override
1994 public void notifyActivityDrawn(IBinder token) {
1995 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1996 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001997 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001999 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 }
2001 }
2002 }
2003
2004 @Override
2005 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2006 synchronized (mGlobalLock) {
2007 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2008 if (r == null) {
2009 return;
2010 }
2011 r.reportFullyDrawnLocked(restoredFromBundle);
2012 }
2013 }
2014
2015 @Override
2016 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2017 synchronized (mGlobalLock) {
2018 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2019 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2020 return stack.mDisplayId;
2021 }
2022 return DEFAULT_DISPLAY;
2023 }
2024 }
2025
2026 @Override
2027 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002028 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 long ident = Binder.clearCallingIdentity();
2030 try {
2031 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002032 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002034 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 }
2036 return null;
2037 }
2038 } finally {
2039 Binder.restoreCallingIdentity(ident);
2040 }
2041 }
2042
2043 @Override
2044 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2047 final long callingId = Binder.clearCallingIdentity();
2048 try {
2049 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002050 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (stack == null) {
2052 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2053 return;
2054 }
2055 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002056 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002057 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 }
2059 }
2060 } finally {
2061 Binder.restoreCallingIdentity(callingId);
2062 }
2063 }
2064
2065 @Override
2066 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002067 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2069 final long callingId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002072 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002073 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 if (task == null) {
2075 return;
2076 }
2077 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002078 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002079 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 }
2081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(callingId);
2084 }
2085 }
2086
2087 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002088 public void restartActivityProcessIfVisible(IBinder activityToken) {
2089 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2090 final long callingId = Binder.clearCallingIdentity();
2091 try {
2092 synchronized (mGlobalLock) {
2093 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2094 if (r == null) {
2095 return;
2096 }
2097 r.restartProcessIfVisible();
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002106 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 synchronized (mGlobalLock) {
2108 final long ident = Binder.clearCallingIdentity();
2109 try {
2110 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2111 "remove-task");
2112 } finally {
2113 Binder.restoreCallingIdentity(ident);
2114 }
2115 }
2116 }
2117
2118 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002119 public void removeAllVisibleRecentTasks() {
2120 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2121 synchronized (mGlobalLock) {
2122 final long ident = Binder.clearCallingIdentity();
2123 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002124 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002125 } finally {
2126 Binder.restoreCallingIdentity(ident);
2127 }
2128 }
2129 }
2130
2131 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2133 synchronized (mGlobalLock) {
2134 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2135 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002136 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 }
2138 }
2139 return false;
2140 }
2141
2142 @Override
2143 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2144 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002145
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002146 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002147 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2148 if (r != null) {
2149 return r.getActivityStack().navigateUpToLocked(
2150 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002151 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002152 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 }
2154 }
2155
2156 /**
2157 * Attempts to move a task backwards in z-order (the order of activities within the task is
2158 * unchanged).
2159 *
2160 * There are several possible results of this call:
2161 * - if the task is locked, then we will show the lock toast
2162 * - if there is a task behind the provided task, then that task is made visible and resumed as
2163 * this task is moved to the back
2164 * - otherwise, if there are no other tasks in the stack:
2165 * - if this task is in the pinned stack, then we remove the stack completely, which will
2166 * have the effect of moving the task to the top or bottom of the fullscreen stack
2167 * (depending on whether it is visible)
2168 * - otherwise, we simply return home and hide this task
2169 *
2170 * @param token A reference to the activity we wish to move
2171 * @param nonRoot If false then this only works if the activity is the root
2172 * of a task; if true it will work for any activity in a task.
2173 * @return Returns true if the move completed, false if not.
2174 */
2175 @Override
2176 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 synchronized (mGlobalLock) {
2179 final long origId = Binder.clearCallingIdentity();
2180 try {
2181 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002182 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183 if (task != null) {
2184 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2185 }
2186 } finally {
2187 Binder.restoreCallingIdentity(origId);
2188 }
2189 }
2190 return false;
2191 }
2192
2193 @Override
2194 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002195 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 long ident = Binder.clearCallingIdentity();
2197 Rect rect = new Rect();
2198 try {
2199 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002200 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2202 if (task == null) {
2203 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2204 return rect;
2205 }
2206 if (task.getStack() != null) {
2207 // Return the bounds from window manager since it will be adjusted for various
2208 // things like the presense of a docked stack for tasks that aren't resizeable.
2209 task.getWindowContainerBounds(rect);
2210 } else {
2211 // Task isn't in window manager yet since it isn't associated with a stack.
2212 // Return the persist value from activity manager
2213 if (!task.matchParentBounds()) {
2214 rect.set(task.getBounds());
2215 } else if (task.mLastNonFullscreenBounds != null) {
2216 rect.set(task.mLastNonFullscreenBounds);
2217 }
2218 }
2219 }
2220 } finally {
2221 Binder.restoreCallingIdentity(ident);
2222 }
2223 return rect;
2224 }
2225
2226 @Override
2227 public ActivityManager.TaskDescription getTaskDescription(int id) {
2228 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002229 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002231 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2233 if (tr != null) {
2234 return tr.lastTaskDescription;
2235 }
2236 }
2237 return null;
2238 }
2239
2240 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002241 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2242 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2243 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2244 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2245 return;
2246 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002248 synchronized (mGlobalLock) {
2249 final long ident = Binder.clearCallingIdentity();
2250 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002251 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002252 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002253 if (task == null) {
2254 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2255 return;
2256 }
2257
2258 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2259 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2260
2261 if (!task.isActivityTypeStandardOrUndefined()) {
2262 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2263 + " non-standard task " + taskId + " to windowing mode="
2264 + windowingMode);
2265 }
2266
2267 final ActivityStack stack = task.getStack();
2268 if (toTop) {
2269 stack.moveToFront("setTaskWindowingMode", task);
2270 }
2271 stack.setWindowingMode(windowingMode);
2272 } finally {
2273 Binder.restoreCallingIdentity(ident);
2274 }
2275 }
2276 }
2277
2278 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002279 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002280 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281 ActivityRecord r = getCallingRecordLocked(token);
2282 return r != null ? r.info.packageName : null;
2283 }
2284 }
2285
2286 @Override
2287 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002288 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 ActivityRecord r = getCallingRecordLocked(token);
2290 return r != null ? r.intent.getComponent() : null;
2291 }
2292 }
2293
2294 private ActivityRecord getCallingRecordLocked(IBinder token) {
2295 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2296 if (r == null) {
2297 return null;
2298 }
2299 return r.resultTo;
2300 }
2301
2302 @Override
2303 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002304 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305
2306 synchronized (mGlobalLock) {
2307 final long origId = Binder.clearCallingIdentity();
2308 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002309 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 } finally {
2311 Binder.restoreCallingIdentity(origId);
2312 }
2313 }
2314 }
2315
Mark Renouf446251d2019-04-26 10:22:41 -04002316 @Override
2317 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2318 synchronized (mGlobalLock) {
2319 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2320 if (r == null) {
2321 return;
2322 }
2323 ActivityStack stack = r.getActivityStack();
2324 if (stack != null && stack.isSingleTaskInstance()) {
2325 // Single-task stacks are used for activities which are presented in floating
2326 // windows above full screen activities. Instead of directly finishing the
2327 // task, a task change listener is used to notify SystemUI so the action can be
2328 // handled specially.
2329 final TaskRecord task = r.getTaskRecord();
2330 mTaskChangeNotificationController
2331 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2332 } else {
2333 try {
2334 callback.requestFinish();
2335 } catch (RemoteException e) {
2336 Slog.e(TAG, "Failed to invoke request finish callback", e);
2337 }
2338 }
2339 }
2340 }
2341
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002342 /**
2343 * TODO: Add mController hook
2344 */
2345 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002346 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2347 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002348 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002349
2350 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2351 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002352 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2353 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 }
2355 }
2356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2358 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002360
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 final int callingPid = Binder.getCallingPid();
2362 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002363 if (!isSameApp(callingUid, callingPackage)) {
2364 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2365 + Binder.getCallingPid() + " as package " + callingPackage;
2366 Slog.w(TAG, msg);
2367 throw new SecurityException(msg);
2368 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 SafeActivityOptions.abort(options);
2371 return;
2372 }
2373 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002374 WindowProcessController callerApp = null;
2375 if (appThread != null) {
2376 callerApp = getProcessController(appThread);
2377 }
2378 final ActivityStarter starter = getActivityStartController().obtainStarter(
2379 null /* intent */, "moveTaskToFront");
2380 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2381 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002382 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 return;
2384 }
2385 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002387 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 if (task == null) {
2389 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002390 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 return;
2392 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002393 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002395 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 return;
2397 }
2398 ActivityOptions realOptions = options != null
2399 ? options.getOptions(mStackSupervisor)
2400 : null;
2401 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2402 false /* forceNonResizable */);
2403
2404 final ActivityRecord topActivity = task.getTopActivity();
2405 if (topActivity != null) {
2406
2407 // We are reshowing a task, use a starting window to hide the initial draw delay
2408 // so the transition can start earlier.
2409 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2410 true /* taskSwitch */, fromRecents);
2411 }
2412 } finally {
2413 Binder.restoreCallingIdentity(origId);
2414 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415 }
2416
Ricky Waiaca8a772019-04-04 16:01:06 +01002417 /**
2418 * Return true if callingUid is system, or packageName belongs to that callingUid.
2419 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002420 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002421 try {
2422 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2423 if (packageName == null) {
2424 return false;
2425 }
2426 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2427 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2428 UserHandle.getUserId(callingUid));
2429 return UserHandle.isSameApp(callingUid, uid);
2430 }
2431 } catch (RemoteException e) {
2432 // Should not happen
2433 }
2434 return true;
2435 }
2436
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002437 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2438 int callingPid, int callingUid, String name) {
2439 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2440 return true;
2441 }
2442
2443 if (getRecentTasks().isCallerRecents(sourceUid)) {
2444 return true;
2445 }
2446
2447 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2448 if (perm == PackageManager.PERMISSION_GRANTED) {
2449 return true;
2450 }
2451 if (checkAllowAppSwitchUid(sourceUid)) {
2452 return true;
2453 }
2454
2455 // If the actual IPC caller is different from the logical source, then
2456 // also see if they are allowed to control app switches.
2457 if (callingUid != -1 && callingUid != sourceUid) {
2458 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2459 if (perm == PackageManager.PERMISSION_GRANTED) {
2460 return true;
2461 }
2462 if (checkAllowAppSwitchUid(callingUid)) {
2463 return true;
2464 }
2465 }
2466
2467 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2468 return false;
2469 }
2470
2471 private boolean checkAllowAppSwitchUid(int uid) {
2472 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2473 if (types != null) {
2474 for (int i = types.size() - 1; i >= 0; i--) {
2475 if (types.valueAt(i).intValue() == uid) {
2476 return true;
2477 }
2478 }
2479 }
2480 return false;
2481 }
2482
2483 @Override
2484 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2485 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2486 "setActivityController()");
2487 synchronized (mGlobalLock) {
2488 mController = controller;
2489 mControllerIsAMonkey = imAMonkey;
2490 Watchdog.getInstance().setActivityController(controller);
2491 }
2492 }
2493
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002494 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002495 synchronized (mGlobalLock) {
2496 return mController != null && mControllerIsAMonkey;
2497 }
2498 }
2499
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002500 @Override
2501 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2502 synchronized (mGlobalLock) {
2503 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2504 }
2505 }
2506
2507 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2509 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2510 }
2511
2512 @Override
2513 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2514 @WindowConfiguration.ActivityType int ignoreActivityType,
2515 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2516 final int callingUid = Binder.getCallingUid();
2517 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2518
2519 synchronized (mGlobalLock) {
2520 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2521
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002522 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002523 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002524 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002525 ignoreWindowingMode, callingUid, allowed);
2526 }
2527
2528 return list;
2529 }
2530
2531 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002532 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2533 synchronized (mGlobalLock) {
2534 final long origId = Binder.clearCallingIdentity();
2535 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2536 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002537 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 }
2539 Binder.restoreCallingIdentity(origId);
2540 }
2541 }
2542
2543 @Override
2544 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002545 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 ActivityStack stack = ActivityRecord.getStackLocked(token);
2547 if (stack != null) {
2548 return stack.willActivityBeVisibleLocked(token);
2549 }
2550 return false;
2551 }
2552 }
2553
2554 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002556 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 synchronized (mGlobalLock) {
2558 final long ident = Binder.clearCallingIdentity();
2559 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002560 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002561 if (task == null) {
2562 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2563 return;
2564 }
2565
2566 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2567 + " to stackId=" + stackId + " toTop=" + toTop);
2568
Wale Ogunwaled32da472018-11-16 07:19:28 -08002569 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002570 if (stack == null) {
2571 throw new IllegalStateException(
2572 "moveTaskToStack: No stack for stackId=" + stackId);
2573 }
2574 if (!stack.isActivityTypeStandardOrUndefined()) {
2575 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2576 + taskId + " to stack " + stackId);
2577 }
2578 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002579 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2581 }
2582 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2583 "moveTaskToStack");
2584 } finally {
2585 Binder.restoreCallingIdentity(ident);
2586 }
2587 }
2588 }
2589
2590 @Override
2591 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2592 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594
2595 final long ident = Binder.clearCallingIdentity();
2596 try {
2597 synchronized (mGlobalLock) {
2598 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002599 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002600 if (stack == null) {
2601 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2602 return;
2603 }
2604 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2605 throw new IllegalArgumentException("Stack: " + stackId
2606 + " doesn't support animated resize.");
2607 }
2608 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2609 animationDuration, false /* fromFullscreen */);
2610 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002611 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002612 if (stack == null) {
2613 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2614 return;
2615 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002616 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2618 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2619 }
2620 }
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625
wilsonshih5c4cf522019-01-25 09:03:47 +08002626 @Override
2627 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2628 int animationDuration) {
2629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2630
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
2633 synchronized (mGlobalLock) {
2634 if (xOffset == 0 && yOffset == 0) {
2635 return;
2636 }
2637 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2638 if (stack == null) {
2639 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2640 return;
2641 }
2642 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2643 throw new IllegalArgumentException("Stack: " + stackId
2644 + " doesn't support animated resize.");
2645 }
2646 final Rect destBounds = new Rect();
2647 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002648 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002649 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2650 return;
2651 }
2652 destBounds.offset(xOffset, yOffset);
2653 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2654 animationDuration, false /* fromFullscreen */);
2655 }
2656 } finally {
2657 Binder.restoreCallingIdentity(ident);
2658 }
2659 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002660 /**
2661 * Moves the specified task to the primary-split-screen stack.
2662 *
2663 * @param taskId Id of task to move.
2664 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2665 * exist already. See
2666 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2667 * and
2668 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2669 * @param toTop If the task and stack should be moved to the top.
2670 * @param animate Whether we should play an animation for the moving the task.
2671 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2672 * stack. Pass {@code null} to use default bounds.
2673 * @param showRecents If the recents activity should be shown on the other side of the task
2674 * going into split-screen mode.
2675 */
2676 @Override
2677 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2678 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002679 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 "setTaskWindowingModeSplitScreenPrimary()");
2681 synchronized (mGlobalLock) {
2682 final long ident = Binder.clearCallingIdentity();
2683 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002684 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002685 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686 if (task == null) {
2687 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2688 return false;
2689 }
2690 if (DEBUG_STACK) Slog.d(TAG_STACK,
2691 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2692 + " to createMode=" + createMode + " toTop=" + toTop);
2693 if (!task.isActivityTypeStandardOrUndefined()) {
2694 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2695 + " non-standard task " + taskId + " to split-screen windowing mode");
2696 }
2697
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002698 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 final int windowingMode = task.getWindowingMode();
2700 final ActivityStack stack = task.getStack();
2701 if (toTop) {
2702 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2703 }
2704 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002705 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2706 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 return windowingMode != task.getWindowingMode();
2708 } finally {
2709 Binder.restoreCallingIdentity(ident);
2710 }
2711 }
2712 }
2713
2714 /**
2715 * Removes stacks in the input windowing modes from the system if they are of activity type
2716 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2717 */
2718 @Override
2719 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002720 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 "removeStacksInWindowingModes()");
2722
2723 synchronized (mGlobalLock) {
2724 final long ident = Binder.clearCallingIdentity();
2725 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002726 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731 }
2732
2733 @Override
2734 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002735 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 "removeStacksWithActivityTypes()");
2737
2738 synchronized (mGlobalLock) {
2739 final long ident = Binder.clearCallingIdentity();
2740 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002741 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 } finally {
2743 Binder.restoreCallingIdentity(ident);
2744 }
2745 }
2746 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747
2748 @Override
2749 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2750 int userId) {
2751 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2753 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 final boolean detailed = checkGetTasksPermission(
2756 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2757 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 == PackageManager.PERMISSION_GRANTED;
2759
2760 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002761 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 callingUid);
2763 }
2764 }
2765
2766 @Override
2767 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 long ident = Binder.clearCallingIdentity();
2770 try {
2771 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002772 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 }
2774 } finally {
2775 Binder.restoreCallingIdentity(ident);
2776 }
2777 }
2778
2779 @Override
2780 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 long ident = Binder.clearCallingIdentity();
2783 try {
2784 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002785 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 }
2787 } finally {
2788 Binder.restoreCallingIdentity(ident);
2789 }
2790 }
2791
2792 @Override
2793 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002794 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 final long callingUid = Binder.getCallingUid();
2796 final long origId = Binder.clearCallingIdentity();
2797 try {
2798 synchronized (mGlobalLock) {
2799 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002800 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2802 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2803 }
2804 } finally {
2805 Binder.restoreCallingIdentity(origId);
2806 }
2807 }
2808
2809 @Override
2810 public void startLockTaskModeByToken(IBinder token) {
2811 synchronized (mGlobalLock) {
2812 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2813 if (r == null) {
2814 return;
2815 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002816 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 }
2818 }
2819
2820 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002821 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002822 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 // This makes inner call to look as if it was initiated by system.
2824 long ident = Binder.clearCallingIdentity();
2825 try {
2826 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002827 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002828 MATCH_TASK_IN_STACKS_ONLY);
2829 if (task == null) {
2830 return;
2831 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832
2833 // When starting lock task mode the stack must be in front and focused
2834 task.getStack().moveToFront("startSystemLockTaskMode");
2835 startLockTaskModeLocked(task, true /* isSystemCaller */);
2836 }
2837 } finally {
2838 Binder.restoreCallingIdentity(ident);
2839 }
2840 }
2841
2842 @Override
2843 public void stopLockTaskModeByToken(IBinder token) {
2844 synchronized (mGlobalLock) {
2845 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2846 if (r == null) {
2847 return;
2848 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002849 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 }
2851 }
2852
2853 /**
2854 * This API should be called by SystemUI only when user perform certain action to dismiss
2855 * lock task mode. We should only dismiss pinned lock task mode in this case.
2856 */
2857 @Override
2858 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002859 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2861 }
2862
2863 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2864 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2865 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2866 return;
2867 }
2868
Wale Ogunwaled32da472018-11-16 07:19:28 -08002869 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 if (stack == null || task != stack.topTask()) {
2871 throw new IllegalArgumentException("Invalid task, not in foreground");
2872 }
2873
2874 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2875 // system or a specific app.
2876 // * System-initiated requests will only start the pinned mode (screen pinning)
2877 // * App-initiated requests
2878 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2879 // - will start the pinned mode, otherwise
2880 final int callingUid = Binder.getCallingUid();
2881 long ident = Binder.clearCallingIdentity();
2882 try {
2883 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002884 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002886 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 } finally {
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891
2892 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2893 final int callingUid = Binder.getCallingUid();
2894 long ident = Binder.clearCallingIdentity();
2895 try {
2896 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002897 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 }
2899 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2900 // task and jumping straight into a call in the case of emergency call back.
2901 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2902 if (tm != null) {
2903 tm.showInCallScreen(false);
2904 }
2905 } finally {
2906 Binder.restoreCallingIdentity(ident);
2907 }
2908 }
2909
2910 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002911 public void updateLockTaskPackages(int userId, String[] packages) {
2912 final int callingUid = Binder.getCallingUid();
2913 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2914 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2915 "updateLockTaskPackages()");
2916 }
2917 synchronized (this) {
2918 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2919 + Arrays.toString(packages));
2920 getLockTaskController().updateLockTaskPackages(userId, packages);
2921 }
2922 }
2923
2924 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 public boolean isInLockTaskMode() {
2926 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2927 }
2928
2929 @Override
2930 public int getLockTaskModeState() {
2931 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002932 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 }
2934 }
2935
2936 @Override
2937 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2938 synchronized (mGlobalLock) {
2939 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2940 if (r != null) {
2941 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002942 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002944 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 }
2946 }
2947 }
2948
2949 @Override
2950 public Bundle getActivityOptions(IBinder token) {
2951 final long origId = Binder.clearCallingIdentity();
2952 try {
2953 synchronized (mGlobalLock) {
2954 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2955 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002956 final ActivityOptions activityOptions = r.takeOptionsLocked(
2957 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 return activityOptions == null ? null : activityOptions.toBundle();
2959 }
2960 return null;
2961 }
2962 } finally {
2963 Binder.restoreCallingIdentity(origId);
2964 }
2965 }
2966
2967 @Override
2968 public List<IBinder> getAppTasks(String callingPackage) {
2969 int callingUid = Binder.getCallingUid();
2970 long ident = Binder.clearCallingIdentity();
2971 try {
2972 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002973 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 }
2975 } finally {
2976 Binder.restoreCallingIdentity(ident);
2977 }
2978 }
2979
2980 @Override
2981 public void finishVoiceTask(IVoiceInteractionSession session) {
2982 synchronized (mGlobalLock) {
2983 final long origId = Binder.clearCallingIdentity();
2984 try {
2985 // TODO: VI Consider treating local voice interactions and voice tasks
2986 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002987 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 } finally {
2989 Binder.restoreCallingIdentity(origId);
2990 }
2991 }
2992
2993 }
2994
2995 @Override
2996 public boolean isTopOfTask(IBinder token) {
2997 synchronized (mGlobalLock) {
2998 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002999 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 }
3001 }
3002
3003 @Override
3004 public void notifyLaunchTaskBehindComplete(IBinder token) {
3005 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3006 }
3007
3008 @Override
3009 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 mH.post(() -> {
3011 synchronized (mGlobalLock) {
3012 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003013 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003014 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003015 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003016 } catch (RemoteException e) {
3017 }
3018 }
3019 }
3020
3021 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 }
3023
3024 /** Called from an app when assist data is ready. */
3025 @Override
3026 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3027 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003028 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 synchronized (pae) {
3030 pae.result = extras;
3031 pae.structure = structure;
3032 pae.content = content;
3033 if (referrer != null) {
3034 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3035 }
3036 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003037 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003038 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3039 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 structure.setHomeActivity(pae.isHome);
3041 }
3042 pae.haveResult = true;
3043 pae.notifyAll();
3044 if (pae.intent == null && pae.receiver == null) {
3045 // Caller is just waiting for the result.
3046 return;
3047 }
3048 }
3049 // We are now ready to launch the assist activity.
3050 IAssistDataReceiver sendReceiver = null;
3051 Bundle sendBundle = null;
3052 synchronized (mGlobalLock) {
3053 buildAssistBundleLocked(pae, extras);
3054 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 if (!exists) {
3057 // Timed out.
3058 return;
3059 }
3060
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003061 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 // Caller wants result sent back to them.
3063 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003064 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3065 pae.activity.getTaskRecord().taskId);
3066 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3067 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3069 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3070 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3071 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3072 }
3073 }
3074 if (sendReceiver != null) {
3075 try {
3076 sendReceiver.onHandleAssistData(sendBundle);
3077 } catch (RemoteException e) {
3078 }
3079 return;
3080 }
3081
3082 final long ident = Binder.clearCallingIdentity();
3083 try {
3084 if (TextUtils.equals(pae.intent.getAction(),
3085 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003086 // Start voice interaction through VoiceInteractionManagerService.
3087 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3088 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 } else {
3090 pae.intent.replaceExtras(pae.extras);
3091 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3092 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3093 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003094 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095
3096 try {
3097 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3098 } catch (ActivityNotFoundException e) {
3099 Slog.w(TAG, "No activity to handle assist action.", e);
3100 }
3101 }
3102 } finally {
3103 Binder.restoreCallingIdentity(ident);
3104 }
3105 }
3106
3107 @Override
3108 public int addAppTask(IBinder activityToken, Intent intent,
3109 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3110 final int callingUid = Binder.getCallingUid();
3111 final long callingIdent = Binder.clearCallingIdentity();
3112
3113 try {
3114 synchronized (mGlobalLock) {
3115 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3116 if (r == null) {
3117 throw new IllegalArgumentException("Activity does not exist; token="
3118 + activityToken);
3119 }
3120 ComponentName comp = intent.getComponent();
3121 if (comp == null) {
3122 throw new IllegalArgumentException("Intent " + intent
3123 + " must specify explicit component");
3124 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003125 if (thumbnail.getWidth() != mThumbnailWidth
3126 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 throw new IllegalArgumentException("Bad thumbnail size: got "
3128 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003129 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 }
3131 if (intent.getSelector() != null) {
3132 intent.setSelector(null);
3133 }
3134 if (intent.getSourceBounds() != null) {
3135 intent.setSourceBounds(null);
3136 }
3137 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3138 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3139 // The caller has added this as an auto-remove task... that makes no
3140 // sense, so turn off auto-remove.
3141 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3142 }
3143 }
3144 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3145 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3146 if (ainfo.applicationInfo.uid != callingUid) {
3147 throw new SecurityException(
3148 "Can't add task for another application: target uid="
3149 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3150 }
3151
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003152 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003154 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003155 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003156 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 // The app has too many tasks already and we can't add any more
3158 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3159 return INVALID_TASK_ID;
3160 }
3161 task.lastTaskDescription.copyFrom(description);
3162
3163 // TODO: Send the thumbnail to WM to store it.
3164
3165 return task.taskId;
3166 }
3167 } finally {
3168 Binder.restoreCallingIdentity(callingIdent);
3169 }
3170 }
3171
3172 @Override
3173 public Point getAppTaskThumbnailSize() {
3174 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 }
3177 }
3178
3179 @Override
3180 public void setTaskResizeable(int taskId, int resizeableMode) {
3181 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003182 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3184 if (task == null) {
3185 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3186 return;
3187 }
3188 task.setResizeMode(resizeableMode);
3189 }
3190 }
3191
3192 @Override
3193 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003194 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 long ident = Binder.clearCallingIdentity();
3196 try {
3197 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003198 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003199 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 if (task == null) {
3201 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3202 return;
3203 }
3204 // Place the task in the right stack if it isn't there already based on
3205 // the requested bounds.
3206 // The stack transition logic is:
3207 // - a null bounds on a freeform task moves that task to fullscreen
3208 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3209 // that task to freeform
3210 // - otherwise the task is not moved
3211 ActivityStack stack = task.getStack();
3212 if (!task.getWindowConfiguration().canResizeTask()) {
3213 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3214 }
3215 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3216 stack = stack.getDisplay().getOrCreateStack(
3217 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3218 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3219 stack = stack.getDisplay().getOrCreateStack(
3220 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3221 }
3222
3223 // Reparent the task to the right stack if necessary
3224 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3225 if (stack != task.getStack()) {
3226 // Defer resume until the task is resized below
3227 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3228 DEFER_RESUME, "resizeTask");
3229 preserveWindow = false;
3230 }
3231
3232 // After reparenting (which only resizes the task to the stack bounds), resize the
3233 // task to the actual bounds provided
3234 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3235 }
3236 } finally {
3237 Binder.restoreCallingIdentity(ident);
3238 }
3239 }
3240
3241 @Override
3242 public boolean releaseActivityInstance(IBinder token) {
3243 synchronized (mGlobalLock) {
3244 final long origId = Binder.clearCallingIdentity();
3245 try {
3246 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3247 if (r == null) {
3248 return false;
3249 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003250 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 } finally {
3252 Binder.restoreCallingIdentity(origId);
3253 }
3254 }
3255 }
3256
3257 @Override
3258 public void releaseSomeActivities(IApplicationThread appInt) {
3259 synchronized (mGlobalLock) {
3260 final long origId = Binder.clearCallingIdentity();
3261 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003262 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003263 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 } finally {
3265 Binder.restoreCallingIdentity(origId);
3266 }
3267 }
3268 }
3269
3270 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003271 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003272 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003273 != PackageManager.PERMISSION_GRANTED) {
3274 throw new SecurityException("Requires permission "
3275 + android.Manifest.permission.DEVICE_POWER);
3276 }
3277
3278 synchronized (mGlobalLock) {
3279 long ident = Binder.clearCallingIdentity();
3280 if (mKeyguardShown != keyguardShowing) {
3281 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003282 final Message msg = PooledLambda.obtainMessage(
3283 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3284 keyguardShowing);
3285 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 }
3287 try {
wilsonshih177261f2019-02-22 12:02:18 +08003288 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 } finally {
3290 Binder.restoreCallingIdentity(ident);
3291 }
3292 }
3293
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003294 mH.post(() -> {
3295 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3296 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3297 }
3298 });
3299 }
3300
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003301 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003302 mH.post(() -> {
3303 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3304 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3305 }
3306 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003307 }
3308
3309 @Override
3310 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003311 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3312 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313
3314 final File passedIconFile = new File(filePath);
3315 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3316 passedIconFile.getName());
3317 if (!legitIconFile.getPath().equals(filePath)
3318 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3319 throw new IllegalArgumentException("Bad file path: " + filePath
3320 + " passed for userId " + userId);
3321 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003322 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 }
3324
3325 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3328 final ActivityOptions activityOptions = safeOptions != null
3329 ? safeOptions.getOptions(mStackSupervisor)
3330 : null;
3331 if (activityOptions == null
3332 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3333 || activityOptions.getCustomInPlaceResId() == 0) {
3334 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3335 "with valid animation");
3336 }
lumark588a3e82018-07-20 18:53:54 +08003337 // Get top display of front most application.
3338 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3339 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003340 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3341 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3342 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003343 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003344 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003345 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 }
3347
3348 @Override
3349 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003350 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 synchronized (mGlobalLock) {
3352 final long ident = Binder.clearCallingIdentity();
3353 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003354 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 if (stack == null) {
3356 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3357 return;
3358 }
3359 if (!stack.isActivityTypeStandardOrUndefined()) {
3360 throw new IllegalArgumentException(
3361 "Removing non-standard stack is not allowed.");
3362 }
3363 mStackSupervisor.removeStack(stack);
3364 } finally {
3365 Binder.restoreCallingIdentity(ident);
3366 }
3367 }
3368 }
3369
3370 @Override
3371 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003372 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373
3374 synchronized (mGlobalLock) {
3375 final long ident = Binder.clearCallingIdentity();
3376 try {
3377 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3378 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003379 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 } finally {
3381 Binder.restoreCallingIdentity(ident);
3382 }
3383 }
3384 }
3385
3386 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003387 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 synchronized (mGlobalLock) {
3389 long ident = Binder.clearCallingIdentity();
3390 try {
3391 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3392 if (r == null) {
3393 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003394 "toggleFreeformWindowingMode: No activity record matching token="
3395 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003398 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003399 if (stack == null) {
3400 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3401 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 }
3403
Yunfan Chend967af82019-01-17 18:30:18 +09003404 if (!stack.inFreeformWindowingMode()
3405 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3406 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3407 + "toggle between fullscreen and freeform.");
3408 }
3409
3410 if (stack.inFreeformWindowingMode()) {
3411 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003412 } else if (stack.getParent().inFreeformWindowingMode()) {
3413 // If the window is on a freeform display, set it to undefined. It will be
3414 // resolved to freeform and it can adjust windowing mode when the display mode
3415 // changes in runtime.
3416 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003417 } else {
3418 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3419 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 } finally {
3421 Binder.restoreCallingIdentity(ident);
3422 }
3423 }
3424 }
3425
3426 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3427 @Override
3428 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003431 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
3434 /** Unregister a task stack listener so that it stops receiving callbacks. */
3435 @Override
3436 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003439 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 @Override
3443 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3444 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3445 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3446 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3447 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3448 }
3449
3450 @Override
3451 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3452 IBinder activityToken, int flags) {
3453 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3454 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3455 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3456 }
3457
3458 @Override
3459 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3460 Bundle args) {
3461 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3462 true /* focused */, true /* newSessionId */, userHandle, args,
3463 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3464 }
3465
3466 @Override
3467 public Bundle getAssistContextExtras(int requestType) {
3468 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3469 null, null, true /* focused */, true /* newSessionId */,
3470 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3471 if (pae == null) {
3472 return null;
3473 }
3474 synchronized (pae) {
3475 while (!pae.haveResult) {
3476 try {
3477 pae.wait();
3478 } catch (InterruptedException e) {
3479 }
3480 }
3481 }
3482 synchronized (mGlobalLock) {
3483 buildAssistBundleLocked(pae, pae.result);
3484 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003485 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486 }
3487 return pae.extras;
3488 }
3489
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003490 /**
3491 * Binder IPC calls go through the public entry point.
3492 * This can be called with or without the global lock held.
3493 */
3494 private static int checkCallingPermission(String permission) {
3495 return checkPermission(
3496 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3497 }
3498
3499 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003500 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003501 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3502 mAmInternal.enforceCallingPermission(permission, func);
3503 }
3504 }
3505
3506 @VisibleForTesting
3507 int checkGetTasksPermission(String permission, int pid, int uid) {
3508 return checkPermission(permission, pid, uid);
3509 }
3510
3511 static int checkPermission(String permission, int pid, int uid) {
3512 if (permission == null) {
3513 return PackageManager.PERMISSION_DENIED;
3514 }
3515 return checkComponentPermission(permission, pid, uid, -1, true);
3516 }
3517
Wale Ogunwale214f3482018-10-04 11:00:47 -07003518 public static int checkComponentPermission(String permission, int pid, int uid,
3519 int owningUid, boolean exported) {
3520 return ActivityManagerService.checkComponentPermission(
3521 permission, pid, uid, owningUid, exported);
3522 }
3523
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003524 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3525 if (getRecentTasks().isCallerRecents(callingUid)) {
3526 // Always allow the recents component to get tasks
3527 return true;
3528 }
3529
3530 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3531 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3532 if (!allowed) {
3533 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3534 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3535 // Temporary compatibility: some existing apps on the system image may
3536 // still be requesting the old permission and not switched to the new
3537 // one; if so, we'll still allow them full access. This means we need
3538 // to see if they are holding the old permission and are a system app.
3539 try {
3540 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3541 allowed = true;
3542 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3543 + " is using old GET_TASKS but privileged; allowing");
3544 }
3545 } catch (RemoteException e) {
3546 }
3547 }
3548 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3549 + " does not hold REAL_GET_TASKS; limiting output");
3550 }
3551 return allowed;
3552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3555 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3556 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3557 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003558 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 "enqueueAssistContext()");
3560
3561 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003562 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 if (activity == null) {
3564 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3565 return null;
3566 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003567 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003568 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3569 return null;
3570 }
3571 if (focused) {
3572 if (activityToken != null) {
3573 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3574 if (activity != caller) {
3575 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3576 + " is not current top " + activity);
3577 return null;
3578 }
3579 }
3580 } else {
3581 activity = ActivityRecord.forTokenLocked(activityToken);
3582 if (activity == null) {
3583 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3584 + " couldn't be found");
3585 return null;
3586 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003587 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3589 return null;
3590 }
3591 }
3592
3593 PendingAssistExtras pae;
3594 Bundle extras = new Bundle();
3595 if (args != null) {
3596 extras.putAll(args);
3597 }
3598 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600
3601 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3602 userHandle);
3603 pae.isHome = activity.isActivityTypeHome();
3604
3605 // Increment the sessionId if necessary
3606 if (newSessionId) {
3607 mViSessionId++;
3608 }
3609 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003610 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3611 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003613 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 } catch (RemoteException e) {
3615 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3616 return null;
3617 }
3618 return pae;
3619 }
3620 }
3621
3622 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3623 if (result != null) {
3624 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3625 }
3626 if (pae.hint != null) {
3627 pae.extras.putBoolean(pae.hint, true);
3628 }
3629 }
3630
3631 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3632 IAssistDataReceiver receiver;
3633 synchronized (mGlobalLock) {
3634 mPendingAssistExtras.remove(pae);
3635 receiver = pae.receiver;
3636 }
3637 if (receiver != null) {
3638 // Caller wants result sent back to them.
3639 Bundle sendBundle = new Bundle();
3640 // At least return the receiver extras
3641 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3642 try {
3643 pae.receiver.onHandleAssistData(sendBundle);
3644 } catch (RemoteException e) {
3645 }
3646 }
3647 }
3648
3649 public class PendingAssistExtras extends Binder implements Runnable {
3650 public final ActivityRecord activity;
3651 public boolean isHome;
3652 public final Bundle extras;
3653 public final Intent intent;
3654 public final String hint;
3655 public final IAssistDataReceiver receiver;
3656 public final int userHandle;
3657 public boolean haveResult = false;
3658 public Bundle result = null;
3659 public AssistStructure structure = null;
3660 public AssistContent content = null;
3661 public Bundle receiverExtras;
3662
3663 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3664 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3665 int _userHandle) {
3666 activity = _activity;
3667 extras = _extras;
3668 intent = _intent;
3669 hint = _hint;
3670 receiver = _receiver;
3671 receiverExtras = _receiverExtras;
3672 userHandle = _userHandle;
3673 }
3674
3675 @Override
3676 public void run() {
3677 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3678 synchronized (this) {
3679 haveResult = true;
3680 notifyAll();
3681 }
3682 pendingAssistExtrasTimedOut(this);
3683 }
3684 }
3685
3686 @Override
3687 public boolean isAssistDataAllowedOnCurrentActivity() {
3688 int userId;
3689 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003690 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3692 return false;
3693 }
3694
3695 final ActivityRecord activity = focusedStack.getTopActivity();
3696 if (activity == null) {
3697 return false;
3698 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003699 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003700 }
3701 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3702 }
3703
3704 @Override
3705 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3706 long ident = Binder.clearCallingIdentity();
3707 try {
3708 synchronized (mGlobalLock) {
3709 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003710 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 if (top != caller) {
3712 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3713 + " is not current top " + top);
3714 return false;
3715 }
3716 if (!top.nowVisible) {
3717 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3718 + " is not visible");
3719 return false;
3720 }
3721 }
3722 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3723 token);
3724 } finally {
3725 Binder.restoreCallingIdentity(ident);
3726 }
3727 }
3728
3729 @Override
3730 public boolean isRootVoiceInteraction(IBinder token) {
3731 synchronized (mGlobalLock) {
3732 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3733 if (r == null) {
3734 return false;
3735 }
3736 return r.rootVoiceInteraction;
3737 }
3738 }
3739
Wale Ogunwalef6733932018-06-27 05:14:34 -07003740 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3741 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3742 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3743 if (activityToCallback == null) return;
3744 activityToCallback.setVoiceSessionLocked(voiceSession);
3745
3746 // Inform the activity
3747 try {
3748 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3749 voiceInteractor);
3750 long token = Binder.clearCallingIdentity();
3751 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003752 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003753 } finally {
3754 Binder.restoreCallingIdentity(token);
3755 }
3756 // TODO: VI Should we cache the activity so that it's easier to find later
3757 // rather than scan through all the stacks and activities?
3758 } catch (RemoteException re) {
3759 activityToCallback.clearVoiceSessionLocked();
3760 // TODO: VI Should this terminate the voice session?
3761 }
3762 }
3763
3764 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3765 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3766 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3767 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3768 boolean wasRunningVoice = mRunningVoice != null;
3769 mRunningVoice = session;
3770 if (!wasRunningVoice) {
3771 mVoiceWakeLock.acquire();
3772 updateSleepIfNeededLocked();
3773 }
3774 }
3775 }
3776
3777 void finishRunningVoiceLocked() {
3778 if (mRunningVoice != null) {
3779 mRunningVoice = null;
3780 mVoiceWakeLock.release();
3781 updateSleepIfNeededLocked();
3782 }
3783 }
3784
3785 @Override
3786 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3787 synchronized (mGlobalLock) {
3788 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3789 if (keepAwake) {
3790 mVoiceWakeLock.acquire();
3791 } else {
3792 mVoiceWakeLock.release();
3793 }
3794 }
3795 }
3796 }
3797
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003798 @Override
3799 public ComponentName getActivityClassForToken(IBinder token) {
3800 synchronized (mGlobalLock) {
3801 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3802 if (r == null) {
3803 return null;
3804 }
3805 return r.intent.getComponent();
3806 }
3807 }
3808
3809 @Override
3810 public String getPackageForToken(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3813 if (r == null) {
3814 return null;
3815 }
3816 return r.packageName;
3817 }
3818 }
3819
3820 @Override
3821 public void showLockTaskEscapeMessage(IBinder token) {
3822 synchronized (mGlobalLock) {
3823 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3824 if (r == null) {
3825 return;
3826 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003827 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 }
3829 }
3830
3831 @Override
3832 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003833 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 final long token = Binder.clearCallingIdentity();
3835 try {
3836 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003837 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839 } finally {
3840 Binder.restoreCallingIdentity(token);
3841 }
3842 }
3843
3844 /**
3845 * Try to place task to provided position. The final position might be different depending on
3846 * current user and stacks state. The task will be moved to target stack if it's currently in
3847 * different stack.
3848 */
3849 @Override
3850 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003851 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 synchronized (mGlobalLock) {
3853 long ident = Binder.clearCallingIdentity();
3854 try {
3855 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3856 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003857 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 if (task == null) {
3859 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3860 + taskId);
3861 }
3862
Wale Ogunwaled32da472018-11-16 07:19:28 -08003863 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864
3865 if (stack == null) {
3866 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3867 + stackId);
3868 }
3869 if (!stack.isActivityTypeStandardOrUndefined()) {
3870 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3871 + " the position of task " + taskId + " in/to non-standard stack");
3872 }
3873
3874 // TODO: Have the callers of this API call a separate reparent method if that is
3875 // what they intended to do vs. having this method also do reparenting.
3876 if (task.getStack() == stack) {
3877 // Change position in current stack.
3878 stack.positionChildAt(task, position);
3879 } else {
3880 // Reparent to new stack.
3881 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3882 !DEFER_RESUME, "positionTaskInStack");
3883 }
3884 } finally {
3885 Binder.restoreCallingIdentity(ident);
3886 }
3887 }
3888 }
3889
3890 @Override
3891 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3892 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3893 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003894 + Arrays.toString(horizontalSizeConfiguration) + " "
3895 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 synchronized (mGlobalLock) {
3897 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3898 if (record == null) {
3899 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3900 + "found for: " + token);
3901 }
3902 record.setSizeConfigurations(horizontalSizeConfiguration,
3903 verticalSizeConfigurations, smallestSizeConfigurations);
3904 }
3905 }
3906
3907 /**
3908 * Dismisses split-screen multi-window mode.
3909 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3910 */
3911 @Override
3912 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003913 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003914 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3915 final long ident = Binder.clearCallingIdentity();
3916 try {
3917 synchronized (mGlobalLock) {
3918 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003919 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 if (stack == null) {
3921 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3922 return;
3923 }
3924
3925 if (toTop) {
3926 // Caller wants the current split-screen primary stack to be the top stack after
3927 // it goes fullscreen, so move it to the front.
3928 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003929 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003931 // stack after it goes fullscreen, so we move the focus to the top-most
3932 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3934 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3935 if (otherStack != null) {
3936 otherStack.moveToFront("dismissSplitScreenMode_other");
3937 }
3938 }
3939
Evan Rosky10475742018-09-05 19:02:48 -07003940 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 }
3942 } finally {
3943 Binder.restoreCallingIdentity(ident);
3944 }
3945 }
3946
3947 /**
3948 * Dismisses Pip
3949 * @param animate True if the dismissal should be animated.
3950 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3951 * default animation duration should be used.
3952 */
3953 @Override
3954 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003955 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 final long ident = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003959 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003960 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 if (stack == null) {
3962 Slog.w(TAG, "dismissPip: pinned stack not found.");
3963 return;
3964 }
3965 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3966 throw new IllegalArgumentException("Stack: " + stack
3967 + " doesn't support animated resize.");
3968 }
3969 if (animate) {
3970 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3971 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3972 } else {
3973 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3974 }
3975 }
3976 } finally {
3977 Binder.restoreCallingIdentity(ident);
3978 }
3979 }
3980
3981 @Override
3982 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 synchronized (mGlobalLock) {
3985 mSuppressResizeConfigChanges = suppress;
3986 }
3987 }
3988
3989 /**
3990 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3991 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3992 * activity and clearing the task at the same time.
3993 */
3994 @Override
3995 // TODO: API should just be about changing windowing modes...
3996 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003997 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 "moveTasksToFullscreenStack()");
3999 synchronized (mGlobalLock) {
4000 final long origId = Binder.clearCallingIdentity();
4001 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004002 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 if (stack != null){
4004 if (!stack.isActivityTypeStandardOrUndefined()) {
4005 throw new IllegalArgumentException(
4006 "You can't move tasks from non-standard stacks.");
4007 }
4008 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4009 }
4010 } finally {
4011 Binder.restoreCallingIdentity(origId);
4012 }
4013 }
4014 }
4015
4016 /**
4017 * Moves the top activity in the input stackId to the pinned stack.
4018 *
4019 * @param stackId Id of stack to move the top activity to pinned stack.
4020 * @param bounds Bounds to use for pinned stack.
4021 *
4022 * @return True if the top activity of the input stack was successfully moved to the pinned
4023 * stack.
4024 */
4025 @Override
4026 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 "moveTopActivityToPinnedStack()");
4029 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4032 + "Device doesn't support picture-in-picture mode");
4033 }
4034
4035 long ident = Binder.clearCallingIdentity();
4036 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004037 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 } finally {
4039 Binder.restoreCallingIdentity(ident);
4040 }
4041 }
4042 }
4043
4044 @Override
4045 public boolean isInMultiWindowMode(IBinder token) {
4046 final long origId = Binder.clearCallingIdentity();
4047 try {
4048 synchronized (mGlobalLock) {
4049 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4050 if (r == null) {
4051 return false;
4052 }
4053 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4054 return r.inMultiWindowMode();
4055 }
4056 } finally {
4057 Binder.restoreCallingIdentity(origId);
4058 }
4059 }
4060
4061 @Override
4062 public boolean isInPictureInPictureMode(IBinder token) {
4063 final long origId = Binder.clearCallingIdentity();
4064 try {
4065 synchronized (mGlobalLock) {
4066 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4067 }
4068 } finally {
4069 Binder.restoreCallingIdentity(origId);
4070 }
4071 }
4072
4073 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004074 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4075 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 return false;
4077 }
4078
4079 // If we are animating to fullscreen then we have already dispatched the PIP mode
4080 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004081 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4082 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 }
4084
4085 @Override
4086 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4087 final long origId = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4091 "enterPictureInPictureMode", token, params);
4092
4093 // If the activity is already in picture in picture mode, then just return early
4094 if (isInPictureInPictureMode(r)) {
4095 return true;
4096 }
4097
4098 // Activity supports picture-in-picture, now check that we can enter PiP at this
4099 // point, if it is
4100 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4101 false /* beforeStopping */)) {
4102 return false;
4103 }
4104
4105 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 synchronized (mGlobalLock) {
4107 // Only update the saved args from the args that are set
4108 r.pictureInPictureArgs.copyOnlySet(params);
4109 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4110 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4111 // Adjust the source bounds by the insets for the transition down
4112 final Rect sourceBounds = new Rect(
4113 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004114 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004116 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004117 stack.setPictureInPictureAspectRatio(aspectRatio);
4118 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004119 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4120 r.info.applicationInfo.uid, r.shortComponentName,
4121 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 logPictureInPictureArgs(params);
4123 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 };
4125
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 // If the keyguard is showing or occluded, then try and dismiss it before
4128 // entering picture-in-picture (this will prompt the user to authenticate if the
4129 // device is currently locked).
4130 dismissKeyguard(token, new KeyguardDismissCallback() {
4131 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004132 public void onDismissSucceeded() {
4133 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 }
4135 }, null /* message */);
4136 } else {
4137 // Enter picture in picture immediately otherwise
4138 enterPipRunnable.run();
4139 }
4140 return true;
4141 }
4142 } finally {
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146
4147 @Override
4148 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4149 final long origId = Binder.clearCallingIdentity();
4150 try {
4151 synchronized (mGlobalLock) {
4152 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4153 "setPictureInPictureParams", token, params);
4154
4155 // Only update the saved args from the args that are set
4156 r.pictureInPictureArgs.copyOnlySet(params);
4157 if (r.inPinnedWindowingMode()) {
4158 // If the activity is already in picture-in-picture, update the pinned stack now
4159 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4160 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004161 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 if (!stack.isAnimatingBoundsToFullscreen()) {
4163 stack.setPictureInPictureAspectRatio(
4164 r.pictureInPictureArgs.getAspectRatio());
4165 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4166 }
4167 }
4168 logPictureInPictureArgs(params);
4169 }
4170 } finally {
4171 Binder.restoreCallingIdentity(origId);
4172 }
4173 }
4174
4175 @Override
4176 public int getMaxNumPictureInPictureActions(IBinder token) {
4177 // Currently, this is a static constant, but later, we may change this to be dependent on
4178 // the context of the activity
4179 return 3;
4180 }
4181
4182 private void logPictureInPictureArgs(PictureInPictureParams params) {
4183 if (params.hasSetActions()) {
4184 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4185 params.getActions().size());
4186 }
4187 if (params.hasSetAspectRatio()) {
4188 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4189 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4190 MetricsLogger.action(lm);
4191 }
4192 }
4193
4194 /**
4195 * Checks the state of the system and the activity associated with the given {@param token} to
4196 * verify that picture-in-picture is supported for that activity.
4197 *
4198 * @return the activity record for the given {@param token} if all the checks pass.
4199 */
4200 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4201 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004202 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 throw new IllegalStateException(caller
4204 + ": Device doesn't support picture-in-picture mode.");
4205 }
4206
4207 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4208 if (r == null) {
4209 throw new IllegalStateException(caller
4210 + ": Can't find activity for token=" + token);
4211 }
4212
4213 if (!r.supportsPictureInPicture()) {
4214 throw new IllegalStateException(caller
4215 + ": Current activity does not support picture-in-picture.");
4216 }
4217
4218 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004219 && !mWindowManager.isValidPictureInPictureAspectRatio(
4220 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 final float minAspectRatio = mContext.getResources().getFloat(
4222 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4223 final float maxAspectRatio = mContext.getResources().getFloat(
4224 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4225 throw new IllegalArgumentException(String.format(caller
4226 + ": Aspect ratio is too extreme (must be between %f and %f).",
4227 minAspectRatio, maxAspectRatio));
4228 }
4229
4230 // Truncate the number of actions if necessary
4231 params.truncateActions(getMaxNumPictureInPictureActions(token));
4232
4233 return r;
4234 }
4235
4236 @Override
4237 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004238 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 synchronized (mGlobalLock) {
4240 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4241 if (r == null) {
4242 throw new IllegalArgumentException("Activity does not exist; token="
4243 + activityToken);
4244 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004245 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 }
4247 }
4248
4249 @Override
4250 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4251 Rect tempDockedTaskInsetBounds,
4252 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 long ident = Binder.clearCallingIdentity();
4255 try {
4256 synchronized (mGlobalLock) {
4257 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4258 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4259 PRESERVE_WINDOWS);
4260 }
4261 } finally {
4262 Binder.restoreCallingIdentity(ident);
4263 }
4264 }
4265
4266 @Override
4267 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 final long ident = Binder.clearCallingIdentity();
4270 try {
4271 synchronized (mGlobalLock) {
4272 mStackSupervisor.setSplitScreenResizing(resizing);
4273 }
4274 } finally {
4275 Binder.restoreCallingIdentity(ident);
4276 }
4277 }
4278
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004279 /**
4280 * Check that we have the features required for VR-related API calls, and throw an exception if
4281 * not.
4282 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004283 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 if (!mContext.getPackageManager().hasSystemFeature(
4285 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4286 throw new UnsupportedOperationException("VR mode not supported on this device!");
4287 }
4288 }
4289
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290 @Override
4291 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293
4294 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4295
4296 ActivityRecord r;
4297 synchronized (mGlobalLock) {
4298 r = ActivityRecord.isInStackLocked(token);
4299 }
4300
4301 if (r == null) {
4302 throw new IllegalArgumentException();
4303 }
4304
4305 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004306 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 VrManagerInternal.NO_ERROR) {
4308 return err;
4309 }
4310
4311 // Clear the binder calling uid since this path may call moveToTask().
4312 final long callingId = Binder.clearCallingIdentity();
4313 try {
4314 synchronized (mGlobalLock) {
4315 r.requestedVrComponent = (enabled) ? packageName : null;
4316
4317 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004318 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004319 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 }
4321 return 0;
4322 }
4323 } finally {
4324 Binder.restoreCallingIdentity(callingId);
4325 }
4326 }
4327
4328 @Override
4329 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4330 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4331 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004332 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4334 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4335 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004336 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 || activity.voiceSession != null) {
4338 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4339 return;
4340 }
4341 if (activity.pendingVoiceInteractionStart) {
4342 Slog.w(TAG, "Pending start of voice interaction already.");
4343 return;
4344 }
4345 activity.pendingVoiceInteractionStart = true;
4346 }
4347 LocalServices.getService(VoiceInteractionManagerInternal.class)
4348 .startLocalVoiceInteraction(callingActivity, options);
4349 }
4350
4351 @Override
4352 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4353 LocalServices.getService(VoiceInteractionManagerInternal.class)
4354 .stopLocalVoiceInteraction(callingActivity);
4355 }
4356
4357 @Override
4358 public boolean supportsLocalVoiceInteraction() {
4359 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4360 .supportsLocalVoiceInteraction();
4361 }
4362
4363 /** Notifies all listeners when the pinned stack animation starts. */
4364 @Override
4365 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004366 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368
4369 /** Notifies all listeners when the pinned stack animation ends. */
4370 @Override
4371 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374
4375 @Override
4376 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 final long ident = Binder.clearCallingIdentity();
4379 try {
4380 synchronized (mGlobalLock) {
4381 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4382 }
4383 } finally {
4384 Binder.restoreCallingIdentity(ident);
4385 }
4386 }
4387
4388 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391
4392 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 }
4397
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004399 final Message msg = PooledLambda.obtainMessage(
4400 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4401 DEFAULT_DISPLAY);
4402 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 }
4404
4405 final long origId = Binder.clearCallingIdentity();
4406 try {
4407 if (values != null) {
4408 Settings.System.clearConfiguration(values);
4409 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004410 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 UserHandle.USER_NULL, false /* deferResume */,
4412 mTmpUpdateConfigurationResult);
4413 return mTmpUpdateConfigurationResult.changes != 0;
4414 } finally {
4415 Binder.restoreCallingIdentity(origId);
4416 }
4417 }
4418 }
4419
4420 @Override
4421 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4422 CharSequence message) {
4423 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4426 }
4427 final long callingId = Binder.clearCallingIdentity();
4428 try {
4429 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004430 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 }
4432 } finally {
4433 Binder.restoreCallingIdentity(callingId);
4434 }
4435 }
4436
4437 @Override
4438 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 "cancelTaskWindowTransition()");
4441 final long ident = Binder.clearCallingIdentity();
4442 try {
4443 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004444 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 MATCH_TASK_IN_STACKS_ONLY);
4446 if (task == null) {
4447 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4448 return;
4449 }
4450 task.cancelWindowTransition();
4451 }
4452 } finally {
4453 Binder.restoreCallingIdentity(ident);
4454 }
4455 }
4456
4457 @Override
4458 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 final long ident = Binder.clearCallingIdentity();
4461 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004462 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 } finally {
4464 Binder.restoreCallingIdentity(ident);
4465 }
4466 }
4467
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004468 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4469 boolean restoreFromDisk) {
4470 final TaskRecord task;
4471 synchronized (mGlobalLock) {
4472 task = mRootActivityContainer.anyTaskForId(taskId,
4473 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4474 if (task == null) {
4475 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4476 return null;
4477 }
4478 }
4479 // Don't call this while holding the lock as this operation might hit the disk.
4480 return task.getSnapshot(reducedResolution, restoreFromDisk);
4481 }
4482
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 @Override
4484 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4485 synchronized (mGlobalLock) {
4486 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4487 if (r == null) {
4488 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4489 + token);
4490 return;
4491 }
4492 final long origId = Binder.clearCallingIdentity();
4493 try {
4494 r.setDisablePreviewScreenshots(disable);
4495 } finally {
4496 Binder.restoreCallingIdentity(origId);
4497 }
4498 }
4499 }
4500
4501 /** Return the user id of the last resumed activity. */
4502 @Override
4503 public @UserIdInt
4504 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004505 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4507 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004508 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004509 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004511 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004512 }
4513 }
4514
4515 @Override
4516 public void updateLockTaskFeatures(int userId, int flags) {
4517 final int callingUid = Binder.getCallingUid();
4518 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 "updateLockTaskFeatures()");
4521 }
4522 synchronized (mGlobalLock) {
4523 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4524 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004525 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 }
4527 }
4528
4529 @Override
4530 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4531 synchronized (mGlobalLock) {
4532 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4533 if (r == null) {
4534 return;
4535 }
4536 final long origId = Binder.clearCallingIdentity();
4537 try {
4538 r.setShowWhenLocked(showWhenLocked);
4539 } finally {
4540 Binder.restoreCallingIdentity(origId);
4541 }
4542 }
4543 }
4544
4545 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004546 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4547 synchronized (mGlobalLock) {
4548 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4549 if (r == null) {
4550 return;
4551 }
4552 final long origId = Binder.clearCallingIdentity();
4553 try {
4554 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4555 } finally {
4556 Binder.restoreCallingIdentity(origId);
4557 }
4558 }
4559 }
4560
4561 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004562 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4563 synchronized (mGlobalLock) {
4564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4565 if (r == null) {
4566 return;
4567 }
4568 final long origId = Binder.clearCallingIdentity();
4569 try {
4570 r.setTurnScreenOn(turnScreenOn);
4571 } finally {
4572 Binder.restoreCallingIdentity(origId);
4573 }
4574 }
4575 }
4576
4577 @Override
4578 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004579 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004581 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 synchronized (mGlobalLock) {
4583 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4584 if (r == null) {
4585 return;
4586 }
4587 final long origId = Binder.clearCallingIdentity();
4588 try {
4589 r.registerRemoteAnimations(definition);
4590 } finally {
4591 Binder.restoreCallingIdentity(origId);
4592 }
4593 }
4594 }
4595
4596 @Override
4597 public void registerRemoteAnimationForNextActivityStart(String packageName,
4598 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004599 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004601 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004602 synchronized (mGlobalLock) {
4603 final long origId = Binder.clearCallingIdentity();
4604 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004605 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 packageName, adapter);
4607 } finally {
4608 Binder.restoreCallingIdentity(origId);
4609 }
4610 }
4611 }
4612
Evan Rosky966759f2019-01-15 10:33:58 -08004613 @Override
4614 public void registerRemoteAnimationsForDisplay(int displayId,
4615 RemoteAnimationDefinition definition) {
4616 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4617 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004618 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004619 synchronized (mGlobalLock) {
4620 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4621 if (display == null) {
4622 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4623 return;
4624 }
4625 final long origId = Binder.clearCallingIdentity();
4626 try {
4627 display.mDisplayContent.registerRemoteAnimations(definition);
4628 } finally {
4629 Binder.restoreCallingIdentity(origId);
4630 }
4631 }
4632 }
4633
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004634 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4635 @Override
4636 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4637 synchronized (mGlobalLock) {
4638 final long origId = Binder.clearCallingIdentity();
4639 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004640 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004641 } finally {
4642 Binder.restoreCallingIdentity(origId);
4643 }
4644 }
4645 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004646
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004647 @Override
4648 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004651 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004652 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004653 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004654 }
4655 }
4656
4657 @Override
4658 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 != PERMISSION_GRANTED) {
4661 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4662 + Binder.getCallingPid()
4663 + ", uid=" + Binder.getCallingUid()
4664 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4665 Slog.w(TAG, msg);
4666 throw new SecurityException(msg);
4667 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004668 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004669 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004670 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004671 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004672 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004673 }
4674 }
4675
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004676 @Override
4677 public void stopAppSwitches() {
4678 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4679 synchronized (mGlobalLock) {
4680 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004681 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004682 mDidAppSwitch = false;
4683 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4684 }
4685 }
4686
4687 @Override
4688 public void resumeAppSwitches() {
4689 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4690 synchronized (mGlobalLock) {
4691 // Note that we don't execute any pending app switches... we will
4692 // let those wait until either the timeout, or the next start
4693 // activity request.
4694 mAppSwitchesAllowedTime = 0;
4695 }
4696 }
4697
Ricky Wai906af482019-06-03 17:25:28 +01004698 long getLastStopAppSwitchesTime() {
4699 return mLastStopAppSwitchesTime;
4700 }
4701
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004702 void onStartActivitySetDidAppSwitch() {
4703 if (mDidAppSwitch) {
4704 // This is the second allowed switch since we stopped switches, so now just generally
4705 // allow switches. Use case:
4706 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4707 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4708 // anyone to switch again).
4709 mAppSwitchesAllowedTime = 0;
4710 } else {
4711 mDidAppSwitch = true;
4712 }
4713 }
4714
4715 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 boolean shouldDisableNonVrUiLocked() {
4717 return mVrController.shouldDisableNonVrUiLocked();
4718 }
4719
Wale Ogunwale53783742018-09-16 10:21:51 -07004720 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 // 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 +00004722 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004724 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4725 + " to main display for VR");
4726 mRootActivityContainer.moveStackToDisplay(
4727 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 }
4729 mH.post(() -> {
4730 if (!mVrController.onVrModeChanged(r)) {
4731 return;
4732 }
4733 synchronized (mGlobalLock) {
4734 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4735 mWindowManager.disableNonVrUi(disableNonVrUi);
4736 if (disableNonVrUi) {
4737 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4738 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004739 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 }
4741 }
4742 });
4743 }
4744
Wale Ogunwale53783742018-09-16 10:21:51 -07004745 @Override
4746 public int getPackageScreenCompatMode(String packageName) {
4747 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4748 synchronized (mGlobalLock) {
4749 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4750 }
4751 }
4752
4753 @Override
4754 public void setPackageScreenCompatMode(String packageName, int mode) {
4755 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4756 "setPackageScreenCompatMode");
4757 synchronized (mGlobalLock) {
4758 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4759 }
4760 }
4761
4762 @Override
4763 public boolean getPackageAskScreenCompat(String packageName) {
4764 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4765 synchronized (mGlobalLock) {
4766 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4767 }
4768 }
4769
4770 @Override
4771 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4772 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4773 "setPackageAskScreenCompat");
4774 synchronized (mGlobalLock) {
4775 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4776 }
4777 }
4778
Wale Ogunwale64258362018-10-16 15:13:37 -07004779 public static String relaunchReasonToString(int relaunchReason) {
4780 switch (relaunchReason) {
4781 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4782 return "window_resize";
4783 case RELAUNCH_REASON_FREE_RESIZE:
4784 return "free_resize";
4785 default:
4786 return null;
4787 }
4788 }
4789
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004790 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004791 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004792 }
4793
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 /** Pokes the task persister. */
4795 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4796 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4797 }
4798
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 boolean isKeyguardLocked() {
4800 return mKeyguardController.isKeyguardLocked();
4801 }
4802
Garfield Tan01548632018-11-27 10:15:48 -08004803 /**
4804 * Clears launch params for the given package.
4805 * @param packageNames the names of the packages of which the launch params are to be cleared
4806 */
4807 @Override
4808 public void clearLaunchParamsForPackages(List<String> packageNames) {
4809 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4810 "clearLaunchParamsForPackages");
4811 synchronized (mGlobalLock) {
4812 for (int i = 0; i < packageNames.size(); ++i) {
4813 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4814 }
4815 }
4816 }
4817
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004818 /**
4819 * Makes the display with the given id a single task instance display. I.e the display can only
4820 * contain one task.
4821 */
4822 @Override
4823 public void setDisplayToSingleTaskInstance(int displayId) {
4824 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4825 "setDisplayToSingleTaskInstance");
4826 final long origId = Binder.clearCallingIdentity();
4827 try {
4828 final ActivityDisplay display =
4829 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4830 if (display != null) {
4831 display.setDisplayToSingleTaskInstance();
4832 }
4833 } finally {
4834 Binder.restoreCallingIdentity(origId);
4835 }
4836 }
4837
Wale Ogunwale31913b52018-10-13 08:29:31 -07004838 void dumpLastANRLocked(PrintWriter pw) {
4839 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4840 if (mLastANRState == null) {
4841 pw.println(" <no ANR has occurred since boot>");
4842 } else {
4843 pw.println(mLastANRState);
4844 }
4845 }
4846
4847 void dumpLastANRTracesLocked(PrintWriter pw) {
4848 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4849
4850 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4851 if (ArrayUtils.isEmpty(files)) {
4852 pw.println(" <no ANR has occurred since boot>");
4853 return;
4854 }
4855 // Find the latest file.
4856 File latest = null;
4857 for (File f : files) {
4858 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4859 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004860 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004861 }
4862 pw.print("File: ");
4863 pw.print(latest.getName());
4864 pw.println();
4865 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4866 String line;
4867 while ((line = in.readLine()) != null) {
4868 pw.println(line);
4869 }
4870 } catch (IOException e) {
4871 pw.print("Unable to read: ");
4872 pw.print(e);
4873 pw.println();
4874 }
4875 }
4876
4877 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4878 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4879 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4880 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4881 }
4882
4883 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4884 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4885 pw.println(header);
4886
Wale Ogunwaled32da472018-11-16 07:19:28 -08004887 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004888 dumpPackage);
4889 boolean needSep = printedAnything;
4890
4891 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004892 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004893 " ResumedActivity: ");
4894 if (printed) {
4895 printedAnything = true;
4896 needSep = false;
4897 }
4898
4899 if (dumpPackage == null) {
4900 if (needSep) {
4901 pw.println();
4902 }
4903 printedAnything = true;
4904 mStackSupervisor.dump(pw, " ");
4905 }
4906
4907 if (!printedAnything) {
4908 pw.println(" (nothing)");
4909 }
4910 }
4911
4912 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004913 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004914 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004915 pw.println(" ");
4916 }
4917
4918 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4919 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4920 getActivityStartController().dump(pw, "", dumpPackage);
4921 }
4922
4923 /**
4924 * There are three things that cmd can be:
4925 * - a flattened component name that matches an existing activity
4926 * - the cmd arg isn't the flattened component name of an existing activity:
4927 * dump all activity whose component contains the cmd as a substring
4928 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004929 * <p>
4930 * The caller should not hold lock when calling this method because it will wait for the
4931 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004932 *
4933 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4934 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4935 */
4936 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4937 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4938 ArrayList<ActivityRecord> activities;
4939
4940 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004941 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 dumpFocusedStackOnly);
4943 }
4944
4945 if (activities.size() <= 0) {
4946 return false;
4947 }
4948
4949 String[] newArgs = new String[args.length - opti];
4950 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4951
4952 TaskRecord lastTask = null;
4953 boolean needSep = false;
4954 for (int i = activities.size() - 1; i >= 0; i--) {
4955 ActivityRecord r = activities.get(i);
4956 if (needSep) {
4957 pw.println();
4958 }
4959 needSep = true;
4960 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004961 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 if (lastTask != task) {
4963 lastTask = task;
4964 pw.print("TASK "); pw.print(lastTask.affinity);
4965 pw.print(" id="); pw.print(lastTask.taskId);
4966 pw.print(" userId="); pw.println(lastTask.userId);
4967 if (dumpAll) {
4968 lastTask.dump(pw, " ");
4969 }
4970 }
4971 }
4972 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4973 }
4974 return true;
4975 }
4976
4977 /**
4978 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4979 * there is a thread associated with the activity.
4980 */
4981 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4982 final ActivityRecord r, String[] args, boolean dumpAll) {
4983 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004984 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004985 synchronized (mGlobalLock) {
4986 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4987 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4988 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004989 if (r.hasProcess()) {
4990 pw.println(r.app.getPid());
4991 appThread = r.app.getThread();
4992 } else {
4993 pw.println("(not running)");
4994 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 if (dumpAll) {
4996 r.dump(pw, innerPrefix);
4997 }
4998 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004999 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 // flush anything that is already in the PrintWriter since the thread is going
5001 // to write to the file descriptor directly
5002 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005003 try (TransferPipe tp = new TransferPipe()) {
5004 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5005 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005006 } catch (IOException e) {
5007 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5008 } catch (RemoteException e) {
5009 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5010 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005011 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005012 }
5013
sanryhuang498e77e2018-12-06 14:57:01 +08005014 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5015 boolean testPssMode) {
5016 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5017 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5018 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005019 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005020 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5021 st.toString());
5022 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005023 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5024 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5025 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005026 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5027 testPssMode);
5028 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005029 }
5030
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005031 int getCurrentUserId() {
5032 return mAmInternal.getCurrentUserId();
5033 }
5034
5035 private void enforceNotIsolatedCaller(String caller) {
5036 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5037 throw new SecurityException("Isolated process not allowed to call " + caller);
5038 }
5039 }
5040
Wale Ogunwalef6733932018-06-27 05:14:34 -07005041 public Configuration getConfiguration() {
5042 Configuration ci;
5043 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005044 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005045 ci.userSetLocale = false;
5046 }
5047 return ci;
5048 }
5049
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005050 /**
5051 * Current global configuration information. Contains general settings for the entire system,
5052 * also corresponds to the merged configuration of the default display.
5053 */
5054 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005055 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005056 }
5057
5058 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5059 boolean initLocale) {
5060 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5061 }
5062
5063 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5064 boolean initLocale, boolean deferResume) {
5065 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5066 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5067 UserHandle.USER_NULL, deferResume);
5068 }
5069
Wale Ogunwale59507092018-10-29 09:00:30 -07005070 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 final long origId = Binder.clearCallingIdentity();
5072 try {
5073 synchronized (mGlobalLock) {
5074 updateConfigurationLocked(values, null, false, true, userId,
5075 false /* deferResume */);
5076 }
5077 } finally {
5078 Binder.restoreCallingIdentity(origId);
5079 }
5080 }
5081
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005082 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5083 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5084 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5085 deferResume, null /* result */);
5086 }
5087
5088 /**
5089 * Do either or both things: (1) change the current configuration, and (2)
5090 * make sure the given activity is running with the (now) current
5091 * configuration. Returns true if the activity has been left running, or
5092 * false if <var>starting</var> is being destroyed to match the new
5093 * configuration.
5094 *
5095 * @param userId is only used when persistent parameter is set to true to persist configuration
5096 * for that particular user
5097 */
5098 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5099 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5100 ActivityTaskManagerService.UpdateConfigurationResult result) {
5101 int changes = 0;
5102 boolean kept = true;
5103
5104 if (mWindowManager != null) {
5105 mWindowManager.deferSurfaceLayout();
5106 }
5107 try {
5108 if (values != null) {
5109 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5110 deferResume);
5111 }
5112
5113 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5114 } finally {
5115 if (mWindowManager != null) {
5116 mWindowManager.continueSurfaceLayout();
5117 }
5118 }
5119
5120 if (result != null) {
5121 result.changes = changes;
5122 result.activityRelaunched = !kept;
5123 }
5124 return kept;
5125 }
5126
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005127 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005128 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005130
5131 final ActivityDisplay defaultDisplay =
5132 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5133
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 mTempConfig.setTo(getGlobalConfiguration());
5135 final int changes = mTempConfig.updateFrom(values);
5136 if (changes == 0) {
5137 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5138 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5139 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5140 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005141 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142 return 0;
5143 }
5144
5145 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5146 "Updating global configuration to: " + values);
5147
5148 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5149 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5150 values.colorMode,
5151 values.densityDpi,
5152 values.fontScale,
5153 values.hardKeyboardHidden,
5154 values.keyboard,
5155 values.keyboardHidden,
5156 values.mcc,
5157 values.mnc,
5158 values.navigation,
5159 values.navigationHidden,
5160 values.orientation,
5161 values.screenHeightDp,
5162 values.screenLayout,
5163 values.screenWidthDp,
5164 values.smallestScreenWidthDp,
5165 values.touchscreen,
5166 values.uiMode);
5167
5168
5169 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5170 final LocaleList locales = values.getLocales();
5171 int bestLocaleIndex = 0;
5172 if (locales.size() > 1) {
5173 if (mSupportedSystemLocales == null) {
5174 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5175 }
5176 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5177 }
5178 SystemProperties.set("persist.sys.locale",
5179 locales.get(bestLocaleIndex).toLanguageTag());
5180 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005181
5182 final Message m = PooledLambda.obtainMessage(
5183 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5184 locales.get(bestLocaleIndex));
5185 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186 }
5187
Yunfan Chen75157d72018-07-27 14:47:21 +09005188 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189
5190 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005191 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005192
5193 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5194 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005195 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005198 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199
5200 AttributeCache ac = AttributeCache.instance();
5201 if (ac != null) {
5202 ac.updateConfiguration(mTempConfig);
5203 }
5204
5205 // Make sure all resources in our process are updated right now, so that anyone who is going
5206 // to retrieve resource values after we return will be sure to get the new ones. This is
5207 // especially important during boot, where the first config change needs to guarantee all
5208 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005209 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210
5211 // We need another copy of global config because we're scheduling some calls instead of
5212 // running them in place. We need to be sure that object we send will be handled unchanged.
5213 final Configuration configCopy = new Configuration(mTempConfig);
5214 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005215 final Message msg = PooledLambda.obtainMessage(
5216 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5217 this, userId, configCopy);
5218 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
5220
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005221 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5222 for (int i = pidMap.size() - 1; i >= 0; i--) {
5223 final int pid = pidMap.keyAt(i);
5224 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005225 if (DEBUG_CONFIGURATION) {
5226 Slog.v(TAG_CONFIGURATION, "Update process config of "
5227 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005229 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230 }
5231
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005232 final Message msg = PooledLambda.obtainMessage(
5233 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5234 mAmInternal, changes, initLocale);
5235 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236
5237 // Override configuration of the default display duplicates global config, so we need to
5238 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005239 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5240 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241
5242 return changes;
5243 }
5244
Wale Ogunwalef6733932018-06-27 05:14:34 -07005245 private void updateEventDispatchingLocked(boolean booted) {
5246 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5247 }
5248
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005249 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5250 final ContentResolver resolver = mContext.getContentResolver();
5251 Settings.System.putConfigurationForUser(resolver, config, userId);
5252 }
5253
5254 private void sendLocaleToMountDaemonMsg(Locale l) {
5255 try {
5256 IBinder service = ServiceManager.getService("mount");
5257 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5258 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5259 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5260 } catch (RemoteException e) {
5261 Log.e(TAG, "Error storing locale for decryption UI", e);
5262 }
5263 }
5264
Alison Cichowlas3e340502018-08-07 17:15:01 -04005265 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5266 mStartActivitySources.remove(permissionToken);
5267 mExpiredStartAsCallerTokens.add(permissionToken);
5268 }
5269
5270 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5271 mExpiredStartAsCallerTokens.remove(permissionToken);
5272 }
5273
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005274 boolean isActivityStartsLoggingEnabled() {
5275 return mAmInternal.isActivityStartsLoggingEnabled();
5276 }
5277
Michal Karpinski8596ded2018-11-14 14:43:48 +00005278 boolean isBackgroundActivityStartsEnabled() {
5279 return mAmInternal.isBackgroundActivityStartsEnabled();
5280 }
5281
Wale Ogunwalef6733932018-06-27 05:14:34 -07005282 void enableScreenAfterBoot(boolean booted) {
5283 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5284 SystemClock.uptimeMillis());
5285 mWindowManager.enableScreenAfterBoot();
5286
5287 synchronized (mGlobalLock) {
5288 updateEventDispatchingLocked(booted);
5289 }
5290 }
5291
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005292 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5293 if (r == null || !r.hasProcess()) {
5294 return KEY_DISPATCHING_TIMEOUT_MS;
5295 }
5296 return getInputDispatchingTimeoutLocked(r.app);
5297 }
5298
5299 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005300 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005301 }
5302
Wale Ogunwalef6733932018-06-27 05:14:34 -07005303 /**
5304 * Decide based on the configuration whether we should show the ANR,
5305 * crash, etc dialogs. The idea is that if there is no affordance to
5306 * press the on-screen buttons, or the user experience would be more
5307 * greatly impacted than the crash itself, we shouldn't show the dialog.
5308 *
5309 * A thought: SystemUI might also want to get told about this, the Power
5310 * dialog / global actions also might want different behaviors.
5311 */
5312 private void updateShouldShowDialogsLocked(Configuration config) {
5313 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5314 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5315 && config.navigation == Configuration.NAVIGATION_NONAV);
5316 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5317 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5318 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5319 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5320 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5321 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5322 HIDE_ERROR_DIALOGS, 0) != 0;
5323 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5324 }
5325
5326 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5327 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5328 FONT_SCALE, 1.0f, userId);
5329
5330 synchronized (this) {
5331 if (getGlobalConfiguration().fontScale == scaleFactor) {
5332 return;
5333 }
5334
5335 final Configuration configuration
5336 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5337 configuration.fontScale = scaleFactor;
5338 updatePersistentConfiguration(configuration, userId);
5339 }
5340 }
5341
5342 // Actually is sleeping or shutting down or whatever else in the future
5343 // is an inactive state.
5344 boolean isSleepingOrShuttingDownLocked() {
5345 return isSleepingLocked() || mShuttingDown;
5346 }
5347
5348 boolean isSleepingLocked() {
5349 return mSleeping;
5350 }
5351
Riddle Hsu16567132018-08-16 21:37:47 +08005352 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005354 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005355 if (task.isActivityTypeStandard()) {
5356 if (mCurAppTimeTracker != r.appTimeTracker) {
5357 // We are switching app tracking. Complete the current one.
5358 if (mCurAppTimeTracker != null) {
5359 mCurAppTimeTracker.stop();
5360 mH.obtainMessage(
5361 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005362 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005363 mCurAppTimeTracker = null;
5364 }
5365 if (r.appTimeTracker != null) {
5366 mCurAppTimeTracker = r.appTimeTracker;
5367 startTimeTrackingFocusedActivityLocked();
5368 }
5369 } else {
5370 startTimeTrackingFocusedActivityLocked();
5371 }
5372 } else {
5373 r.appTimeTracker = null;
5374 }
5375 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5376 // TODO: Probably not, because we don't want to resume voice on switching
5377 // back to this activity
5378 if (task.voiceInteractor != null) {
5379 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5380 } else {
5381 finishRunningVoiceLocked();
5382
5383 if (mLastResumedActivity != null) {
5384 final IVoiceInteractionSession session;
5385
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005386 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005387 if (lastResumedActivityTask != null
5388 && lastResumedActivityTask.voiceSession != null) {
5389 session = lastResumedActivityTask.voiceSession;
5390 } else {
5391 session = mLastResumedActivity.voiceSession;
5392 }
5393
5394 if (session != null) {
5395 // We had been in a voice interaction session, but now focused has
5396 // move to something different. Just finish the session, we can't
5397 // return to it and retain the proper state and synchronization with
5398 // the voice interaction service.
5399 finishVoiceTask(session);
5400 }
5401 }
5402 }
5403
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005404 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5405 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005406 }
5407 updateResumedAppTrace(r);
5408 mLastResumedActivity = r;
5409
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005410 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411
5412 applyUpdateLockStateLocked(r);
5413 applyUpdateVrModeLocked(r);
5414
5415 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005416 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005417 r == null ? "NULL" : r.shortComponentName,
5418 reason);
5419 }
5420
5421 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5422 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005423 final ActivityTaskManagerInternal.SleepToken token =
5424 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 updateSleepIfNeededLocked();
5426 return token;
5427 }
5428 }
5429
5430 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005431 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 final boolean wasSleeping = mSleeping;
5433 boolean updateOomAdj = false;
5434
5435 if (!shouldSleep) {
5436 // If wasSleeping is true, we need to wake up activity manager state from when
5437 // we started sleeping. In either case, we need to apply the sleep tokens, which
5438 // will wake up stacks or put them to sleep as appropriate.
5439 if (wasSleeping) {
5440 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005441 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5442 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 startTimeTrackingFocusedActivityLocked();
5444 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005445 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5447 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005448 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 if (wasSleeping) {
5450 updateOomAdj = true;
5451 }
5452 } else if (!mSleeping && shouldSleep) {
5453 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005454 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5455 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005456 if (mCurAppTimeTracker != null) {
5457 mCurAppTimeTracker.stop();
5458 }
5459 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005460 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 mStackSupervisor.goingToSleepLocked();
5462 updateResumedAppTrace(null /* resumed */);
5463 updateOomAdj = true;
5464 }
5465 if (updateOomAdj) {
5466 mH.post(mAmInternal::updateOomAdj);
5467 }
5468 }
5469
5470 void updateOomAdj() {
5471 mH.post(mAmInternal::updateOomAdj);
5472 }
5473
Wale Ogunwale53783742018-09-16 10:21:51 -07005474 void updateCpuStats() {
5475 mH.post(mAmInternal::updateCpuStats);
5476 }
5477
Hui Yu03d12402018-12-06 18:00:37 -08005478 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5479 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005480 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5481 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005482 mH.sendMessage(m);
5483 }
5484
Hui Yu03d12402018-12-06 18:00:37 -08005485 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005486 ComponentName taskRoot = null;
5487 final TaskRecord task = activity.getTaskRecord();
5488 if (task != null) {
5489 final ActivityRecord rootActivity = task.getRootActivity();
5490 if (rootActivity != null) {
5491 taskRoot = rootActivity.mActivityComponent;
5492 }
5493 }
5494
Hui Yu03d12402018-12-06 18:00:37 -08005495 final Message m = PooledLambda.obtainMessage(
5496 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005497 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005498 mH.sendMessage(m);
5499 }
5500
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005501 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5502 String hostingType) {
5503 try {
5504 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5505 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5506 + activity.processName);
5507 }
5508 // Post message to start process to avoid possible deadlock of calling into AMS with the
5509 // ATMS lock held.
5510 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5511 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5512 isTop, hostingType, activity.intent.getComponent());
5513 mH.sendMessage(m);
5514 } finally {
5515 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5516 }
5517 }
5518
Wale Ogunwale53783742018-09-16 10:21:51 -07005519 void setBooting(boolean booting) {
5520 mAmInternal.setBooting(booting);
5521 }
5522
5523 boolean isBooting() {
5524 return mAmInternal.isBooting();
5525 }
5526
5527 void setBooted(boolean booted) {
5528 mAmInternal.setBooted(booted);
5529 }
5530
5531 boolean isBooted() {
5532 return mAmInternal.isBooted();
5533 }
5534
5535 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5536 mH.post(() -> {
5537 if (finishBooting) {
5538 mAmInternal.finishBooting();
5539 }
5540 if (enableScreen) {
5541 mInternal.enableScreenAfterBoot(isBooted());
5542 }
5543 });
5544 }
5545
5546 void setHeavyWeightProcess(ActivityRecord root) {
5547 mHeavyWeightProcess = root.app;
5548 final Message m = PooledLambda.obtainMessage(
5549 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005550 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005551 mH.sendMessage(m);
5552 }
5553
5554 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5555 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5556 return;
5557 }
5558
5559 mHeavyWeightProcess = null;
5560 final Message m = PooledLambda.obtainMessage(
5561 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5562 proc.mUserId);
5563 mH.sendMessage(m);
5564 }
5565
5566 private void cancelHeavyWeightProcessNotification(int userId) {
5567 final INotificationManager inm = NotificationManager.getService();
5568 if (inm == null) {
5569 return;
5570 }
5571 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005572 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005573 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5574 } catch (RuntimeException e) {
5575 Slog.w(TAG, "Error canceling notification for service", e);
5576 } catch (RemoteException e) {
5577 }
5578
5579 }
5580
5581 private void postHeavyWeightProcessNotification(
5582 WindowProcessController proc, Intent intent, int userId) {
5583 if (proc == null) {
5584 return;
5585 }
5586
5587 final INotificationManager inm = NotificationManager.getService();
5588 if (inm == null) {
5589 return;
5590 }
5591
5592 try {
5593 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5594 String text = mContext.getString(R.string.heavy_weight_notification,
5595 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5596 Notification notification =
5597 new Notification.Builder(context,
5598 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5599 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5600 .setWhen(0)
5601 .setOngoing(true)
5602 .setTicker(text)
5603 .setColor(mContext.getColor(
5604 com.android.internal.R.color.system_notification_accent_color))
5605 .setContentTitle(text)
5606 .setContentText(
5607 mContext.getText(R.string.heavy_weight_notification_detail))
5608 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5609 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5610 new UserHandle(userId)))
5611 .build();
5612 try {
5613 inm.enqueueNotificationWithTag("android", "android", null,
5614 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5615 } catch (RuntimeException e) {
5616 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5617 } catch (RemoteException e) {
5618 }
5619 } catch (PackageManager.NameNotFoundException e) {
5620 Slog.w(TAG, "Unable to create context for heavy notification", e);
5621 }
5622
5623 }
5624
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005625 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5626 IBinder token, String resultWho, int requestCode, Intent[] intents,
5627 String[] resolvedTypes, int flags, Bundle bOptions) {
5628
5629 ActivityRecord activity = null;
5630 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5631 activity = ActivityRecord.isInStackLocked(token);
5632 if (activity == null) {
5633 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5634 return null;
5635 }
5636 if (activity.finishing) {
5637 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5638 return null;
5639 }
5640 }
5641
5642 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5643 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5644 bOptions);
5645 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5646 if (noCreate) {
5647 return rec;
5648 }
5649 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5650 if (activity.pendingResults == null) {
5651 activity.pendingResults = new HashSet<>();
5652 }
5653 activity.pendingResults.add(rec.ref);
5654 }
5655 return rec;
5656 }
5657
Andrii Kulian52d255c2018-07-13 11:32:19 -07005658 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005660 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005661 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5662 mCurAppTimeTracker.start(resumedActivity.packageName);
5663 }
5664 }
5665
5666 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5667 if (mTracedResumedActivity != null) {
5668 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5669 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5670 }
5671 if (resumed != null) {
5672 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5673 constructResumedTraceName(resumed.packageName), 0);
5674 }
5675 mTracedResumedActivity = resumed;
5676 }
5677
5678 private String constructResumedTraceName(String packageName) {
5679 return "focused app: " + packageName;
5680 }
5681
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005682 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005683 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005684 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005685 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005686 // mainStack is null during startup.
5687 if (mainStack != null) {
5688 if (changes != 0 && starting == null) {
5689 // If the configuration changed, and the caller is not already
5690 // in the process of starting an activity, then find the top
5691 // activity to check if its configuration needs to change.
5692 starting = mainStack.topRunningActivityLocked();
5693 }
5694
5695 if (starting != null) {
5696 kept = starting.ensureActivityConfiguration(changes,
5697 false /* preserveWindow */);
5698 // And we need to make sure at this point that all other activities
5699 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005700 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005701 !PRESERVE_WINDOWS);
5702 }
5703 }
5704
5705 return kept;
5706 }
5707
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005708 void scheduleAppGcsLocked() {
5709 mH.post(() -> mAmInternal.scheduleAppGcs());
5710 }
5711
Wale Ogunwale53783742018-09-16 10:21:51 -07005712 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5713 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5714 }
5715
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005716 /**
5717 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5718 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5719 * on demand.
5720 */
5721 IPackageManager getPackageManager() {
5722 return AppGlobals.getPackageManager();
5723 }
5724
5725 PackageManagerInternal getPackageManagerInternalLocked() {
5726 if (mPmInternal == null) {
5727 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5728 }
5729 return mPmInternal;
5730 }
5731
Hai Zhangf4da9be2019-05-01 13:46:06 +08005732 PermissionPolicyInternal getPermissionPolicyInternal() {
5733 if (mPermissionPolicyInternal == null) {
5734 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5735 }
5736 return mPermissionPolicyInternal;
5737 }
5738
Wale Ogunwale008163e2018-07-23 23:11:08 -07005739 AppWarnings getAppWarningsLocked() {
5740 return mAppWarnings;
5741 }
5742
Wale Ogunwale214f3482018-10-04 11:00:47 -07005743 Intent getHomeIntent() {
5744 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5745 intent.setComponent(mTopComponent);
5746 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5747 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5748 intent.addCategory(Intent.CATEGORY_HOME);
5749 }
5750 return intent;
5751 }
5752
Chilun2ef71f72018-11-16 17:57:15 +08005753 /**
5754 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5755 * activities.
5756 *
5757 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5758 * component defined in config_secondaryHomeComponent.
5759 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5760 */
5761 Intent getSecondaryHomeIntent(String preferredPackage) {
5762 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005763 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5764 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5765 if (preferredPackage == null || useSystemProvidedLauncher) {
5766 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005767 final String secondaryHomeComponent = mContext.getResources().getString(
5768 com.android.internal.R.string.config_secondaryHomeComponent);
5769 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5770 } else {
5771 intent.setPackage(preferredPackage);
5772 }
5773 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5774 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5775 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5776 }
5777 return intent;
5778 }
5779
Wale Ogunwale214f3482018-10-04 11:00:47 -07005780 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5781 if (info == null) return null;
5782 ApplicationInfo newInfo = new ApplicationInfo(info);
5783 newInfo.initForUser(userId);
5784 return newInfo;
5785 }
5786
Wale Ogunwale9c103022018-10-18 07:44:54 -07005787 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005788 if (uid == SYSTEM_UID) {
5789 // The system gets to run in any process. If there are multiple processes with the same
5790 // uid, just pick the first (this should never happen).
5791 final SparseArray<WindowProcessController> procs =
5792 mProcessNames.getMap().get(processName);
5793 if (procs == null) return null;
5794 final int procCount = procs.size();
5795 for (int i = 0; i < procCount; i++) {
5796 final int procUid = procs.keyAt(i);
5797 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5798 // Don't use an app process or different user process for system component.
5799 continue;
5800 }
5801 return procs.valueAt(i);
5802 }
5803 }
5804
5805 return mProcessNames.get(processName, uid);
5806 }
5807
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005808 WindowProcessController getProcessController(IApplicationThread thread) {
5809 if (thread == null) {
5810 return null;
5811 }
5812
5813 final IBinder threadBinder = thread.asBinder();
5814 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5815 for (int i = pmap.size()-1; i >= 0; i--) {
5816 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5817 for (int j = procs.size() - 1; j >= 0; j--) {
5818 final WindowProcessController proc = procs.valueAt(j);
5819 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5820 return proc;
5821 }
5822 }
5823 }
5824
5825 return null;
5826 }
5827
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005828 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005829 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005830 if (proc == null) return null;
5831 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5832 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005833 }
5834 return null;
5835 }
5836
Riddle Hsua0536432019-02-16 00:38:59 +08005837 int getUidState(int uid) {
5838 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005839 }
5840
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005841 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005842 // A uid is considered to be foreground if it has a visible non-toast window.
5843 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005844 }
5845
Ricky Wai96f5c352019-04-10 18:40:17 +01005846 boolean isDeviceOwner(int uid) {
5847 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005848 }
5849
Ricky Wai96f5c352019-04-10 18:40:17 +01005850 void setDeviceOwnerUid(int uid) {
5851 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005852 }
5853
Wale Ogunwale9de19442018-10-18 19:05:03 -07005854 /**
5855 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5856 * the whitelist
5857 */
5858 String getPendingTempWhitelistTagForUidLocked(int uid) {
5859 return mPendingTempWhitelist.get(uid);
5860 }
5861
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005862 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5863 if (true || Build.IS_USER) {
5864 return;
5865 }
5866
5867 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5868 StrictMode.allowThreadDiskWrites();
5869 try {
5870 File tracesDir = new File("/data/anr");
5871 File tracesFile = null;
5872 try {
5873 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5874
5875 StringBuilder sb = new StringBuilder();
5876 Time tobj = new Time();
5877 tobj.set(System.currentTimeMillis());
5878 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5879 sb.append(": ");
5880 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5881 sb.append(" since ");
5882 sb.append(msg);
5883 FileOutputStream fos = new FileOutputStream(tracesFile);
5884 fos.write(sb.toString().getBytes());
5885 if (app == null) {
5886 fos.write("\n*** No application process!".getBytes());
5887 }
5888 fos.close();
5889 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5890 } catch (IOException e) {
5891 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5892 return;
5893 }
5894
5895 if (app != null && app.getPid() > 0) {
5896 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5897 firstPids.add(app.getPid());
5898 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5899 }
5900
5901 File lastTracesFile = null;
5902 File curTracesFile = null;
5903 for (int i=9; i>=0; i--) {
5904 String name = String.format(Locale.US, "slow%02d.txt", i);
5905 curTracesFile = new File(tracesDir, name);
5906 if (curTracesFile.exists()) {
5907 if (lastTracesFile != null) {
5908 curTracesFile.renameTo(lastTracesFile);
5909 } else {
5910 curTracesFile.delete();
5911 }
5912 }
5913 lastTracesFile = curTracesFile;
5914 }
5915 tracesFile.renameTo(curTracesFile);
5916 } finally {
5917 StrictMode.setThreadPolicy(oldPolicy);
5918 }
5919 }
5920
Michal Karpinskida34cd42019-04-02 19:46:52 +01005921 boolean isAssociatedCompanionApp(int userId, int uid) {
5922 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5923 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005924 return false;
5925 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005926 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005927 }
5928
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005929 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005930 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005931
5932
Wale Ogunwale98875612018-10-12 07:53:02 -07005933 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5934 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005935
Riddle Hsud93a6c42018-11-29 21:50:06 +08005936 H(Looper looper) {
5937 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005938 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005939
5940 @Override
5941 public void handleMessage(Message msg) {
5942 switch (msg.what) {
5943 case REPORT_TIME_TRACKER_MSG: {
5944 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5945 tracker.deliverResult(mContext);
5946 } break;
5947 }
5948 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005949 }
5950
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005951 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005952 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005953
5954 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005955 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005956 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005957
5958 @Override
5959 public void handleMessage(Message msg) {
5960 switch (msg.what) {
5961 case DISMISS_DIALOG_UI_MSG: {
5962 final Dialog d = (Dialog) msg.obj;
5963 d.dismiss();
5964 break;
5965 }
5966 }
5967 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005968 }
5969
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005970 final class LocalService extends ActivityTaskManagerInternal {
5971 @Override
5972 public SleepToken acquireSleepToken(String tag, int displayId) {
5973 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005974 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005975 }
5976
5977 @Override
5978 public ComponentName getHomeActivityForUser(int userId) {
5979 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005980 final ActivityRecord homeActivity =
5981 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005982 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005983 }
5984 }
5985
5986 @Override
5987 public void onLocalVoiceInteractionStarted(IBinder activity,
5988 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5989 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005990 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005991 }
5992 }
5993
5994 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005995 public void notifyAppTransitionStarting(SparseIntArray reasons,
5996 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005997 synchronized (mGlobalLock) {
5998 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5999 reasons, timestamp);
6000 }
6001 }
6002
6003 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006004 public void notifySingleTaskDisplayDrawn(int displayId) {
6005 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6006 }
6007
6008 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 public void notifyAppTransitionFinished() {
6010 synchronized (mGlobalLock) {
6011 mStackSupervisor.notifyAppTransitionDone();
6012 }
6013 }
6014
6015 @Override
6016 public void notifyAppTransitionCancelled() {
6017 synchronized (mGlobalLock) {
6018 mStackSupervisor.notifyAppTransitionDone();
6019 }
6020 }
6021
6022 @Override
6023 public List<IBinder> getTopVisibleActivities() {
6024 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006025 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006026 }
6027 }
6028
6029 @Override
6030 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6031 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006032 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006033 }
6034 }
6035
6036 @Override
6037 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6038 Bundle bOptions) {
6039 Preconditions.checkNotNull(intents, "intents");
6040 final String[] resolvedTypes = new String[intents.length];
6041
6042 // UID of the package on user userId.
6043 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6044 // packageUid may not be initialized.
6045 int packageUid = 0;
6046 final long ident = Binder.clearCallingIdentity();
6047
6048 try {
6049 for (int i = 0; i < intents.length; i++) {
6050 resolvedTypes[i] =
6051 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6052 }
6053
6054 packageUid = AppGlobals.getPackageManager().getPackageUid(
6055 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6056 } catch (RemoteException e) {
6057 // Shouldn't happen.
6058 } finally {
6059 Binder.restoreCallingIdentity(ident);
6060 }
6061
Riddle Hsu591bf612019-02-14 17:55:31 +08006062 return getActivityStartController().startActivitiesInPackage(
6063 packageUid, packageName,
6064 intents, resolvedTypes, null /* resultTo */,
6065 SafeActivityOptions.fromBundle(bOptions), userId,
6066 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6067 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006068 }
6069
6070 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006071 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6072 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6073 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6074 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006075 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006076 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006077 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6078 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6079 userId, validateIncomingUser, originatingPendingIntent,
6080 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006081 }
6082 }
6083
6084 @Override
6085 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6086 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6087 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6088 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006089 PendingIntentRecord originatingPendingIntent,
6090 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006091 synchronized (mGlobalLock) {
6092 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6093 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6094 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006095 validateIncomingUser, originatingPendingIntent,
6096 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006097 }
6098 }
6099
6100 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6102 Intent intent, Bundle options, int userId) {
6103 return ActivityTaskManagerService.this.startActivityAsUser(
6104 caller, callerPacakge, intent,
6105 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6106 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6107 false /*validateIncomingUser*/);
6108 }
6109
6110 @Override
lumark588a3e82018-07-20 18:53:54 +08006111 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 synchronized (mGlobalLock) {
6113
6114 // We might change the visibilities here, so prepare an empty app transition which
6115 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006116 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006117 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006118 if (activityDisplay == null) {
6119 return;
6120 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006121 final DisplayContent dc = activityDisplay.mDisplayContent;
6122 final boolean wasTransitionSet =
6123 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006124 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006125 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006126 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006127 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128
6129 // If there was a transition set already we don't want to interfere with it as we
6130 // might be starting it too early.
6131 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006132 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 }
6134 }
6135 if (callback != null) {
6136 callback.run();
6137 }
6138 }
6139
6140 @Override
6141 public void notifyKeyguardTrustedChanged() {
6142 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006143 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006144 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 }
6146 }
6147 }
6148
6149 /**
6150 * Called after virtual display Id is updated by
6151 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6152 * {@param vrVr2dDisplayId}.
6153 */
6154 @Override
6155 public void setVr2dDisplayId(int vr2dDisplayId) {
6156 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6157 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006158 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 }
6160 }
6161
6162 @Override
6163 public void setFocusedActivity(IBinder token) {
6164 synchronized (mGlobalLock) {
6165 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6166 if (r == null) {
6167 throw new IllegalArgumentException(
6168 "setFocusedActivity: No activity record matching token=" + token);
6169 }
Louis Chang19443452018-10-09 12:10:21 +08006170 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006171 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 }
6173 }
6174 }
6175
6176 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006177 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006178 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
6180
6181 @Override
6182 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006183 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006184 }
6185
6186 @Override
6187 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006188 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
6190
6191 @Override
6192 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6193 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6194 }
6195
6196 @Override
6197 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006198 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006199 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006200
6201 @Override
6202 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6203 synchronized (mGlobalLock) {
6204 mActiveVoiceInteractionServiceComponent = component;
6205 }
6206 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006207
6208 @Override
6209 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6210 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6211 return;
6212 }
6213 synchronized (mGlobalLock) {
6214 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6215 if (types == null) {
6216 if (uid < 0) {
6217 return;
6218 }
6219 types = new ArrayMap<>();
6220 mAllowAppSwitchUids.put(userId, types);
6221 }
6222 if (uid < 0) {
6223 types.remove(type);
6224 } else {
6225 types.put(type, uid);
6226 }
6227 }
6228 }
6229
6230 @Override
6231 public void onUserStopped(int userId) {
6232 synchronized (mGlobalLock) {
6233 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6234 mAllowAppSwitchUids.remove(userId);
6235 }
6236 }
6237
6238 @Override
6239 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6240 synchronized (mGlobalLock) {
6241 return ActivityTaskManagerService.this.isGetTasksAllowed(
6242 caller, callingPid, callingUid);
6243 }
6244 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006245
Riddle Hsua0536432019-02-16 00:38:59 +08006246 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006247 @Override
6248 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006249 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006250 mProcessNames.put(proc.mName, proc.mUid, proc);
6251 }
6252 }
6253
Riddle Hsua0536432019-02-16 00:38:59 +08006254 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006255 @Override
6256 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006257 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006258 mProcessNames.remove(name, uid);
6259 }
6260 }
6261
Riddle Hsua0536432019-02-16 00:38:59 +08006262 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006263 @Override
6264 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006265 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006266 if (proc == mHomeProcess) {
6267 mHomeProcess = null;
6268 }
6269 if (proc == mPreviousProcess) {
6270 mPreviousProcess = null;
6271 }
6272 }
6273 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006274
Riddle Hsua0536432019-02-16 00:38:59 +08006275 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006276 @Override
6277 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006278 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006279 return mTopProcessState;
6280 }
6281 }
6282
Riddle Hsua0536432019-02-16 00:38:59 +08006283 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006284 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006285 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006286 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 return proc == mHeavyWeightProcess;
6288 }
6289 }
6290
Riddle Hsua0536432019-02-16 00:38:59 +08006291 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006292 @Override
6293 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006294 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006295 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6296 }
6297 }
6298
6299 @Override
6300 public void finishHeavyWeightApp() {
6301 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006302 if (mHeavyWeightProcess != null) {
6303 mHeavyWeightProcess.finishActivities();
6304 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006305 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6306 mHeavyWeightProcess);
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006311 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006314 return isSleepingLocked();
6315 }
6316 }
6317
6318 @Override
6319 public boolean isShuttingDown() {
6320 synchronized (mGlobalLock) {
6321 return mShuttingDown;
6322 }
6323 }
6324
6325 @Override
6326 public boolean shuttingDown(boolean booted, int timeout) {
6327 synchronized (mGlobalLock) {
6328 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006329 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006330 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006331 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006332 return mStackSupervisor.shutdownLocked(timeout);
6333 }
6334 }
6335
6336 @Override
6337 public void enableScreenAfterBoot(boolean booted) {
6338 synchronized (mGlobalLock) {
6339 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6340 SystemClock.uptimeMillis());
6341 mWindowManager.enableScreenAfterBoot();
6342 updateEventDispatchingLocked(booted);
6343 }
6344 }
6345
6346 @Override
6347 public boolean showStrictModeViolationDialog() {
6348 synchronized (mGlobalLock) {
6349 return mShowDialogs && !mSleeping && !mShuttingDown;
6350 }
6351 }
6352
6353 @Override
6354 public void showSystemReadyErrorDialogsIfNeeded() {
6355 synchronized (mGlobalLock) {
6356 try {
6357 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6358 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6359 + " data partition or your device will be unstable.");
6360 mUiHandler.post(() -> {
6361 if (mShowDialogs) {
6362 AlertDialog d = new BaseErrorDialog(mUiContext);
6363 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6364 d.setCancelable(false);
6365 d.setTitle(mUiContext.getText(R.string.android_system_label));
6366 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6367 d.setButton(DialogInterface.BUTTON_POSITIVE,
6368 mUiContext.getText(R.string.ok),
6369 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6370 d.show();
6371 }
6372 });
6373 }
6374 } catch (RemoteException e) {
6375 }
6376
6377 if (!Build.isBuildConsistent()) {
6378 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6379 mUiHandler.post(() -> {
6380 if (mShowDialogs) {
6381 AlertDialog d = new BaseErrorDialog(mUiContext);
6382 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6383 d.setCancelable(false);
6384 d.setTitle(mUiContext.getText(R.string.android_system_label));
6385 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6386 d.setButton(DialogInterface.BUTTON_POSITIVE,
6387 mUiContext.getText(R.string.ok),
6388 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6389 d.show();
6390 }
6391 });
6392 }
6393 }
6394 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006395
6396 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006397 public void onProcessMapped(int pid, WindowProcessController proc) {
6398 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006399 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006400 }
6401 }
6402
6403 @Override
6404 public void onProcessUnMapped(int pid) {
6405 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006406 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006407 }
6408 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006409
6410 @Override
6411 public void onPackageDataCleared(String name) {
6412 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006413 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006414 mAppWarnings.onPackageDataCleared(name);
6415 }
6416 }
6417
6418 @Override
6419 public void onPackageUninstalled(String name) {
6420 synchronized (mGlobalLock) {
6421 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006423 }
6424 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006425
6426 @Override
6427 public void onPackageAdded(String name, boolean replacing) {
6428 synchronized (mGlobalLock) {
6429 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6430 }
6431 }
6432
6433 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006434 public void onPackageReplaced(ApplicationInfo aInfo) {
6435 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006436 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006437 }
6438 }
6439
6440 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6442 synchronized (mGlobalLock) {
6443 return compatibilityInfoForPackageLocked(ai);
6444 }
6445 }
6446
Yunfan Chen75157d72018-07-27 14:47:21 +09006447 /**
6448 * Set the corresponding display information for the process global configuration. To be
6449 * called when we need to show IME on a different display.
6450 *
6451 * @param pid The process id associated with the IME window.
6452 * @param displayId The ID of the display showing the IME.
6453 */
6454 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006455 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006456 // Don't update process-level configuration for Multi-Client IME process since other
6457 // IMEs on other displays will also receive this configuration change due to IME
6458 // services use the same application config/context.
6459 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006460
Yunfan Chen75157d72018-07-27 14:47:21 +09006461 if (pid == MY_PID || pid < 0) {
6462 if (DEBUG_CONFIGURATION) {
6463 Slog.w(TAG,
6464 "Trying to update display configuration for system/invalid process.");
6465 }
6466 return;
6467 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006468 synchronized (mGlobalLock) {
6469 final ActivityDisplay activityDisplay =
6470 mRootActivityContainer.getActivityDisplay(displayId);
6471 if (activityDisplay == null) {
6472 // Call might come when display is not yet added or has been removed.
6473 if (DEBUG_CONFIGURATION) {
6474 Slog.w(TAG, "Trying to update display configuration for non-existing "
6475 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006476 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006477 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006478 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006479 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006480 if (process == null) {
6481 if (DEBUG_CONFIGURATION) {
6482 Slog.w(TAG, "Trying to update display configuration for invalid "
6483 + "process, pid=" + pid);
6484 }
6485 return;
6486 }
lumarkddc77fb2019-06-27 22:22:23 +08006487 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006488 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6489 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006490 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006491
6492 @Override
6493 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006494 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006495 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006496 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6497 if (r != null && r.getActivityStack() != null) {
6498 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6499 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006500 }
6501 }
6502 }
6503
6504 @Override
6505 public void clearPendingResultForActivity(IBinder activityToken,
6506 WeakReference<PendingIntentRecord> pir) {
6507 synchronized (mGlobalLock) {
6508 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6509 if (r != null && r.pendingResults != null) {
6510 r.pendingResults.remove(pir);
6511 }
6512 }
6513 }
6514
6515 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006516 public ActivityTokens getTopActivityForTask(int taskId) {
6517 synchronized (mGlobalLock) {
6518 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6519 if (taskRecord == null) {
6520 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6521 + " Requested task not found");
6522 return null;
6523 }
6524 final ActivityRecord activity = taskRecord.getTopActivity();
6525 if (activity == null) {
6526 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6527 + " Requested activity not found");
6528 return null;
6529 }
6530 if (!activity.attachedToProcess()) {
6531 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6532 + activity);
6533 return null;
6534 }
6535 return new ActivityTokens(activity.appToken, activity.assistToken,
6536 activity.app.getThread());
6537 }
6538 }
6539
6540 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006541 public IIntentSender getIntentSender(int type, String packageName,
6542 int callingUid, int userId, IBinder token, String resultWho,
6543 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6544 Bundle bOptions) {
6545 synchronized (mGlobalLock) {
6546 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6547 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6548 }
6549 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006550
6551 @Override
6552 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6553 synchronized (mGlobalLock) {
6554 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6555 if (r == null) {
6556 return null;
6557 }
6558 if (r.mServiceConnectionsHolder == null) {
6559 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6560 ActivityTaskManagerService.this, r);
6561 }
6562
6563 return r.mServiceConnectionsHolder;
6564 }
6565 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006566
6567 @Override
6568 public Intent getHomeIntent() {
6569 synchronized (mGlobalLock) {
6570 return ActivityTaskManagerService.this.getHomeIntent();
6571 }
6572 }
6573
6574 @Override
6575 public boolean startHomeActivity(int userId, String reason) {
6576 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006577 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006578 }
6579 }
6580
6581 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006582 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006583 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006584 synchronized (mGlobalLock) {
6585 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006586 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006587 }
Chilun8b1f1be2019-03-13 17:14:36 +08006588 }
6589
6590 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006591 public boolean startHomeOnAllDisplays(int userId, String reason) {
6592 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006593 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006594 }
6595 }
6596
Riddle Hsua0536432019-02-16 00:38:59 +08006597 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006598 @Override
6599 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006600 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006601 if (mFactoryTest == FACTORY_TEST_OFF) {
6602 return false;
6603 }
6604 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6605 && wpc.mName.equals(mTopComponent.getPackageName())) {
6606 return true;
6607 }
6608 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6609 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6610 }
6611 }
6612
6613 @Override
6614 public void updateTopComponentForFactoryTest() {
6615 synchronized (mGlobalLock) {
6616 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6617 return;
6618 }
6619 final ResolveInfo ri = mContext.getPackageManager()
6620 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6621 final CharSequence errorMsg;
6622 if (ri != null) {
6623 final ActivityInfo ai = ri.activityInfo;
6624 final ApplicationInfo app = ai.applicationInfo;
6625 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6626 mTopAction = Intent.ACTION_FACTORY_TEST;
6627 mTopData = null;
6628 mTopComponent = new ComponentName(app.packageName, ai.name);
6629 errorMsg = null;
6630 } else {
6631 errorMsg = mContext.getResources().getText(
6632 com.android.internal.R.string.factorytest_not_system);
6633 }
6634 } else {
6635 errorMsg = mContext.getResources().getText(
6636 com.android.internal.R.string.factorytest_no_action);
6637 }
6638 if (errorMsg == null) {
6639 return;
6640 }
6641
6642 mTopAction = null;
6643 mTopData = null;
6644 mTopComponent = null;
6645 mUiHandler.post(() -> {
6646 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6647 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006648 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006649 });
6650 }
6651 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652
Riddle Hsua0536432019-02-16 00:38:59 +08006653 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654 @Override
6655 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6656 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006657 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006658 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006659 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660
6661 wpc.clearRecentTasks();
6662 wpc.clearActivities();
6663
6664 if (wpc.isInstrumenting()) {
6665 finishInstrumentationCallback.run();
6666 }
6667
Jorim Jaggid0752812018-10-16 16:07:20 +02006668 if (!restarting && hasVisibleActivities) {
6669 mWindowManager.deferSurfaceLayout();
6670 try {
6671 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6672 // If there was nothing to resume, and we are not already restarting
6673 // this process, but there is a visible activity that is hosted by the
6674 // process...then make sure all visible activities are running, taking
6675 // care of restarting this process.
6676 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6677 !PRESERVE_WINDOWS);
6678 }
6679 } finally {
6680 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006681 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006682 }
6683 }
6684 }
6685
6686 @Override
6687 public void closeSystemDialogs(String reason) {
6688 enforceNotIsolatedCaller("closeSystemDialogs");
6689
6690 final int pid = Binder.getCallingPid();
6691 final int uid = Binder.getCallingUid();
6692 final long origId = Binder.clearCallingIdentity();
6693 try {
6694 synchronized (mGlobalLock) {
6695 // Only allow this from foreground processes, so that background
6696 // applications can't abuse it to prevent system UI from being shown.
6697 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006698 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 if (!proc.isPerceptible()) {
6700 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6701 + " from background process " + proc);
6702 return;
6703 }
6704 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006705 mWindowManager.closeSystemDialogs(reason);
6706
Wale Ogunwaled32da472018-11-16 07:19:28 -08006707 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006708 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006709 // Call into AM outside the synchronized block.
6710 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006711 } finally {
6712 Binder.restoreCallingIdentity(origId);
6713 }
6714 }
6715
6716 @Override
6717 public void cleanupDisabledPackageComponents(
6718 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6719 synchronized (mGlobalLock) {
6720 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006721 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006723 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006724 mStackSupervisor.scheduleIdleLocked();
6725 }
6726
6727 // Clean-up disabled tasks
6728 getRecentTasks().cleanupDisabledPackageTasksLocked(
6729 packageName, disabledClasses, userId);
6730 }
6731 }
6732
6733 @Override
6734 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6735 int userId) {
6736 synchronized (mGlobalLock) {
6737
6738 boolean didSomething =
6739 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006740 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006741 null, doit, evenPersistent, userId);
6742 return didSomething;
6743 }
6744 }
6745
6746 @Override
6747 public void resumeTopActivities(boolean scheduleIdle) {
6748 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006749 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 if (scheduleIdle) {
6751 mStackSupervisor.scheduleIdleLocked();
6752 }
6753 }
6754 }
6755
Riddle Hsua0536432019-02-16 00:38:59 +08006756 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757 @Override
6758 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006759 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6761 }
6762 }
6763
Riddle Hsua0536432019-02-16 00:38:59 +08006764 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 @Override
6766 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006767 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006768 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006769 }
6770 }
6771
6772 @Override
6773 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6774 try {
6775 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6776 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6777 }
6778 } catch (RemoteException ex) {
6779 throw new SecurityException("Fail to check is caller a privileged app", ex);
6780 }
6781
6782 synchronized (mGlobalLock) {
6783 final long ident = Binder.clearCallingIdentity();
6784 try {
6785 if (mAmInternal.shouldConfirmCredentials(userId)) {
6786 if (mKeyguardController.isKeyguardLocked()) {
6787 // Showing launcher to avoid user entering credential twice.
6788 startHomeActivity(currentUserId, "notifyLockedProfile");
6789 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006790 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 }
6792 } finally {
6793 Binder.restoreCallingIdentity(ident);
6794 }
6795 }
6796 }
6797
6798 @Override
6799 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6800 mAmInternal.enforceCallingPermission(
6801 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6802
6803 synchronized (mGlobalLock) {
6804 final long ident = Binder.clearCallingIdentity();
6805 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006806 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6807 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006808 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6810 UserHandle.CURRENT);
6811 } finally {
6812 Binder.restoreCallingIdentity(ident);
6813 }
6814 }
6815 }
6816
6817 @Override
6818 public void writeActivitiesToProto(ProtoOutputStream proto) {
6819 synchronized (mGlobalLock) {
6820 // The output proto of "activity --proto activities"
6821 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006822 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006823 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6824 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 }
6826 }
6827
6828 @Override
6829 public void saveANRState(String reason) {
6830 synchronized (mGlobalLock) {
6831 final StringWriter sw = new StringWriter();
6832 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6833 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6834 if (reason != null) {
6835 pw.println(" Reason: " + reason);
6836 }
6837 pw.println();
6838 getActivityStartController().dump(pw, " ", null);
6839 pw.println();
6840 pw.println("-------------------------------------------------------------------------------");
6841 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6842 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6843 "" /* header */);
6844 pw.println();
6845 pw.close();
6846
6847 mLastANRState = sw.toString();
6848 }
6849 }
6850
6851 @Override
6852 public void clearSavedANRState() {
6853 synchronized (mGlobalLock) {
6854 mLastANRState = null;
6855 }
6856 }
6857
6858 @Override
6859 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6860 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6861 synchronized (mGlobalLock) {
6862 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6863 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6864 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6865 dumpLastANRLocked(pw);
6866 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6867 dumpLastANRTracesLocked(pw);
6868 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6869 dumpActivityStarterLocked(pw, dumpPackage);
6870 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6871 dumpActivityContainersLocked(pw);
6872 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6873 if (getRecentTasks() != null) {
6874 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6875 }
6876 }
6877 }
6878 }
6879
6880 @Override
6881 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6882 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6883 int wakefulness) {
6884 synchronized (mGlobalLock) {
6885 if (mHomeProcess != null && (dumpPackage == null
6886 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6887 if (needSep) {
6888 pw.println();
6889 needSep = false;
6890 }
6891 pw.println(" mHomeProcess: " + mHomeProcess);
6892 }
6893 if (mPreviousProcess != null && (dumpPackage == null
6894 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6895 if (needSep) {
6896 pw.println();
6897 needSep = false;
6898 }
6899 pw.println(" mPreviousProcess: " + mPreviousProcess);
6900 }
6901 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6902 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6903 StringBuilder sb = new StringBuilder(128);
6904 sb.append(" mPreviousProcessVisibleTime: ");
6905 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6906 pw.println(sb);
6907 }
6908 if (mHeavyWeightProcess != null && (dumpPackage == null
6909 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6910 if (needSep) {
6911 pw.println();
6912 needSep = false;
6913 }
6914 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6915 }
6916 if (dumpPackage == null) {
6917 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006918 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 }
6920 if (dumpAll) {
6921 if (dumpPackage == null) {
6922 pw.println(" mConfigWillChange: "
6923 + getTopDisplayFocusedStack().mConfigWillChange);
6924 }
6925 if (mCompatModePackages.getPackages().size() > 0) {
6926 boolean printed = false;
6927 for (Map.Entry<String, Integer> entry
6928 : mCompatModePackages.getPackages().entrySet()) {
6929 String pkg = entry.getKey();
6930 int mode = entry.getValue();
6931 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6932 continue;
6933 }
6934 if (!printed) {
6935 pw.println(" mScreenCompatPackages:");
6936 printed = true;
6937 }
6938 pw.println(" " + pkg + ": " + mode);
6939 }
6940 }
6941 }
6942
6943 if (dumpPackage == null) {
6944 pw.println(" mWakefulness="
6945 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006946 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 if (mRunningVoice != null) {
6948 pw.println(" mRunningVoice=" + mRunningVoice);
6949 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6950 }
6951 pw.println(" mSleeping=" + mSleeping);
6952 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6953 pw.println(" mVrController=" + mVrController);
6954 }
6955 if (mCurAppTimeTracker != null) {
6956 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6957 }
6958 if (mAllowAppSwitchUids.size() > 0) {
6959 boolean printed = false;
6960 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6961 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6962 for (int j = 0; j < types.size(); j++) {
6963 if (dumpPackage == null ||
6964 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6965 if (needSep) {
6966 pw.println();
6967 needSep = false;
6968 }
6969 if (!printed) {
6970 pw.println(" mAllowAppSwitchUids:");
6971 printed = true;
6972 }
6973 pw.print(" User ");
6974 pw.print(mAllowAppSwitchUids.keyAt(i));
6975 pw.print(": Type ");
6976 pw.print(types.keyAt(j));
6977 pw.print(" = ");
6978 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6979 pw.println();
6980 }
6981 }
6982 }
6983 }
6984 if (dumpPackage == null) {
6985 if (mController != null) {
6986 pw.println(" mController=" + mController
6987 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6988 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006989 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6990 pw.println(" mLaunchingActivityWakeLock="
6991 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006992 }
6993
6994 return needSep;
6995 }
6996 }
6997
6998 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006999 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7000 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007001 synchronized (mGlobalLock) {
7002 if (dumpPackage == null) {
7003 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7004 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007005 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7006 if (mRunningVoice != null) {
7007 final long vrToken = proto.start(
7008 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7009 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7010 mRunningVoice.toString());
7011 mVoiceWakeLock.writeToProto(
7012 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7013 proto.end(vrToken);
7014 }
7015 mVrController.writeToProto(proto,
7016 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 if (mController != null) {
7018 final long token = proto.start(CONTROLLER);
7019 proto.write(CONTROLLER, mController.toString());
7020 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7021 proto.end(token);
7022 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007023 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7024 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7025 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 }
7027
7028 if (mHomeProcess != null && (dumpPackage == null
7029 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007030 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007031 }
7032
7033 if (mPreviousProcess != null && (dumpPackage == null
7034 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007035 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007036 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7037 }
7038
7039 if (mHeavyWeightProcess != null && (dumpPackage == null
7040 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007041 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007042 }
7043
7044 for (Map.Entry<String, Integer> entry
7045 : mCompatModePackages.getPackages().entrySet()) {
7046 String pkg = entry.getKey();
7047 int mode = entry.getValue();
7048 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7049 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7050 proto.write(PACKAGE, pkg);
7051 proto.write(MODE, mode);
7052 proto.end(compatToken);
7053 }
7054 }
7055
7056 if (mCurAppTimeTracker != null) {
7057 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7058 }
7059
7060 }
7061 }
7062
7063 @Override
7064 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7065 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7066 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007067 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7068 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007069 }
7070
7071 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007072 public void dumpForOom(PrintWriter pw) {
7073 synchronized (mGlobalLock) {
7074 pw.println(" mHomeProcess: " + mHomeProcess);
7075 pw.println(" mPreviousProcess: " + mPreviousProcess);
7076 if (mHeavyWeightProcess != null) {
7077 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7078 }
7079 }
7080 }
7081
7082 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 public boolean canGcNow() {
7084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007085 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 }
7087 }
7088
Riddle Hsua0536432019-02-16 00:38:59 +08007089 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 @Override
7091 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007092 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007093 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 return top != null ? top.app : null;
7095 }
7096 }
7097
Riddle Hsua0536432019-02-16 00:38:59 +08007098 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 @Override
7100 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007101 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007102 if (mRootActivityContainer != null) {
7103 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 }
7105 }
7106 }
7107
7108 @Override
7109 public void scheduleDestroyAllActivities(String reason) {
7110 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007111 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 }
7113 }
7114
7115 @Override
7116 public void removeUser(int userId) {
7117 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007118 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120 }
7121
7122 @Override
7123 public boolean switchUser(int userId, UserState userState) {
7124 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007125 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 }
7127 }
7128
7129 @Override
7130 public void onHandleAppCrash(WindowProcessController wpc) {
7131 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007132 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007133 }
7134 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007135
7136 @Override
7137 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7138 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007139 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007140 }
7141 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007142
Riddle Hsua0536432019-02-16 00:38:59 +08007143 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007144 @Override
7145 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007146 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007147 }
7148
Riddle Hsua0536432019-02-16 00:38:59 +08007149 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007150 @Override
7151 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007152 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007153 }
7154
Riddle Hsua0536432019-02-16 00:38:59 +08007155 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007156 @Override
7157 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007158 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007159 }
7160
Riddle Hsua0536432019-02-16 00:38:59 +08007161 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007162 @Override
7163 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007164 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007165 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007166
7167 @Override
7168 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007169 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007170 mPendingTempWhitelist.put(uid, tag);
7171 }
7172 }
7173
7174 @Override
7175 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007176 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007177 mPendingTempWhitelist.remove(uid);
7178 }
7179 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007180
7181 @Override
7182 public boolean handleAppCrashInActivityController(String processName, int pid,
7183 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7184 Runnable killCrashingAppCallback) {
7185 synchronized (mGlobalLock) {
7186 if (mController == null) {
7187 return false;
7188 }
7189
7190 try {
7191 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7192 stackTrace)) {
7193 killCrashingAppCallback.run();
7194 return true;
7195 }
7196 } catch (RemoteException e) {
7197 mController = null;
7198 Watchdog.getInstance().setActivityController(null);
7199 }
7200 return false;
7201 }
7202 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007203
7204 @Override
7205 public void removeRecentTasksByPackageName(String packageName, int userId) {
7206 synchronized (mGlobalLock) {
7207 mRecentTasks.removeTasksByPackageName(packageName, userId);
7208 }
7209 }
7210
7211 @Override
7212 public void cleanupRecentTasksForUser(int userId) {
7213 synchronized (mGlobalLock) {
7214 mRecentTasks.cleanupLocked(userId);
7215 }
7216 }
7217
7218 @Override
7219 public void loadRecentTasksForUser(int userId) {
7220 synchronized (mGlobalLock) {
7221 mRecentTasks.loadUserRecentsLocked(userId);
7222 }
7223 }
7224
7225 @Override
7226 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7227 synchronized (mGlobalLock) {
7228 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7229 }
7230 }
7231
7232 @Override
7233 public void flushRecentTasks() {
7234 mRecentTasks.flush();
7235 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007236
7237 @Override
7238 public WindowProcessController getHomeProcess() {
7239 synchronized (mGlobalLock) {
7240 return mHomeProcess;
7241 }
7242 }
7243
7244 @Override
7245 public WindowProcessController getPreviousProcess() {
7246 synchronized (mGlobalLock) {
7247 return mPreviousProcess;
7248 }
7249 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007250
7251 @Override
7252 public void clearLockedTasks(String reason) {
7253 synchronized (mGlobalLock) {
7254 getLockTaskController().clearLockedTasks(reason);
7255 }
7256 }
7257
7258 @Override
7259 public void updateUserConfiguration() {
7260 synchronized (mGlobalLock) {
7261 final Configuration configuration = new Configuration(getGlobalConfiguration());
7262 final int currentUserId = mAmInternal.getCurrentUserId();
7263 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7264 configuration, currentUserId, Settings.System.canWrite(mContext));
7265 updateConfigurationLocked(configuration, null /* starting */,
7266 false /* initLocale */, false /* persistent */, currentUserId,
7267 false /* deferResume */);
7268 }
7269 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007270
7271 @Override
7272 public boolean canShowErrorDialogs() {
7273 synchronized (mGlobalLock) {
7274 return mShowDialogs && !mSleeping && !mShuttingDown
7275 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7276 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7277 mAmInternal.getCurrentUserId())
7278 && !(UserManager.isDeviceInDemoMode(mContext)
7279 && mAmInternal.getCurrentUser().isDemo());
7280 }
7281 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007282
7283 @Override
7284 public void setProfileApp(String profileApp) {
7285 synchronized (mGlobalLock) {
7286 mProfileApp = profileApp;
7287 }
7288 }
7289
7290 @Override
7291 public void setProfileProc(WindowProcessController wpc) {
7292 synchronized (mGlobalLock) {
7293 mProfileProc = wpc;
7294 }
7295 }
7296
7297 @Override
7298 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7299 synchronized (mGlobalLock) {
7300 mProfilerInfo = profilerInfo;
7301 }
7302 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007303
7304 @Override
7305 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7306 synchronized (mGlobalLock) {
7307 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7308 }
7309 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007310
7311 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007312 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7313 boolean reducedResolution) {
7314 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7315 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007316 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007317
7318 @Override
7319 public boolean isUidForeground(int uid) {
7320 synchronized (mGlobalLock) {
7321 return ActivityTaskManagerService.this.isUidForeground(uid);
7322 }
7323 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007324
7325 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007326 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007327 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007328 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007329 }
7330 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007331
7332 @Override
7333 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007334 // Translate package names into UIDs
7335 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007336 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007337 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7338 if (uid >= 0) {
7339 result.add(uid);
7340 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007341 }
7342 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007343 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007344 }
7345 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007346 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007347}